Sat Mar 26 11:07:25 2011

Asterisk developer's documentation


channel.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Channel Management
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 291581 $")
00029 
00030 #include "asterisk/_private.h"
00031 
00032 #include <sys/time.h>
00033 #include <signal.h>
00034 #include <math.h>
00035 
00036 #include "asterisk/paths.h"   /* use ast_config_AST_SYSTEM_NAME */
00037 
00038 #include "asterisk/pbx.h"
00039 #include "asterisk/frame.h"
00040 #include "asterisk/mod_format.h"
00041 #include "asterisk/sched.h"
00042 #include "asterisk/channel.h"
00043 #include "asterisk/musiconhold.h"
00044 #include "asterisk/say.h"
00045 #include "asterisk/file.h"
00046 #include "asterisk/cli.h"
00047 #include "asterisk/translate.h"
00048 #include "asterisk/manager.h"
00049 #include "asterisk/cel.h"
00050 #include "asterisk/chanvars.h"
00051 #include "asterisk/linkedlists.h"
00052 #include "asterisk/indications.h"
00053 #include "asterisk/monitor.h"
00054 #include "asterisk/causes.h"
00055 #include "asterisk/callerid.h"
00056 #include "asterisk/utils.h"
00057 #include "asterisk/lock.h"
00058 #include "asterisk/app.h"
00059 #include "asterisk/transcap.h"
00060 #include "asterisk/devicestate.h"
00061 #include "asterisk/sha1.h"
00062 #include "asterisk/threadstorage.h"
00063 #include "asterisk/slinfactory.h"
00064 #include "asterisk/audiohook.h"
00065 #include "asterisk/framehook.h"
00066 #include "asterisk/timing.h"
00067 #include "asterisk/autochan.h"
00068 #include "asterisk/stringfields.h"
00069 #include "asterisk/global_datastores.h"
00070 #include "asterisk/data.h"
00071 
00072 #ifdef HAVE_EPOLL
00073 #include <sys/epoll.h>
00074 #endif
00075 
00076 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00077 #if defined(HAVE_PRI)
00078 #include "libpri.h"
00079 #endif   /* defined(HAVE_PRI) */
00080 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00081 
00082 struct ast_epoll_data {
00083    struct ast_channel *chan;
00084    int which;
00085 };
00086 
00087 /* uncomment if you have problems with 'monitoring' synchronized files */
00088 #if 0
00089 #define MONITOR_CONSTANT_DELAY
00090 #define MONITOR_DELAY   150 * 8     /*!< 150 ms of MONITORING DELAY */
00091 #endif
00092 
00093 /*! \brief Prevent new channel allocation if shutting down. */
00094 static int shutting_down;
00095 
00096 static int uniqueint;
00097 
00098 unsigned long global_fin, global_fout;
00099 
00100 AST_THREADSTORAGE(state2str_threadbuf);
00101 #define STATE2STR_BUFSIZE   32
00102 
00103 /*! Default amount of time to use when emulating a digit as a begin and end 
00104  *  100ms */
00105 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
00106 
00107 /*! Minimum allowed digit length - 80ms */
00108 #define AST_MIN_DTMF_DURATION 80
00109 
00110 /*! Minimum amount of time between the end of the last digit and the beginning 
00111  *  of a new one - 45ms */
00112 #define AST_MIN_DTMF_GAP 45
00113 
00114 /*! \brief List of channel drivers */
00115 struct chanlist {
00116    const struct ast_channel_tech *tech;
00117    AST_LIST_ENTRY(chanlist) list;
00118 };
00119 
00120 #ifdef CHANNEL_TRACE
00121 /*! \brief Structure to hold channel context backtrace data */
00122 struct ast_chan_trace_data {
00123    int enabled;
00124    AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
00125 };
00126 
00127 /*! \brief Structure to save contexts where an ast_chan has been into */
00128 struct ast_chan_trace {
00129    char context[AST_MAX_CONTEXT];
00130    char exten[AST_MAX_EXTENSION];
00131    int priority;
00132    AST_LIST_ENTRY(ast_chan_trace) entry;
00133 };
00134 #endif
00135 
00136 /*! \brief the list of registered channel types */
00137 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
00138 
00139 #ifdef LOW_MEMORY
00140 #define NUM_CHANNEL_BUCKETS 61
00141 #else
00142 #define NUM_CHANNEL_BUCKETS 1567
00143 #endif
00144 
00145 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
00146 #define DATA_EXPORT_CALLERID(MEMBER)            \
00147    MEMBER(ast_callerid, cid_dnid, AST_DATA_STRING)    \
00148    MEMBER(ast_callerid, cid_num, AST_DATA_STRING)     \
00149    MEMBER(ast_callerid, cid_name, AST_DATA_STRING)    \
00150    MEMBER(ast_callerid, cid_ani, AST_DATA_STRING)     \
00151    MEMBER(ast_callerid, cid_pres, AST_DATA_INTEGER)   \
00152    MEMBER(ast_callerid, cid_ani2, AST_DATA_INTEGER)   \
00153    MEMBER(ast_callerid, cid_tag, AST_DATA_STRING)
00154 
00155 AST_DATA_STRUCTURE(ast_callerid, DATA_EXPORT_CALLERID);
00156 #endif
00157 
00158 #define DATA_EXPORT_CHANNEL(MEMBER)                \
00159    MEMBER(ast_channel, blockproc, AST_DATA_STRING)          \
00160    MEMBER(ast_channel, appl, AST_DATA_STRING)            \
00161    MEMBER(ast_channel, data, AST_DATA_STRING)            \
00162    MEMBER(ast_channel, name, AST_DATA_STRING)            \
00163    MEMBER(ast_channel, language, AST_DATA_STRING)           \
00164    MEMBER(ast_channel, musicclass, AST_DATA_STRING)         \
00165    MEMBER(ast_channel, accountcode, AST_DATA_STRING)        \
00166    MEMBER(ast_channel, peeraccount, AST_DATA_STRING)        \
00167    MEMBER(ast_channel, userfield, AST_DATA_STRING)          \
00168    MEMBER(ast_channel, call_forward, AST_DATA_STRING)       \
00169    MEMBER(ast_channel, uniqueid, AST_DATA_STRING)           \
00170    MEMBER(ast_channel, linkedid, AST_DATA_STRING)           \
00171    MEMBER(ast_channel, parkinglot, AST_DATA_STRING)         \
00172    MEMBER(ast_channel, hangupsource, AST_DATA_STRING)       \
00173    MEMBER(ast_channel, dialcontext, AST_DATA_STRING)        \
00174    MEMBER(ast_channel, rings, AST_DATA_INTEGER)          \
00175    MEMBER(ast_channel, priority, AST_DATA_INTEGER)          \
00176    MEMBER(ast_channel, macropriority, AST_DATA_INTEGER)        \
00177    MEMBER(ast_channel, adsicpe, AST_DATA_INTEGER)           \
00178    MEMBER(ast_channel, fin, AST_DATA_UNSIGNED_INTEGER)         \
00179    MEMBER(ast_channel, fout, AST_DATA_UNSIGNED_INTEGER)        \
00180    MEMBER(ast_channel, emulate_dtmf_duration, AST_DATA_UNSIGNED_INTEGER)   \
00181    MEMBER(ast_channel, visible_indication, AST_DATA_INTEGER)      \
00182    MEMBER(ast_channel, context, AST_DATA_STRING)            \
00183    MEMBER(ast_channel, exten, AST_DATA_STRING)           \
00184    MEMBER(ast_channel, macrocontext, AST_DATA_STRING)       \
00185    MEMBER(ast_channel, macroexten, AST_DATA_STRING)
00186 
00187 AST_DATA_STRUCTURE(ast_channel, DATA_EXPORT_CHANNEL);
00188 
00189 
00190 /*! \brief All active channels on the system */
00191 static struct ao2_container *channels;
00192 
00193 /*! \brief map AST_CAUSE's to readable string representations 
00194  *
00195  * \ref causes.h
00196 */
00197 static const struct {
00198    int cause;
00199    const char *name;
00200    const char *desc;
00201 } causes[] = {
00202    { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
00203    { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
00204    { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
00205    { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
00206    { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
00207    { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
00208    { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
00209    { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
00210    { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
00211    { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
00212    { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
00213    { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
00214    { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
00215    { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
00216    { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
00217    { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
00218    { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
00219    { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
00220    { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
00221    { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
00222    { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
00223    { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
00224    { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
00225    { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
00226    { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
00227    { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
00228    { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
00229    { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
00230    { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
00231    { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
00232    { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
00233    { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
00234    { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
00235    { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
00236    { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
00237    { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
00238    { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
00239    { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
00240    { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
00241    { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
00242    { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
00243    { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
00244    { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
00245    { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
00246 };
00247 
00248 struct ast_variable *ast_channeltype_list(void)
00249 {
00250    struct chanlist *cl;
00251    struct ast_variable *var = NULL, *prev = NULL;
00252 
00253    AST_RWLIST_RDLOCK(&backends);
00254    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00255       if (prev)  {
00256          if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
00257             prev = prev->next;
00258       } else {
00259          var = ast_variable_new(cl->tech->type, cl->tech->description, "");
00260          prev = var;
00261       }
00262    }
00263    AST_RWLIST_UNLOCK(&backends);
00264 
00265    return var;
00266 }
00267 
00268 static void channel_data_add_flags(struct ast_data *tree,
00269    struct ast_channel *chan)
00270 {
00271    ast_data_add_bool(tree, "DEFER_DTMF", ast_test_flag(chan, AST_FLAG_DEFER_DTMF));
00272    ast_data_add_bool(tree, "WRITE_INT", ast_test_flag(chan, AST_FLAG_WRITE_INT));
00273    ast_data_add_bool(tree, "BLOCKING", ast_test_flag(chan, AST_FLAG_BLOCKING));
00274    ast_data_add_bool(tree, "ZOMBIE", ast_test_flag(chan, AST_FLAG_ZOMBIE));
00275    ast_data_add_bool(tree, "EXCEPTION", ast_test_flag(chan, AST_FLAG_EXCEPTION));
00276    ast_data_add_bool(tree, "MOH", ast_test_flag(chan, AST_FLAG_MOH));
00277    ast_data_add_bool(tree, "SPYING", ast_test_flag(chan, AST_FLAG_SPYING));
00278    ast_data_add_bool(tree, "NBRIDGE", ast_test_flag(chan, AST_FLAG_NBRIDGE));
00279    ast_data_add_bool(tree, "IN_AUTOLOOP", ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP));
00280    ast_data_add_bool(tree, "OUTGOING", ast_test_flag(chan, AST_FLAG_OUTGOING));
00281    ast_data_add_bool(tree, "IN_DTMF", ast_test_flag(chan, AST_FLAG_IN_DTMF));
00282    ast_data_add_bool(tree, "EMULATE_DTMF", ast_test_flag(chan, AST_FLAG_EMULATE_DTMF));
00283    ast_data_add_bool(tree, "END_DTMF_ONLY", ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY));
00284    ast_data_add_bool(tree, "ANSWERED_ELSEWHERE", ast_test_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE));
00285    ast_data_add_bool(tree, "MASQ_NOSTREAM", ast_test_flag(chan, AST_FLAG_MASQ_NOSTREAM));
00286    ast_data_add_bool(tree, "BRIDGE_HANGUP_RUN", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN));
00287    ast_data_add_bool(tree, "BRIDGE_HANGUP_DONT", ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT));
00288    ast_data_add_bool(tree, "DISABLE_WORKAROUNDS", ast_test_flag(chan, AST_FLAG_DISABLE_WORKAROUNDS));
00289 }
00290 
00291 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00292 static const char *party_number_ton2str(int ton)
00293 {
00294 #if defined(HAVE_PRI)
00295    switch ((ton >> 4) & 0x07) {
00296    case PRI_TON_INTERNATIONAL:
00297       return "International";
00298    case PRI_TON_NATIONAL:
00299       return "National";
00300    case PRI_TON_NET_SPECIFIC:
00301       return "Network Specific";
00302    case PRI_TON_SUBSCRIBER:
00303       return "Subscriber";
00304    case PRI_TON_ABBREVIATED:
00305       return "Abbreviated";
00306    case PRI_TON_RESERVED:
00307       return "Reserved";
00308    case PRI_TON_UNKNOWN:
00309    default:
00310       break;
00311    }
00312 #endif   /* defined(HAVE_PRI) */
00313    return "Unknown";
00314 }
00315 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00316 
00317 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00318 static const char *party_number_plan2str(int plan)
00319 {
00320 #if defined(HAVE_PRI)
00321    switch (plan & 0x0F) {
00322    default:
00323    case PRI_NPI_UNKNOWN:
00324       break;
00325    case PRI_NPI_E163_E164:
00326       return "Public (E.163/E.164)";
00327    case PRI_NPI_X121:
00328       return "Data (X.121)";
00329    case PRI_NPI_F69:
00330       return "Telex (F.69)";
00331    case PRI_NPI_NATIONAL:
00332       return "National Standard";
00333    case PRI_NPI_PRIVATE:
00334       return "Private";
00335    case PRI_NPI_RESERVED:
00336       return "Reserved";
00337    }
00338 #endif   /* defined(HAVE_PRI) */
00339    return "Unknown";
00340 }
00341 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00342 
00343 int ast_channel_data_add_structure(struct ast_data *tree,
00344    struct ast_channel *chan, int add_bridged)
00345 {
00346    struct ast_channel *bc;
00347    struct ast_data *data_bridged;
00348    struct ast_data *data_cdr;
00349    struct ast_data *data_flags;
00350    struct ast_data *data_zones;
00351    struct ast_data *enum_node;
00352    struct ast_data *data_softhangup;
00353 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
00354    struct ast_data *data_callerid;
00355    char value_str[100];
00356 #endif
00357 
00358    if (!tree) {
00359       return -1;
00360    }
00361 
00362    ast_data_add_structure(ast_channel, tree, chan);
00363 
00364    if (add_bridged) {
00365       bc = ast_bridged_channel(chan);
00366       if (bc) {
00367          data_bridged = ast_data_add_node(tree, "bridged");
00368          if (!data_bridged) {
00369             return -1;
00370          }
00371          ast_channel_data_add_structure(data_bridged, bc, 0);
00372       }
00373    }
00374 
00375    ast_data_add_codecs(tree, "oldwriteformat", chan->oldwriteformat);
00376    ast_data_add_codecs(tree, "nativeformats", chan->nativeformats);
00377    ast_data_add_codecs(tree, "readformat", chan->readformat);
00378    ast_data_add_codecs(tree, "writeformat", chan->writeformat);
00379    ast_data_add_codecs(tree, "rawreadformat", chan->rawreadformat);
00380    ast_data_add_codecs(tree, "rawwriteformat", chan->rawwriteformat);
00381 
00382    /* state */
00383    enum_node = ast_data_add_node(tree, "state");
00384    if (!enum_node) {
00385       return -1;
00386    }
00387    ast_data_add_str(enum_node, "text", ast_state2str(chan->_state));
00388    ast_data_add_int(enum_node, "value", chan->_state);
00389 
00390    /* hangupcause */
00391    enum_node = ast_data_add_node(tree, "hangupcause");
00392    if (!enum_node) {
00393       return -1;
00394    }
00395    ast_data_add_str(enum_node, "text", ast_cause2str(chan->hangupcause));
00396    ast_data_add_int(enum_node, "value", chan->hangupcause);
00397 
00398    /* amaflags */
00399    enum_node = ast_data_add_node(tree, "amaflags");
00400    if (!enum_node) {
00401       return -1;
00402    }
00403    ast_data_add_str(enum_node, "text", ast_cdr_flags2str(chan->amaflags));
00404    ast_data_add_int(enum_node, "value", chan->amaflags);
00405 
00406    /* transfercapability */
00407    enum_node = ast_data_add_node(tree, "transfercapability");
00408    if (!enum_node) {
00409       return -1;
00410    }
00411    ast_data_add_str(enum_node, "text", ast_transfercapability2str(chan->transfercapability));
00412    ast_data_add_int(enum_node, "value", chan->transfercapability);
00413 
00414    /* _softphangup */
00415    data_softhangup = ast_data_add_node(tree, "softhangup");
00416    if (!data_softhangup) {
00417       return -1;
00418    }
00419    ast_data_add_bool(data_softhangup, "dev", chan->_softhangup & AST_SOFTHANGUP_DEV);
00420    ast_data_add_bool(data_softhangup, "asyncgoto", chan->_softhangup & AST_SOFTHANGUP_ASYNCGOTO);
00421    ast_data_add_bool(data_softhangup, "shutdown", chan->_softhangup & AST_SOFTHANGUP_SHUTDOWN);
00422    ast_data_add_bool(data_softhangup, "timeout", chan->_softhangup & AST_SOFTHANGUP_TIMEOUT);
00423    ast_data_add_bool(data_softhangup, "appunload", chan->_softhangup & AST_SOFTHANGUP_APPUNLOAD);
00424    ast_data_add_bool(data_softhangup, "explicit", chan->_softhangup & AST_SOFTHANGUP_EXPLICIT);
00425    ast_data_add_bool(data_softhangup, "unbridge", chan->_softhangup & AST_SOFTHANGUP_UNBRIDGE);
00426 
00427    /* channel flags */
00428    data_flags = ast_data_add_node(tree, "flags");
00429    if (!data_flags) {
00430       return -1;
00431    }
00432    channel_data_add_flags(data_flags, chan);
00433 
00434    ast_data_add_uint(tree, "timetohangup", chan->whentohangup.tv_sec);
00435 
00436 #if 0 /* XXX AstData: ast_callerid no longer exists. (Equivalent code not readily apparent.) */
00437    /* callerid */
00438    data_callerid = ast_data_add_node(tree, "callerid");
00439    if (!data_callerid) {
00440       return -1;
00441    }
00442    ast_data_add_structure(ast_callerid, data_callerid, &(chan->cid));
00443    /* insert the callerid ton */
00444    enum_node = ast_data_add_node(data_callerid, "cid_ton");
00445    if (!enum_node) {
00446       return -1;
00447    }
00448    ast_data_add_int(enum_node, "value", chan->cid.cid_ton);
00449    snprintf(value_str, sizeof(value_str), "TON: %s/Plan: %s",
00450       party_number_ton2str(chan->cid.cid_ton),
00451       party_number_plan2str(chan->cid.cid_ton));
00452    ast_data_add_str(enum_node, "text", value_str);
00453 #endif
00454 
00455    /* tone zone */
00456    if (chan->zone) {
00457       data_zones = ast_data_add_node(tree, "zone");
00458       if (!data_zones) {
00459          return -1;
00460       }
00461       ast_tone_zone_data_add_structure(data_zones, chan->zone);
00462    }
00463 
00464    /* insert cdr */
00465    data_cdr = ast_data_add_node(tree, "cdr");
00466    if (!data_cdr) {
00467       return -1;
00468    }
00469 
00470    ast_cdr_data_add_structure(data_cdr, chan->cdr, 1);
00471 
00472    return 0;
00473 }
00474 
00475 int ast_channel_data_cmp_structure(const struct ast_data_search *tree,
00476    struct ast_channel *chan, const char *structure_name)
00477 {
00478    return ast_data_search_cmp_structure(tree, ast_channel, chan, structure_name);
00479 }
00480 
00481 /*! \brief Show channel types - CLI command */
00482 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00483 {
00484 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
00485    struct chanlist *cl;
00486    int count_chan = 0;
00487 
00488    switch (cmd) {
00489    case CLI_INIT:
00490       e->command = "core show channeltypes";
00491       e->usage =
00492          "Usage: core show channeltypes\n"
00493          "       Lists available channel types registered in your\n"
00494          "       Asterisk server.\n";
00495       return NULL;
00496    case CLI_GENERATE:
00497       return NULL;
00498    }
00499 
00500    if (a->argc != 3)
00501       return CLI_SHOWUSAGE;
00502 
00503    ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
00504    ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
00505 
00506    AST_RWLIST_RDLOCK(&backends);
00507    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00508       ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
00509          (cl->tech->devicestate) ? "yes" : "no",
00510          (cl->tech->indicate) ? "yes" : "no",
00511          (cl->tech->transfer) ? "yes" : "no");
00512       count_chan++;
00513    }
00514    AST_RWLIST_UNLOCK(&backends);
00515 
00516    ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
00517 
00518    return CLI_SUCCESS;
00519 
00520 #undef FORMAT
00521 }
00522 
00523 static char *complete_channeltypes(struct ast_cli_args *a)
00524 {
00525    struct chanlist *cl;
00526    int which = 0;
00527    int wordlen;
00528    char *ret = NULL;
00529 
00530    if (a->pos != 3)
00531       return NULL;
00532 
00533    wordlen = strlen(a->word);
00534 
00535    AST_RWLIST_RDLOCK(&backends);
00536    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00537       if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
00538          ret = ast_strdup(cl->tech->type);
00539          break;
00540       }
00541    }
00542    AST_RWLIST_UNLOCK(&backends);
00543    
00544    return ret;
00545 }
00546 
00547 /*! \brief Show details about a channel driver - CLI command */
00548 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00549 {
00550    struct chanlist *cl = NULL;
00551    char buf[512];
00552 
00553    switch (cmd) {
00554    case CLI_INIT:
00555       e->command = "core show channeltype";
00556       e->usage =
00557          "Usage: core show channeltype <name>\n"
00558          "  Show details about the specified channel type, <name>.\n";
00559       return NULL;
00560    case CLI_GENERATE:
00561       return complete_channeltypes(a);
00562    }
00563 
00564    if (a->argc != 4)
00565       return CLI_SHOWUSAGE;
00566    
00567    AST_RWLIST_RDLOCK(&backends);
00568 
00569    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00570       if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
00571          break;
00572    }
00573 
00574 
00575    if (!cl) {
00576       ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
00577       AST_RWLIST_UNLOCK(&backends);
00578       return CLI_FAILURE;
00579    }
00580 
00581    ast_cli(a->fd,
00582       "-- Info about channel driver: %s --\n"
00583       "  Device State: %s\n"
00584       "    Indication: %s\n"
00585       "     Transfer : %s\n"
00586       "  Capabilities: %s\n"
00587       "   Digit Begin: %s\n"
00588       "     Digit End: %s\n"
00589       "    Send HTML : %s\n"
00590       " Image Support: %s\n"
00591       "  Text Support: %s\n",
00592       cl->tech->type,
00593       (cl->tech->devicestate) ? "yes" : "no",
00594       (cl->tech->indicate) ? "yes" : "no",
00595       (cl->tech->transfer) ? "yes" : "no",
00596       ast_getformatname_multiple(buf, sizeof(buf), (cl->tech->capabilities) ? cl->tech->capabilities : -1),
00597       (cl->tech->send_digit_begin) ? "yes" : "no",
00598       (cl->tech->send_digit_end) ? "yes" : "no",
00599       (cl->tech->send_html) ? "yes" : "no",
00600       (cl->tech->send_image) ? "yes" : "no",
00601       (cl->tech->send_text) ? "yes" : "no"
00602       
00603    );
00604 
00605    AST_RWLIST_UNLOCK(&backends);
00606 
00607    return CLI_SUCCESS;
00608 }
00609 
00610 static struct ast_cli_entry cli_channel[] = {
00611    AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
00612    AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
00613 };
00614 
00615 #ifdef CHANNEL_TRACE
00616 /*! \brief Destructor for the channel trace datastore */
00617 static void ast_chan_trace_destroy_cb(void *data)
00618 {
00619    struct ast_chan_trace *trace;
00620    struct ast_chan_trace_data *traced = data;
00621    while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
00622       ast_free(trace);
00623    }
00624    ast_free(traced);
00625 }
00626 
00627 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
00628 static const struct ast_datastore_info ast_chan_trace_datastore_info = {
00629    .type = "ChanTrace",
00630    .destroy = ast_chan_trace_destroy_cb
00631 };
00632 
00633 /*! \brief Put the channel backtrace in a string */
00634 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
00635 {
00636    int total = 0;
00637    struct ast_chan_trace *trace;
00638    struct ast_chan_trace_data *traced;
00639    struct ast_datastore *store;
00640 
00641    ast_channel_lock(chan);
00642    store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00643    if (!store) {
00644       ast_channel_unlock(chan);
00645       return total;
00646    }
00647    traced = store->data;
00648    ast_str_reset(*buf);
00649    AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
00650       if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
00651          ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
00652          total = -1;
00653          break;
00654       }
00655       total++;
00656    }
00657    ast_channel_unlock(chan);
00658    return total;
00659 }
00660 
00661 /* !\brief Whether or not context tracing is enabled */
00662 int ast_channel_trace_is_enabled(struct ast_channel *chan)
00663 {
00664    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00665    if (!store)
00666       return 0;
00667    return ((struct ast_chan_trace_data *)store->data)->enabled;
00668 }
00669 
00670 /*! \brief Update the context backtrace data if tracing is enabled */
00671 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
00672 {
00673    struct ast_chan_trace *trace;
00674    if (!traced->enabled)
00675       return 0;
00676    /* If the last saved context does not match the current one
00677       OR we have not saved any context so far, then save the current context */
00678    if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
00679        (AST_LIST_EMPTY(&traced->trace))) {
00680       /* Just do some debug logging */
00681       if (AST_LIST_EMPTY(&traced->trace))
00682          ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
00683       else
00684          ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
00685       /* alloc or bail out */
00686       trace = ast_malloc(sizeof(*trace));
00687       if (!trace) 
00688          return -1;
00689       /* save the current location and store it in the trace list */
00690       ast_copy_string(trace->context, chan->context, sizeof(trace->context));
00691       ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
00692       trace->priority = chan->priority;
00693       AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
00694    }
00695    return 0;
00696 }
00697 
00698 /*! \brief Update the context backtrace if tracing is enabled */
00699 int ast_channel_trace_update(struct ast_channel *chan)
00700 {
00701    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00702    if (!store)
00703       return 0;
00704    return ast_channel_trace_data_update(chan, store->data);
00705 }
00706 
00707 /*! \brief Enable context tracing in the channel */
00708 int ast_channel_trace_enable(struct ast_channel *chan)
00709 {
00710    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00711    struct ast_chan_trace_data *traced;
00712    if (!store) {
00713       store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
00714       if (!store) 
00715          return -1;
00716       traced = ast_calloc(1, sizeof(*traced));
00717       if (!traced) {
00718          ast_datastore_free(store);
00719          return -1;
00720       }  
00721       store->data = traced;
00722       AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
00723       ast_channel_datastore_add(chan, store);
00724    }  
00725    ((struct ast_chan_trace_data *)store->data)->enabled = 1;
00726    ast_channel_trace_data_update(chan, store->data);
00727    return 0;
00728 }
00729 
00730 /*! \brief Disable context tracing in the channel */
00731 int ast_channel_trace_disable(struct ast_channel *chan)
00732 {
00733    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00734    if (!store)
00735       return 0;
00736    ((struct ast_chan_trace_data *)store->data)->enabled = 0;
00737    return 0;
00738 }
00739 #endif /* CHANNEL_TRACE */
00740 
00741 /*! \brief Checks to see if a channel is needing hang up */
00742 int ast_check_hangup(struct ast_channel *chan)
00743 {
00744    if (chan->_softhangup)     /* yes if soft hangup flag set */
00745       return 1;
00746    if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
00747       return 0;
00748    if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0)  /* no if hangup time has not come yet. */
00749       return 0;
00750    ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(chan->whentohangup, ast_tvnow()));
00751    chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
00752    return 1;
00753 }
00754 
00755 int ast_check_hangup_locked(struct ast_channel *chan)
00756 {
00757    int res;
00758    ast_channel_lock(chan);
00759    res = ast_check_hangup(chan);
00760    ast_channel_unlock(chan);
00761    return res;
00762 }
00763 
00764 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
00765 {
00766    struct ast_channel *chan = obj;
00767 
00768    ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
00769 
00770    return 0;
00771 }
00772 
00773 void ast_begin_shutdown(int hangup)
00774 {
00775    shutting_down = 1;
00776 
00777    if (hangup) {
00778       ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
00779    }
00780 }
00781 
00782 /*! \brief returns number of active/allocated channels */
00783 int ast_active_channels(void)
00784 {
00785    return channels ? ao2_container_count(channels) : 0;
00786 }
00787 
00788 /*! \brief Cancel a shutdown in progress */
00789 void ast_cancel_shutdown(void)
00790 {
00791    shutting_down = 0;
00792 }
00793 
00794 /*! \brief Returns non-zero if Asterisk is being shut down */
00795 int ast_shutting_down(void)
00796 {
00797    return shutting_down;
00798 }
00799 
00800 /*! \brief Set when to hangup channel */
00801 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00802 {
00803    chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
00804    ast_queue_frame(chan, &ast_null_frame);
00805    return;
00806 }
00807 
00808 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
00809 {
00810    struct timeval when = { offset, };
00811    ast_channel_setwhentohangup_tv(chan, when);
00812 }
00813 
00814 /*! \brief Compare a offset with when to hangup channel */
00815 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00816 {
00817    struct timeval whentohangup;
00818 
00819    if (ast_tvzero(chan->whentohangup))
00820       return ast_tvzero(offset) ? 0 : -1;
00821 
00822    if (ast_tvzero(offset))
00823       return 1;
00824 
00825    whentohangup = ast_tvadd(offset, ast_tvnow());
00826 
00827    return ast_tvdiff_ms(whentohangup, chan->whentohangup);
00828 }
00829 
00830 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
00831 {
00832    struct timeval when = { offset, };
00833    return ast_channel_cmpwhentohangup_tv(chan, when);
00834 }
00835 
00836 /*! \brief Register a new telephony channel in Asterisk */
00837 int ast_channel_register(const struct ast_channel_tech *tech)
00838 {
00839    struct chanlist *chan;
00840 
00841    AST_RWLIST_WRLOCK(&backends);
00842 
00843    AST_RWLIST_TRAVERSE(&backends, chan, list) {
00844       if (!strcasecmp(tech->type, chan->tech->type)) {
00845          ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
00846          AST_RWLIST_UNLOCK(&backends);
00847          return -1;
00848       }
00849    }
00850    
00851    if (!(chan = ast_calloc(1, sizeof(*chan)))) {
00852       AST_RWLIST_UNLOCK(&backends);
00853       return -1;
00854    }
00855    chan->tech = tech;
00856    AST_RWLIST_INSERT_HEAD(&backends, chan, list);
00857 
00858    ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
00859 
00860    ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
00861 
00862    AST_RWLIST_UNLOCK(&backends);
00863 
00864    return 0;
00865 }
00866 
00867 /*! \brief Unregister channel driver */
00868 void ast_channel_unregister(const struct ast_channel_tech *tech)
00869 {
00870    struct chanlist *chan;
00871 
00872    ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
00873 
00874    AST_RWLIST_WRLOCK(&backends);
00875 
00876    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
00877       if (chan->tech == tech) {
00878          AST_LIST_REMOVE_CURRENT(list);
00879          ast_free(chan);
00880          ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
00881          break;   
00882       }
00883    }
00884    AST_LIST_TRAVERSE_SAFE_END;
00885 
00886    AST_RWLIST_UNLOCK(&backends);
00887 }
00888 
00889 /*! \brief Get handle to channel driver based on name */
00890 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
00891 {
00892    struct chanlist *chanls;
00893    const struct ast_channel_tech *ret = NULL;
00894 
00895    AST_RWLIST_RDLOCK(&backends);
00896 
00897    AST_RWLIST_TRAVERSE(&backends, chanls, list) {
00898       if (!strcasecmp(name, chanls->tech->type)) {
00899          ret = chanls->tech;
00900          break;
00901       }
00902    }
00903 
00904    AST_RWLIST_UNLOCK(&backends);
00905    
00906    return ret;
00907 }
00908 
00909 /*! \brief Gives the string form of a given hangup cause */
00910 const char *ast_cause2str(int cause)
00911 {
00912    int x;
00913 
00914    for (x = 0; x < ARRAY_LEN(causes); x++) {
00915       if (causes[x].cause == cause)
00916          return causes[x].desc;
00917    }
00918 
00919    return "Unknown";
00920 }
00921 
00922 /*! \brief Convert a symbolic hangup cause to number */
00923 int ast_str2cause(const char *name)
00924 {
00925    int x;
00926 
00927    for (x = 0; x < ARRAY_LEN(causes); x++)
00928       if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
00929          return causes[x].cause;
00930 
00931    return -1;
00932 }
00933 
00934 /*! \brief Gives the string form of a given channel state.
00935    \note This function is not reentrant.
00936  */
00937 const char *ast_state2str(enum ast_channel_state state)
00938 {
00939    char *buf;
00940 
00941    switch (state) {
00942    case AST_STATE_DOWN:
00943       return "Down";
00944    case AST_STATE_RESERVED:
00945       return "Rsrvd";
00946    case AST_STATE_OFFHOOK:
00947       return "OffHook";
00948    case AST_STATE_DIALING:
00949       return "Dialing";
00950    case AST_STATE_RING:
00951       return "Ring";
00952    case AST_STATE_RINGING:
00953       return "Ringing";
00954    case AST_STATE_UP:
00955       return "Up";
00956    case AST_STATE_BUSY:
00957       return "Busy";
00958    case AST_STATE_DIALING_OFFHOOK:
00959       return "Dialing Offhook";
00960    case AST_STATE_PRERING:
00961       return "Pre-ring";
00962    default:
00963       if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
00964          return "Unknown";
00965       snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
00966       return buf;
00967    }
00968 }
00969 
00970 /*! \brief Gives the string form of a given transfer capability */
00971 char *ast_transfercapability2str(int transfercapability)
00972 {
00973    switch (transfercapability) {
00974    case AST_TRANS_CAP_SPEECH:
00975       return "SPEECH";
00976    case AST_TRANS_CAP_DIGITAL:
00977       return "DIGITAL";
00978    case AST_TRANS_CAP_RESTRICTED_DIGITAL:
00979       return "RESTRICTED_DIGITAL";
00980    case AST_TRANS_CAP_3_1K_AUDIO:
00981       return "3K1AUDIO";
00982    case AST_TRANS_CAP_DIGITAL_W_TONES:
00983       return "DIGITAL_W_TONES";
00984    case AST_TRANS_CAP_VIDEO:
00985       return "VIDEO";
00986    default:
00987       return "UNKNOWN";
00988    }
00989 }
00990 
00991 /*! \brief Pick the best audio codec */
00992 format_t ast_best_codec(format_t fmts)
00993 {
00994    /* This just our opinion, expressed in code.  We are asked to choose
00995       the best codec to use, given no information */
00996    int x;
00997    static const format_t prefs[] =
00998    {
00999       /*! Okay, ulaw is used by all telephony equipment, so start with it */
01000       AST_FORMAT_ULAW,
01001       /*! Unless of course, you're a silly European, so then prefer ALAW */
01002       AST_FORMAT_ALAW,
01003       AST_FORMAT_G719,
01004       AST_FORMAT_SIREN14,
01005       AST_FORMAT_SIREN7,
01006       AST_FORMAT_TESTLAW,
01007       /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
01008       AST_FORMAT_G722,
01009       /*! Okay, well, signed linear is easy to translate into other stuff */
01010       AST_FORMAT_SLINEAR16,
01011       AST_FORMAT_SLINEAR,
01012       /*! G.726 is standard ADPCM, in RFC3551 packing order */
01013       AST_FORMAT_G726,
01014       /*! G.726 is standard ADPCM, in AAL2 packing order */
01015       AST_FORMAT_G726_AAL2,
01016       /*! ADPCM has great sound quality and is still pretty easy to translate */
01017       AST_FORMAT_ADPCM,
01018       /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
01019           translate and sounds pretty good */
01020       AST_FORMAT_GSM,
01021       /*! iLBC is not too bad */
01022       AST_FORMAT_ILBC,
01023       /*! Speex is free, but computationally more expensive than GSM */
01024       AST_FORMAT_SPEEX16,
01025       AST_FORMAT_SPEEX,
01026       /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
01027           to use it */
01028       AST_FORMAT_LPC10,
01029       /*! G.729a is faster than 723 and slightly less expensive */
01030       AST_FORMAT_G729A,
01031       /*! Down to G.723.1 which is proprietary but at least designed for voice */
01032       AST_FORMAT_G723_1,
01033    };
01034    char buf[512];
01035 
01036    /* Strip out video */
01037    fmts &= AST_FORMAT_AUDIO_MASK;
01038    
01039    /* Find the first preferred codec in the format given */
01040    for (x = 0; x < ARRAY_LEN(prefs); x++) {
01041       if (fmts & prefs[x])
01042          return prefs[x];
01043    }
01044 
01045    ast_log(LOG_WARNING, "Don't know any of %s formats\n", ast_getformatname_multiple(buf, sizeof(buf), fmts));
01046 
01047    return 0;
01048 }
01049 
01050 static const struct ast_channel_tech null_tech = {
01051    .type = "NULL",
01052    .description = "Null channel (should not see this)",
01053 };
01054 
01055 static void ast_channel_destructor(void *obj);
01056 static void ast_dummy_channel_destructor(void *obj);
01057 
01058 /*! \brief Create a new channel structure */
01059 static struct ast_channel * attribute_malloc __attribute__((format(printf, 13, 0)))
01060 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
01061              const char *acctcode, const char *exten, const char *context,
01062              const char *linkedid, const int amaflag, const char *file, int line,
01063              const char *function, const char *name_fmt, va_list ap1, va_list ap2)
01064 {
01065    struct ast_channel *tmp;
01066    int x;
01067    int flags;
01068    struct varshead *headp;
01069    char *tech = "", *tech2 = NULL;
01070 
01071    /* If shutting down, don't allocate any new channels */
01072    if (shutting_down) {
01073       ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
01074       return NULL;
01075    }
01076 
01077 #if defined(REF_DEBUG)
01078    tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
01079       function, 1);
01080 #elif defined(__AST_DEBUG_MALLOC)
01081    tmp = __ao2_alloc_debug(sizeof(*tmp), ast_channel_destructor, "", file, line,
01082       function, 0);
01083 #else
01084    tmp = ao2_alloc(sizeof(*tmp), ast_channel_destructor);
01085 #endif
01086    if (!tmp) {
01087       /* Channel structure allocation failure. */
01088       return NULL;
01089    }
01090 
01091    /*
01092     * Init file descriptors to unopened state so
01093     * the destructor can know not to close them.
01094     */
01095    tmp->timingfd = -1;
01096    for (x = 0; x < ARRAY_LEN(tmp->alertpipe); ++x) {
01097       tmp->alertpipe[x] = -1;
01098    }
01099    for (x = 0; x < ARRAY_LEN(tmp->fds); ++x) {
01100       tmp->fds[x] = -1;
01101    }
01102 #ifdef HAVE_EPOLL
01103    tmp->epfd = epoll_create(25);
01104 #endif
01105 
01106    if (!(tmp->sched = sched_context_create())) {
01107       ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
01108       return ast_channel_unref(tmp);
01109    }
01110    
01111    ast_party_dialed_init(&tmp->dialed);
01112    ast_party_caller_init(&tmp->caller);
01113    ast_party_connected_line_init(&tmp->connected);
01114    ast_party_redirecting_init(&tmp->redirecting);
01115 
01116    if (cid_name) {
01117       tmp->caller.id.name.valid = 1;
01118       tmp->caller.id.name.str = ast_strdup(cid_name);
01119       if (!tmp->caller.id.name.str) {
01120          return ast_channel_unref(tmp);
01121       }
01122    }
01123    if (cid_num) {
01124       tmp->caller.id.number.valid = 1;
01125       tmp->caller.id.number.str = ast_strdup(cid_num);
01126       if (!tmp->caller.id.number.str) {
01127          return ast_channel_unref(tmp);
01128       }
01129    }
01130 
01131    if ((tmp->timer = ast_timer_open())) {
01132       needqueue = 0;
01133       tmp->timingfd = ast_timer_fd(tmp->timer);
01134    }
01135 
01136    if (needqueue) {
01137       if (pipe(tmp->alertpipe)) {
01138          ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
01139          return ast_channel_unref(tmp);
01140       } else {
01141          flags = fcntl(tmp->alertpipe[0], F_GETFL);
01142          if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
01143             ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
01144             return ast_channel_unref(tmp);
01145          }
01146          flags = fcntl(tmp->alertpipe[1], F_GETFL);
01147          if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
01148             ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
01149             return ast_channel_unref(tmp);
01150          }
01151       }
01152    }
01153 
01154    /*
01155     * This is the last place the channel constructor can fail.
01156     *
01157     * The destructor takes advantage of this fact to ensure that the
01158     * AST_CEL_CHANNEL_END is not posted if we have not posted the
01159     * AST_CEL_CHANNEL_START yet.
01160     */
01161    if ((ast_string_field_init(tmp, 128))) {
01162       return ast_channel_unref(tmp);
01163    }
01164 
01165    /* Always watch the alertpipe */
01166    ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
01167    /* And timing pipe */
01168    ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
01169 
01170    /* Initial state */
01171    tmp->_state = state;
01172 
01173    tmp->streamid = -1;
01174    
01175    tmp->fin = global_fin;
01176    tmp->fout = global_fout;
01177 
01178    if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
01179       ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
01180          ast_atomic_fetchadd_int(&uniqueint, 1));
01181    } else {
01182       ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
01183          (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
01184    }
01185 
01186    if (!ast_strlen_zero(linkedid)) {
01187       ast_string_field_set(tmp, linkedid, linkedid);
01188    } else {
01189       ast_string_field_set(tmp, linkedid, tmp->uniqueid);
01190    }
01191 
01192    if (!ast_strlen_zero(name_fmt)) {
01193       char *slash, *slash2;
01194       /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
01195        * And they all use slightly different formats for their name string.
01196        * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
01197        * This means, that the stringfields must have a routine that takes the va_lists directly, and 
01198        * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
01199        * This new function was written so this can be accomplished.
01200        */
01201       ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
01202       tech = ast_strdupa(tmp->name);
01203       if ((slash = strchr(tech, '/'))) {
01204          if ((slash2 = strchr(slash + 1, '/'))) {
01205             tech2 = slash + 1;
01206             *slash2 = '\0';
01207          }
01208          *slash = '\0';
01209       }
01210    } else {
01211       /*
01212        * Start the string with '-' so it becomes an empty string
01213        * in the destructor.
01214        */
01215       ast_string_field_set(tmp, name, "-**Unknown**");
01216    }
01217 
01218    /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
01219 
01220    /* These 4 variables need to be set up for the cdr_init() to work right */
01221    if (amaflag)
01222       tmp->amaflags = amaflag;
01223    else
01224       tmp->amaflags = ast_default_amaflags;
01225    
01226    if (!ast_strlen_zero(acctcode))
01227       ast_string_field_set(tmp, accountcode, acctcode);
01228    else
01229       ast_string_field_set(tmp, accountcode, ast_default_accountcode);
01230       
01231    if (!ast_strlen_zero(context))
01232       ast_copy_string(tmp->context, context, sizeof(tmp->context));
01233    else
01234       strcpy(tmp->context, "default");
01235 
01236    if (!ast_strlen_zero(exten))
01237       ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
01238    else
01239       strcpy(tmp->exten, "s");
01240 
01241    tmp->priority = 1;
01242 
01243    tmp->cdr = ast_cdr_alloc();
01244    ast_cdr_init(tmp->cdr, tmp);
01245    ast_cdr_start(tmp->cdr);
01246 
01247    ast_cel_report_event(tmp, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
01248 
01249    headp = &tmp->varshead;
01250    AST_LIST_HEAD_INIT_NOLOCK(headp);
01251    
01252    AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
01253 
01254    AST_LIST_HEAD_INIT_NOLOCK(&tmp->autochans);
01255    
01256    ast_string_field_set(tmp, language, defaultlanguage);
01257 
01258    tmp->tech = &null_tech;
01259 
01260    ao2_link(channels, tmp);
01261 
01262    /*
01263     * And now, since the channel structure is built, and has its name, let's
01264     * call the manager event generator with this Newchannel event. This is the
01265     * proper and correct place to make this call, but you sure do have to pass
01266     * a lot of data into this func to do it here!
01267     */
01268    if (ast_get_channel_tech(tech) || (tech2 && ast_get_channel_tech(tech2))) {
01269       ast_manager_event(tmp, EVENT_FLAG_CALL, "Newchannel",
01270          "Channel: %s\r\n"
01271          "ChannelState: %d\r\n"
01272          "ChannelStateDesc: %s\r\n"
01273          "CallerIDNum: %s\r\n"
01274          "CallerIDName: %s\r\n"
01275          "AccountCode: %s\r\n"
01276          "Exten: %s\r\n"
01277          "Context: %s\r\n"
01278          "Uniqueid: %s\r\n",
01279          tmp->name, 
01280          state, 
01281          ast_state2str(state),
01282          S_OR(cid_num, ""),
01283          S_OR(cid_name, ""),
01284          tmp->accountcode,
01285          S_OR(exten, ""),
01286          S_OR(context, ""),
01287          tmp->uniqueid);
01288    }
01289 
01290    return tmp;
01291 }
01292 
01293 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
01294                const char *cid_name, const char *acctcode,
01295                const char *exten, const char *context,
01296                const char *linkedid, const int amaflag,
01297                const char *file, int line, const char *function,
01298                const char *name_fmt, ...)
01299 {
01300    va_list ap1, ap2;
01301    struct ast_channel *result;
01302 
01303    va_start(ap1, name_fmt);
01304    va_start(ap2, name_fmt);
01305    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
01306                linkedid, amaflag, file, line, function, name_fmt, ap1, ap2);
01307    va_end(ap1);
01308    va_end(ap2);
01309 
01310    return result;
01311 }
01312 
01313 /* only do the minimum amount of work needed here to make a channel
01314  * structure that can be used to expand channel vars */
01315 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
01316 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
01317 #else
01318 struct ast_channel *ast_dummy_channel_alloc(void)
01319 #endif
01320 {
01321    struct ast_channel *tmp;
01322    struct varshead *headp;
01323 
01324 #if defined(REF_DEBUG)
01325    tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
01326       file, line, function, 1);
01327 #elif defined(__AST_DEBUG_MALLOC)
01328    tmp = __ao2_alloc_debug(sizeof(*tmp), ast_dummy_channel_destructor, "dummy channel",
01329       file, line, function, 0);
01330 #else
01331    tmp = ao2_alloc(sizeof(*tmp), ast_dummy_channel_destructor);
01332 #endif
01333    if (!tmp) {
01334       /* Dummy channel structure allocation failure. */
01335       return NULL;
01336    }
01337 
01338    if ((ast_string_field_init(tmp, 128))) {
01339       return ast_channel_unref(tmp);
01340    }
01341 
01342    headp = &tmp->varshead;
01343    AST_LIST_HEAD_INIT_NOLOCK(headp);
01344 
01345    return tmp;
01346 }
01347 
01348 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
01349 {
01350    struct ast_frame *f;
01351    struct ast_frame *cur;
01352    int blah = 1;
01353    unsigned int new_frames = 0;
01354    unsigned int new_voice_frames = 0;
01355    unsigned int queued_frames = 0;
01356    unsigned int queued_voice_frames = 0;
01357    AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
01358 
01359    ast_channel_lock(chan);
01360 
01361    /* See if the last frame on the queue is a hangup, if so don't queue anything */
01362    if ((cur = AST_LIST_LAST(&chan->readq)) &&
01363        (cur->frametype == AST_FRAME_CONTROL) &&
01364        (cur->subclass.integer == AST_CONTROL_HANGUP)) {
01365       ast_channel_unlock(chan);
01366       return 0;
01367    }
01368 
01369    /* Build copies of all the frames and count them */
01370    AST_LIST_HEAD_INIT_NOLOCK(&frames);
01371    for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
01372       if (!(f = ast_frdup(cur))) {
01373          if (AST_LIST_FIRST(&frames)) {
01374             ast_frfree(AST_LIST_FIRST(&frames));
01375          }
01376          ast_channel_unlock(chan);
01377          return -1;
01378       }
01379 
01380       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01381       new_frames++;
01382       if (f->frametype == AST_FRAME_VOICE) {
01383          new_voice_frames++;
01384       }
01385    }
01386 
01387    /* Count how many frames exist on the queue */
01388    AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
01389       queued_frames++;
01390       if (cur->frametype == AST_FRAME_VOICE) {
01391          queued_voice_frames++;
01392       }
01393    }
01394 
01395    if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
01396       int count = 0;
01397       ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
01398       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
01399          /* Save the most recent frame */
01400          if (!AST_LIST_NEXT(cur, frame_list)) {
01401             break;
01402          } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
01403             if (++count > 64) {
01404                break;
01405             }
01406             AST_LIST_REMOVE_CURRENT(frame_list);
01407             ast_frfree(cur);
01408          }
01409       }
01410       AST_LIST_TRAVERSE_SAFE_END;
01411    }
01412 
01413    if (after) {
01414       AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
01415    } else {
01416       if (head) {
01417          AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
01418          AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
01419       }
01420       AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
01421    }
01422 
01423    if (chan->alertpipe[1] > -1) {
01424       if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
01425          ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
01426             chan->name, queued_frames, strerror(errno));
01427       }
01428    } else if (chan->timingfd > -1) {
01429       ast_timer_enable_continuous(chan->timer);
01430    } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
01431       pthread_kill(chan->blocker, SIGURG);
01432    }
01433 
01434    ast_channel_unlock(chan);
01435 
01436    return 0;
01437 }
01438 
01439 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
01440 {
01441    return __ast_queue_frame(chan, fin, 0, NULL);
01442 }
01443 
01444 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
01445 {
01446    return __ast_queue_frame(chan, fin, 1, NULL);
01447 }
01448 
01449 /*! \brief Queue a hangup frame for channel */
01450 int ast_queue_hangup(struct ast_channel *chan)
01451 {
01452    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
01453    /* Yeah, let's not change a lock-critical value without locking */
01454    if (!ast_channel_trylock(chan)) {
01455       chan->_softhangup |= AST_SOFTHANGUP_DEV;
01456       ast_channel_unlock(chan);
01457    }
01458    return ast_queue_frame(chan, &f);
01459 }
01460 
01461 /*! \brief Queue a hangup frame for channel */
01462 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
01463 {
01464    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
01465 
01466    if (cause >= 0)
01467       f.data.uint32 = cause;
01468 
01469    /* Yeah, let's not change a lock-critical value without locking */
01470    if (!ast_channel_trylock(chan)) {
01471       chan->_softhangup |= AST_SOFTHANGUP_DEV;
01472       if (cause < 0)
01473          f.data.uint32 = chan->hangupcause;
01474 
01475       ast_channel_unlock(chan);
01476    }
01477 
01478    return ast_queue_frame(chan, &f);
01479 }
01480 
01481 /*! \brief Queue a control frame */
01482 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
01483 {
01484    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
01485    return ast_queue_frame(chan, &f);
01486 }
01487 
01488 /*! \brief Queue a control frame with payload */
01489 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
01490             const void *data, size_t datalen)
01491 {
01492    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
01493    return ast_queue_frame(chan, &f);
01494 }
01495 
01496 /*! \brief Set defer DTMF flag on channel */
01497 int ast_channel_defer_dtmf(struct ast_channel *chan)
01498 {
01499    int pre = 0;
01500 
01501    if (chan) {
01502       pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
01503       ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
01504    }
01505    return pre;
01506 }
01507 
01508 /*! \brief Unset defer DTMF flag on channel */
01509 void ast_channel_undefer_dtmf(struct ast_channel *chan)
01510 {
01511    if (chan)
01512       ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
01513 }
01514 
01515 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
01516       void *data, int ao2_flags)
01517 {
01518    return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
01519 }
01520 
01521 struct ast_channel_iterator {
01522    /* storage for non-dynamically allocated iterator */
01523    struct ao2_iterator simple_iterator;
01524    /* pointer to the actual iterator (simple_iterator or a dynamically
01525     * allocated iterator)
01526     */
01527    struct ao2_iterator *active_iterator;
01528 };
01529 
01530 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
01531 {
01532    ao2_iterator_destroy(i->active_iterator);
01533    ast_free(i);
01534 
01535    return NULL;
01536 }
01537 
01538 static struct ast_channel_iterator *channel_iterator_search(const char *name,
01539                          size_t name_len, const char *exten,
01540                          const char *context)
01541 {
01542    struct ast_channel_iterator *i;
01543    struct ast_channel tmp_chan = {
01544       .name = name,
01545       /* This is sort of a hack.  Basically, we're using an arbitrary field
01546        * in ast_channel to pass the name_len for a prefix match.  If this
01547        * gets changed, then the compare callback must be changed, too. */
01548       .rings = name_len,
01549    };
01550 
01551    if (!(i = ast_calloc(1, sizeof(*i)))) {
01552       return NULL;
01553    }
01554 
01555    if (exten) {
01556       ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
01557    }
01558 
01559    if (context) {
01560       ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
01561    }
01562 
01563    if (!(i->active_iterator = ao2_find(channels, &tmp_chan,
01564                    OBJ_MULTIPLE | ((!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0)))) {
01565           ast_free(i);
01566           return NULL;
01567    }
01568 
01569    return i;
01570 }
01571 
01572 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
01573 {
01574    return channel_iterator_search(NULL, 0, exten, context);
01575 }
01576 
01577 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
01578 {
01579    return channel_iterator_search(name, name_len, NULL, NULL);
01580 }
01581 
01582 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
01583 {
01584    struct ast_channel_iterator *i;
01585 
01586    if (!(i = ast_calloc(1, sizeof(*i)))) {
01587       return NULL;
01588    }
01589 
01590    i->simple_iterator = ao2_iterator_init(channels, 0);
01591    i->active_iterator = &i->simple_iterator;
01592 
01593    return i;
01594 }
01595 
01596 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
01597 {
01598    return ao2_iterator_next(i->active_iterator);
01599 }
01600 
01601 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
01602 {
01603    struct ast_channel *chan = obj, *cmp_args = arg;
01604    size_t name_len;
01605    int ret = CMP_MATCH;
01606 
01607    /* This is sort of a hack.  Basically, we're using an arbitrary field
01608     * in ast_channel to pass the name_len for a prefix match.  If this
01609     * gets changed, then the uses of ao2_find() must be changed, too. */
01610    name_len = cmp_args->rings;
01611 
01612    ast_channel_lock(chan);
01613 
01614    if (!ast_strlen_zero(cmp_args->name)) { /* match by name */
01615       if ((!name_len && strcasecmp(chan->name, cmp_args->name)) ||
01616             (name_len && strncasecmp(chan->name, cmp_args->name, name_len))) {
01617          ret = 0; /* name match failed */
01618       }
01619    } else if (!ast_strlen_zero(cmp_args->exten)) {
01620       if (cmp_args->context && strcasecmp(chan->context, cmp_args->context) &&
01621             strcasecmp(chan->macrocontext, cmp_args->context)) {
01622          ret = 0; /* context match failed */
01623       }
01624       if (ret && strcasecmp(chan->exten, cmp_args->exten) &&
01625             strcasecmp(chan->macroexten, cmp_args->exten)) {
01626          ret = 0; /* exten match failed */
01627       }
01628    } else if (!ast_strlen_zero(cmp_args->uniqueid)) {
01629       if ((!name_len && strcasecmp(chan->uniqueid, cmp_args->uniqueid)) ||
01630             (name_len && strncasecmp(chan->uniqueid, cmp_args->uniqueid, name_len))) {
01631          ret = 0; /* uniqueid match failed */
01632       }
01633    } else {
01634       ret = 0;
01635    }
01636 
01637    ast_channel_unlock(chan);
01638 
01639    return ret;
01640 }
01641 
01642 static struct ast_channel *ast_channel_get_full(const char *name, size_t name_len,
01643                   const char *exten, const char *context)
01644 {
01645    struct ast_channel tmp_chan = {
01646       .name = name,
01647       /* This is sort of a hack.  Basically, we're using an arbitrary field
01648        * in ast_channel to pass the name_len for a prefix match.  If this
01649        * gets changed, then the compare callback must be changed, too. */
01650       .rings = name_len,
01651    };
01652    struct ast_channel *chan;
01653 
01654    if (exten) {
01655       ast_copy_string(tmp_chan.exten, exten, sizeof(tmp_chan.exten));
01656    }
01657 
01658    if (context) {
01659       ast_copy_string(tmp_chan.context, context, sizeof(tmp_chan.context));
01660    }
01661 
01662    if ((chan = ao2_find(channels, &tmp_chan,
01663               (!ast_strlen_zero(name) && (name_len == 0)) ? OBJ_POINTER : 0))) {
01664       return chan;
01665    }
01666 
01667    if (!name) {
01668       return NULL;
01669    }
01670 
01671    /* If name was specified, but the result was NULL, 
01672     * try a search on uniqueid, instead. */
01673 
01674    {
01675       struct ast_channel tmp_chan2 = {
01676          .uniqueid = name,
01677          .rings = name_len,
01678       };
01679 
01680       return ao2_find(channels, &tmp_chan2, 0);
01681    }
01682 }
01683 
01684 struct ast_channel *ast_channel_get_by_name(const char *name)
01685 {
01686    return ast_channel_get_full(name, 0, NULL, NULL);
01687 }
01688 
01689 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
01690 {
01691    return ast_channel_get_full(name, name_len, NULL, NULL);
01692 }
01693 
01694 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
01695 {
01696    return ast_channel_get_full(NULL, 0, exten, context);
01697 }
01698 
01699 int ast_is_deferrable_frame(const struct ast_frame *frame)
01700 {
01701    /* Do not add a default entry in this switch statement.  Each new
01702     * frame type should be addressed directly as to whether it should
01703     * be queued up or not.
01704     */
01705    switch (frame->frametype) {
01706    case AST_FRAME_DTMF_END:
01707    case AST_FRAME_CONTROL:
01708    case AST_FRAME_TEXT:
01709    case AST_FRAME_IMAGE:
01710    case AST_FRAME_HTML:
01711       return 1;
01712 
01713    case AST_FRAME_DTMF_BEGIN:
01714    case AST_FRAME_VOICE:
01715    case AST_FRAME_VIDEO:
01716    case AST_FRAME_NULL:
01717    case AST_FRAME_IAX:
01718    case AST_FRAME_CNG:
01719    case AST_FRAME_MODEM:
01720       return 0;
01721    }
01722    return 0;
01723 }
01724 
01725 /*! \brief Wait, look for hangups and condition arg */
01726 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
01727 {
01728    struct ast_frame *f;
01729    struct ast_silence_generator *silgen = NULL;
01730    int res = 0;
01731    AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
01732 
01733    AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
01734 
01735    /* If no other generator is present, start silencegen while waiting */
01736    if (ast_opt_transmit_silence && !chan->generatordata) {
01737       silgen = ast_channel_start_silence_generator(chan);
01738    }
01739 
01740    while (ms > 0) {
01741       struct ast_frame *dup_f = NULL;
01742       if (cond && ((*cond)(data) == 0)) {
01743          break;
01744       }
01745       ms = ast_waitfor(chan, ms);
01746       if (ms < 0) {
01747          res = -1;
01748          break;
01749       }
01750       if (ms > 0) {
01751          f = ast_read(chan);
01752          if (!f) {
01753             res = -1;
01754             break;
01755          }
01756 
01757          if (!ast_is_deferrable_frame(f)) {
01758             ast_frfree(f);
01759             continue;
01760          }
01761          
01762          if ((dup_f = ast_frisolate(f))) {
01763             if (dup_f != f) {
01764                ast_frfree(f);
01765             }
01766             AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
01767          }
01768       }
01769    }
01770 
01771    /* stop silgen if present */
01772    if (silgen) {
01773       ast_channel_stop_silence_generator(chan, silgen);
01774    }
01775 
01776    /* We need to free all the deferred frames, but we only need to
01777     * queue the deferred frames if there was no error and no
01778     * hangup was received
01779     */
01780    ast_channel_lock(chan);
01781    while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
01782       if (!res) {
01783          ast_queue_frame_head(chan, f);
01784       }
01785       ast_frfree(f);
01786    }
01787    ast_channel_unlock(chan);
01788 
01789    return res;
01790 }
01791 
01792 /*! \brief Wait, look for hangups */
01793 int ast_safe_sleep(struct ast_channel *chan, int ms)
01794 {
01795    return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
01796 }
01797 
01798 struct ast_channel *ast_channel_release(struct ast_channel *chan)
01799 {
01800    /* Safe, even if already unlinked. */
01801    ao2_unlink(channels, chan);
01802    return ast_channel_unref(chan);
01803 }
01804 
01805 void ast_party_name_init(struct ast_party_name *init)
01806 {
01807    init->str = NULL;
01808    init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
01809    init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
01810    init->valid = 0;
01811 }
01812 
01813 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
01814 {
01815    if (dest == src) {
01816       /* Don't copy to self */
01817       return;
01818    }
01819 
01820    ast_free(dest->str);
01821    dest->str = ast_strdup(src->str);
01822    dest->char_set = src->char_set;
01823    dest->presentation = src->presentation;
01824    dest->valid = src->valid;
01825 }
01826 
01827 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
01828 {
01829    init->str = NULL;
01830    init->char_set = guide->char_set;
01831    init->presentation = guide->presentation;
01832    init->valid = guide->valid;
01833 }
01834 
01835 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
01836 {
01837    if (dest == src) {
01838       /* Don't set to self */
01839       return;
01840    }
01841 
01842    if (src->str && src->str != dest->str) {
01843       ast_free(dest->str);
01844       dest->str = ast_strdup(src->str);
01845    }
01846 
01847    dest->char_set = src->char_set;
01848    dest->presentation = src->presentation;
01849    dest->valid = src->valid;
01850 }
01851 
01852 void ast_party_name_free(struct ast_party_name *doomed)
01853 {
01854    ast_free(doomed->str);
01855    doomed->str = NULL;
01856 }
01857 
01858 void ast_party_number_init(struct ast_party_number *init)
01859 {
01860    init->str = NULL;
01861    init->plan = 0;/* Unknown */
01862    init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
01863    init->valid = 0;
01864 }
01865 
01866 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
01867 {
01868    if (dest == src) {
01869       /* Don't copy to self */
01870       return;
01871    }
01872 
01873    ast_free(dest->str);
01874    dest->str = ast_strdup(src->str);
01875    dest->plan = src->plan;
01876    dest->presentation = src->presentation;
01877    dest->valid = src->valid;
01878 }
01879 
01880 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
01881 {
01882    init->str = NULL;
01883    init->plan = guide->plan;
01884    init->presentation = guide->presentation;
01885    init->valid = guide->valid;
01886 }
01887 
01888 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
01889 {
01890    if (dest == src) {
01891       /* Don't set to self */
01892       return;
01893    }
01894 
01895    if (src->str && src->str != dest->str) {
01896       ast_free(dest->str);
01897       dest->str = ast_strdup(src->str);
01898    }
01899 
01900    dest->plan = src->plan;
01901    dest->presentation = src->presentation;
01902    dest->valid = src->valid;
01903 }
01904 
01905 void ast_party_number_free(struct ast_party_number *doomed)
01906 {
01907    ast_free(doomed->str);
01908    doomed->str = NULL;
01909 }
01910 
01911 void ast_party_subaddress_init(struct ast_party_subaddress *init)
01912 {
01913    init->str = NULL;
01914    init->type = 0;
01915    init->odd_even_indicator = 0;
01916    init->valid = 0;
01917 }
01918 
01919 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
01920 {
01921    if (dest == src) {
01922       /* Don't copy to self */
01923       return;
01924    }
01925 
01926    ast_free(dest->str);
01927    dest->str = ast_strdup(src->str);
01928    dest->type = src->type;
01929    dest->odd_even_indicator = src->odd_even_indicator;
01930    dest->valid = src->valid;
01931 }
01932 
01933 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
01934 {
01935    init->str = NULL;
01936    init->type = guide->type;
01937    init->odd_even_indicator = guide->odd_even_indicator;
01938    init->valid = guide->valid;
01939 }
01940 
01941 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
01942 {
01943    if (dest == src) {
01944       /* Don't set to self */
01945       return;
01946    }
01947 
01948    if (src->str && src->str != dest->str) {
01949       ast_free(dest->str);
01950       dest->str = ast_strdup(src->str);
01951    }
01952 
01953    dest->type = src->type;
01954    dest->odd_even_indicator = src->odd_even_indicator;
01955    dest->valid = src->valid;
01956 }
01957 
01958 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
01959 {
01960    ast_free(doomed->str);
01961    doomed->str = NULL;
01962 }
01963 
01964 void ast_party_id_init(struct ast_party_id *init)
01965 {
01966    ast_party_name_init(&init->name);
01967    ast_party_number_init(&init->number);
01968    ast_party_subaddress_init(&init->subaddress);
01969    init->tag = NULL;
01970 }
01971 
01972 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
01973 {
01974    if (dest == src) {
01975       /* Don't copy to self */
01976       return;
01977    }
01978 
01979    ast_party_name_copy(&dest->name, &src->name);
01980    ast_party_number_copy(&dest->number, &src->number);
01981    ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
01982 
01983    ast_free(dest->tag);
01984    dest->tag = ast_strdup(src->tag);
01985 }
01986 
01987 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
01988 {
01989    ast_party_name_set_init(&init->name, &guide->name);
01990    ast_party_number_set_init(&init->number, &guide->number);
01991    ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
01992    init->tag = NULL;
01993 }
01994 
01995 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
01996 {
01997    if (dest == src) {
01998       /* Don't set to self */
01999       return;
02000    }
02001 
02002    if (!update || update->name) {
02003       ast_party_name_set(&dest->name, &src->name);
02004    }
02005    if (!update || update->number) {
02006       ast_party_number_set(&dest->number, &src->number);
02007    }
02008    if (!update || update->subaddress) {
02009       ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
02010    }
02011 
02012    if (src->tag && src->tag != dest->tag) {
02013       ast_free(dest->tag);
02014       dest->tag = ast_strdup(src->tag);
02015    }
02016 }
02017 
02018 void ast_party_id_free(struct ast_party_id *doomed)
02019 {
02020    ast_party_name_free(&doomed->name);
02021    ast_party_number_free(&doomed->number);
02022    ast_party_subaddress_free(&doomed->subaddress);
02023 
02024    ast_free(doomed->tag);
02025    doomed->tag = NULL;
02026 }
02027 
02028 int ast_party_id_presentation(const struct ast_party_id *id)
02029 {
02030    int number_priority;
02031    int number_value;
02032    int number_screening;
02033    int name_priority;
02034    int name_value;
02035 
02036    /* Determine name presentation priority. */
02037    if (!id->name.valid) {
02038       name_value = AST_PRES_UNAVAILABLE;
02039       name_priority = 3;
02040    } else {
02041       name_value = id->name.presentation & AST_PRES_RESTRICTION;
02042       switch (name_value) {
02043       case AST_PRES_RESTRICTED:
02044          name_priority = 0;
02045          break;
02046       case AST_PRES_ALLOWED:
02047          name_priority = 1;
02048          break;
02049       case AST_PRES_UNAVAILABLE:
02050          name_priority = 2;
02051          break;
02052       default:
02053          name_value = AST_PRES_UNAVAILABLE;
02054          name_priority = 3;
02055          break;
02056       }
02057    }
02058 
02059    /* Determine number presentation priority. */
02060    if (!id->number.valid) {
02061       number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
02062       number_value = AST_PRES_UNAVAILABLE;
02063       number_priority = 3;
02064    } else {
02065       number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
02066       number_value = id->number.presentation & AST_PRES_RESTRICTION;
02067       switch (number_value) {
02068       case AST_PRES_RESTRICTED:
02069          number_priority = 0;
02070          break;
02071       case AST_PRES_ALLOWED:
02072          number_priority = 1;
02073          break;
02074       case AST_PRES_UNAVAILABLE:
02075          number_priority = 2;
02076          break;
02077       default:
02078          number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
02079          number_value = AST_PRES_UNAVAILABLE;
02080          number_priority = 3;
02081          break;
02082       }
02083    }
02084 
02085    /* Select the wining presentation value. */
02086    if (name_priority < number_priority) {
02087       number_value = name_value;
02088    }
02089 
02090    return number_value | number_screening;
02091 }
02092 
02093 void ast_party_dialed_init(struct ast_party_dialed *init)
02094 {
02095    init->number.str = NULL;
02096    init->number.plan = 0;/* Unknown */
02097    ast_party_subaddress_init(&init->subaddress);
02098    init->transit_network_select = 0;
02099 }
02100 
02101 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
02102 {
02103    if (dest == src) {
02104       /* Don't copy to self */
02105       return;
02106    }
02107 
02108    ast_free(dest->number.str);
02109    dest->number.str = ast_strdup(src->number.str);
02110    dest->number.plan = src->number.plan;
02111    ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
02112    dest->transit_network_select = src->transit_network_select;
02113 }
02114 
02115 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
02116 {
02117    init->number.str = NULL;
02118    init->number.plan = guide->number.plan;
02119    ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
02120    init->transit_network_select = guide->transit_network_select;
02121 }
02122 
02123 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
02124 {
02125    if (src->number.str && src->number.str != dest->number.str) {
02126       ast_free(dest->number.str);
02127       dest->number.str = ast_strdup(src->number.str);
02128    }
02129    dest->number.plan = src->number.plan;
02130 
02131    ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
02132 
02133    dest->transit_network_select = src->transit_network_select;
02134 }
02135 
02136 void ast_party_dialed_free(struct ast_party_dialed *doomed)
02137 {
02138    ast_free(doomed->number.str);
02139    doomed->number.str = NULL;
02140    ast_party_subaddress_free(&doomed->subaddress);
02141 }
02142 
02143 void ast_party_caller_init(struct ast_party_caller *init)
02144 {
02145    ast_party_id_init(&init->id);
02146    ast_party_id_init(&init->ani);
02147    init->ani2 = 0;
02148 }
02149 
02150 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
02151 {
02152    if (dest == src) {
02153       /* Don't copy to self */
02154       return;
02155    }
02156 
02157    ast_party_id_copy(&dest->id, &src->id);
02158    ast_party_id_copy(&dest->ani, &src->ani);
02159    dest->ani2 = src->ani2;
02160 }
02161 
02162 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
02163 {
02164    ast_party_id_set_init(&init->id, &guide->id);
02165    ast_party_id_set_init(&init->ani, &guide->ani);
02166    init->ani2 = guide->ani2;
02167 }
02168 
02169 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
02170 {
02171    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
02172    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
02173    dest->ani2 = src->ani2;
02174 }
02175 
02176 void ast_party_caller_free(struct ast_party_caller *doomed)
02177 {
02178    ast_party_id_free(&doomed->id);
02179    ast_party_id_free(&doomed->ani);
02180 }
02181 
02182 void ast_party_connected_line_init(struct ast_party_connected_line *init)
02183 {
02184    ast_party_id_init(&init->id);
02185    ast_party_id_init(&init->ani);
02186    init->ani2 = 0;
02187    init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02188 }
02189 
02190 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
02191 {
02192    if (dest == src) {
02193       /* Don't copy to self */
02194       return;
02195    }
02196 
02197    ast_party_id_copy(&dest->id, &src->id);
02198    ast_party_id_copy(&dest->ani, &src->ani);
02199    dest->ani2 = src->ani2;
02200    dest->source = src->source;
02201 }
02202 
02203 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
02204 {
02205    ast_party_id_set_init(&init->id, &guide->id);
02206    ast_party_id_set_init(&init->ani, &guide->ani);
02207    init->ani2 = guide->ani2;
02208    init->source = guide->source;
02209 }
02210 
02211 void ast_party_connected_line_set(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src, const struct ast_set_party_connected_line *update)
02212 {
02213    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
02214    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
02215    dest->ani2 = src->ani2;
02216    dest->source = src->source;
02217 }
02218 
02219 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
02220 {
02221    connected->id = caller->id;
02222    connected->ani = caller->ani;
02223    connected->ani2 = caller->ani2;
02224    connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02225 }
02226 
02227 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
02228 {
02229    ast_party_id_free(&doomed->id);
02230    ast_party_id_free(&doomed->ani);
02231 }
02232 
02233 void ast_party_redirecting_init(struct ast_party_redirecting *init)
02234 {
02235    ast_party_id_init(&init->from);
02236    ast_party_id_init(&init->to);
02237    init->count = 0;
02238    init->reason = AST_REDIRECTING_REASON_UNKNOWN;
02239 }
02240 
02241 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
02242 {
02243    if (dest == src) {
02244       /* Don't copy to self */
02245       return;
02246    }
02247 
02248    ast_party_id_copy(&dest->from, &src->from);
02249    ast_party_id_copy(&dest->to, &src->to);
02250    dest->count = src->count;
02251    dest->reason = src->reason;
02252 }
02253 
02254 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
02255 {
02256    ast_party_id_set_init(&init->from, &guide->from);
02257    ast_party_id_set_init(&init->to, &guide->to);
02258    init->count = guide->count;
02259    init->reason = guide->reason;
02260 }
02261 
02262 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
02263 {
02264    ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
02265    ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
02266    dest->reason = src->reason;
02267    dest->count = src->count;
02268 }
02269 
02270 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
02271 {
02272    ast_party_id_free(&doomed->from);
02273    ast_party_id_free(&doomed->to);
02274 }
02275 
02276 /*! \brief Free a channel structure */
02277 static void ast_channel_destructor(void *obj)
02278 {
02279    struct ast_channel *chan = obj;
02280    int fd;
02281 #ifdef HAVE_EPOLL
02282    int i;
02283 #endif
02284    struct ast_var_t *vardata;
02285    struct ast_frame *f;
02286    struct varshead *headp;
02287    struct ast_datastore *datastore;
02288    char device_name[AST_CHANNEL_NAME];
02289 
02290    if (chan->name) {
02291       /* The string fields were initialized. */
02292       ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
02293       ast_cel_check_retire_linkedid(chan);
02294    }
02295 
02296    /* Get rid of each of the data stores on the channel */
02297    ast_channel_lock(chan);
02298    while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
02299       /* Free the data store */
02300       ast_datastore_free(datastore);
02301    ast_channel_unlock(chan);
02302 
02303    /* Lock and unlock the channel just to be sure nobody has it locked still
02304       due to a reference that was stored in a datastore. (i.e. app_chanspy) */
02305    ast_channel_lock(chan);
02306    ast_channel_unlock(chan);
02307 
02308    if (chan->tech_pvt) {
02309       ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
02310       ast_free(chan->tech_pvt);
02311    }
02312 
02313    if (chan->sched)
02314       sched_context_destroy(chan->sched);
02315 
02316    if (chan->name) {
02317       char *dashptr;
02318 
02319       /* The string fields were initialized. */
02320       ast_copy_string(device_name, chan->name, sizeof(device_name));
02321       if ((dashptr = strrchr(device_name, '-'))) {
02322          *dashptr = '\0';
02323       }
02324    } else {
02325       device_name[0] = '\0';
02326    }
02327 
02328    /* Stop monitoring */
02329    if (chan->monitor)
02330       chan->monitor->stop( chan, 0 );
02331 
02332    /* If there is native format music-on-hold state, free it */
02333    if (chan->music_state)
02334       ast_moh_cleanup(chan);
02335 
02336    /* Free translators */
02337    if (chan->readtrans)
02338       ast_translator_free_path(chan->readtrans);
02339    if (chan->writetrans)
02340       ast_translator_free_path(chan->writetrans);
02341    if (chan->pbx)
02342       ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
02343 
02344    ast_party_dialed_free(&chan->dialed);
02345    ast_party_caller_free(&chan->caller);
02346    ast_party_connected_line_free(&chan->connected);
02347    ast_party_redirecting_free(&chan->redirecting);
02348 
02349    /* Close pipes if appropriate */
02350    if ((fd = chan->alertpipe[0]) > -1)
02351       close(fd);
02352    if ((fd = chan->alertpipe[1]) > -1)
02353       close(fd);
02354    if (chan->timer) {
02355       ast_timer_close(chan->timer);
02356    }
02357 #ifdef HAVE_EPOLL
02358    for (i = 0; i < AST_MAX_FDS; i++) {
02359       if (chan->epfd_data[i])
02360          free(chan->epfd_data[i]);
02361    }
02362    close(chan->epfd);
02363 #endif
02364    while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
02365       ast_frfree(f);
02366    
02367    /* loop over the variables list, freeing all data and deleting list items */
02368    /* no need to lock the list, as the channel is already locked */
02369    headp = &chan->varshead;
02370    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02371       ast_var_delete(vardata);
02372 
02373    ast_app_group_discard(chan);
02374 
02375    /* Destroy the jitterbuffer */
02376    ast_jb_destroy(chan);
02377 
02378    if (chan->cdr) {
02379       ast_cdr_discard(chan->cdr);
02380       chan->cdr = NULL;
02381    }
02382 
02383    if (chan->zone) {
02384       chan->zone = ast_tone_zone_unref(chan->zone);
02385    }
02386 
02387    ast_string_field_free_memory(chan);
02388 
02389    if (device_name[0]) {
02390       /*
02391        * We have a device name to notify of a new state.
02392        *
02393        * Queue an unknown state, because, while we know that this particular
02394        * instance is dead, we don't know the state of all other possible
02395        * instances.
02396        */
02397       ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
02398    }
02399 }
02400 
02401 /*! \brief Free a dummy channel structure */
02402 static void ast_dummy_channel_destructor(void *obj)
02403 {
02404    struct ast_channel *chan = obj;
02405    struct ast_var_t *vardata;
02406    struct varshead *headp;
02407 
02408    headp = &chan->varshead;
02409 
02410    ast_party_dialed_free(&chan->dialed);
02411    ast_party_caller_free(&chan->caller);
02412    ast_party_connected_line_free(&chan->connected);
02413    ast_party_redirecting_free(&chan->redirecting);
02414 
02415    /* loop over the variables list, freeing all data and deleting list items */
02416    /* no need to lock the list, as the channel is already locked */
02417    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02418       ast_var_delete(vardata);
02419 
02420    if (chan->cdr) {
02421       ast_cdr_discard(chan->cdr);
02422       chan->cdr = NULL;
02423    }
02424 
02425    ast_string_field_free_memory(chan);
02426 }
02427 
02428 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
02429 {
02430    return ast_datastore_alloc(info, uid);
02431 }
02432 
02433 int ast_channel_datastore_free(struct ast_datastore *datastore)
02434 {
02435    return ast_datastore_free(datastore);
02436 }
02437 
02438 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
02439 {
02440    struct ast_datastore *datastore = NULL, *datastore2;
02441 
02442    AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
02443       if (datastore->inheritance > 0) {
02444          datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
02445          if (datastore2) {
02446             datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
02447             datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
02448             AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
02449          }
02450       }
02451    }
02452    return 0;
02453 }
02454 
02455 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
02456 {
02457    int res = 0;
02458 
02459    AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
02460 
02461    return res;
02462 }
02463 
02464 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
02465 {
02466    return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
02467 }
02468 
02469 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
02470 {
02471    struct ast_datastore *datastore = NULL;
02472    
02473    if (info == NULL)
02474       return NULL;
02475 
02476    AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
02477       if (datastore->info != info) {
02478          continue;
02479       }
02480 
02481       if (uid == NULL) {
02482          /* matched by type only */
02483          break;
02484       }
02485 
02486       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
02487          /* Matched by type AND uid */
02488          break;
02489       }
02490    }
02491    AST_LIST_TRAVERSE_SAFE_END;
02492 
02493    return datastore;
02494 }
02495 
02496 /*! Set the file descriptor on the channel */
02497 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
02498 {
02499 #ifdef HAVE_EPOLL
02500    struct epoll_event ev;
02501    struct ast_epoll_data *aed = NULL;
02502 
02503    if (chan->fds[which] > -1) {
02504       epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
02505       aed = chan->epfd_data[which];
02506    }
02507 
02508    /* If this new fd is valid, add it to the epoll */
02509    if (fd > -1) {
02510       if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
02511          return;
02512       
02513       chan->epfd_data[which] = aed;
02514       aed->chan = chan;
02515       aed->which = which;
02516       
02517       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02518       ev.data.ptr = aed;
02519       epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
02520    } else if (aed) {
02521       /* We don't have to keep around this epoll data structure now */
02522       free(aed);
02523       chan->epfd_data[which] = NULL;
02524    }
02525 #endif
02526    chan->fds[which] = fd;
02527    return;
02528 }
02529 
02530 /*! Add a channel to an optimized waitfor */
02531 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
02532 {
02533 #ifdef HAVE_EPOLL
02534    struct epoll_event ev;
02535    int i = 0;
02536 
02537    if (chan0->epfd == -1)
02538       return;
02539 
02540    /* Iterate through the file descriptors on chan1, adding them to chan0 */
02541    for (i = 0; i < AST_MAX_FDS; i++) {
02542       if (chan1->fds[i] == -1)
02543          continue;
02544       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02545       ev.data.ptr = chan1->epfd_data[i];
02546       epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
02547    }
02548 
02549 #endif
02550    return;
02551 }
02552 
02553 /*! Delete a channel from an optimized waitfor */
02554 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
02555 {
02556 #ifdef HAVE_EPOLL
02557    struct epoll_event ev;
02558    int i = 0;
02559 
02560    if (chan0->epfd == -1)
02561       return;
02562 
02563    for (i = 0; i < AST_MAX_FDS; i++) {
02564       if (chan1->fds[i] == -1)
02565          continue;
02566       epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
02567    }
02568 
02569 #endif
02570    return;
02571 }
02572 
02573 /*! \brief Softly hangup a channel, don't lock */
02574 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
02575 {
02576    ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
02577    /* Inform channel driver that we need to be hung up, if it cares */
02578    chan->_softhangup |= cause;
02579    ast_queue_frame(chan, &ast_null_frame);
02580    /* Interrupt any poll call or such */
02581    if (ast_test_flag(chan, AST_FLAG_BLOCKING))
02582       pthread_kill(chan->blocker, SIGURG);
02583    return 0;
02584 }
02585 
02586 /*! \brief Softly hangup a channel, lock */
02587 int ast_softhangup(struct ast_channel *chan, int cause)
02588 {
02589    int res;
02590 
02591    ast_channel_lock(chan);
02592    res = ast_softhangup_nolock(chan, cause);
02593    ast_channel_unlock(chan);
02594 
02595    return res;
02596 }
02597 
02598 static void free_translation(struct ast_channel *clonechan)
02599 {
02600    if (clonechan->writetrans)
02601       ast_translator_free_path(clonechan->writetrans);
02602    if (clonechan->readtrans)
02603       ast_translator_free_path(clonechan->readtrans);
02604    clonechan->writetrans = NULL;
02605    clonechan->readtrans = NULL;
02606    clonechan->rawwriteformat = clonechan->nativeformats;
02607    clonechan->rawreadformat = clonechan->nativeformats;
02608 }
02609 
02610 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
02611 {
02612    struct ast_channel *bridge;
02613 
02614    ast_channel_lock(chan);
02615    if (force || ast_strlen_zero(chan->hangupsource)) {
02616       ast_string_field_set(chan, hangupsource, source);
02617    }
02618    bridge = ast_bridged_channel(chan);
02619    ast_channel_unlock(chan);
02620 
02621    if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
02622       ast_channel_lock(bridge);
02623       ast_string_field_set(chan, hangupsource, source);
02624       ast_channel_unlock(bridge);
02625    }
02626 }
02627 
02628 /*! \brief Hangup a channel */
02629 int ast_hangup(struct ast_channel *chan)
02630 {
02631    int res = 0;
02632    char extra_str[64]; /* used for cel logging below */
02633 
02634    /* Don't actually hang up a channel that will masquerade as someone else, or
02635       if someone is going to masquerade as us */
02636    ast_channel_lock(chan);
02637 
02638    if (chan->audiohooks) {
02639       ast_audiohook_detach_list(chan->audiohooks);
02640       chan->audiohooks = NULL;
02641    }
02642 
02643    ast_framehook_list_destroy(chan);
02644 
02645    ast_autoservice_stop(chan);
02646 
02647    if (chan->masq) {
02648       ast_channel_unlock(chan);
02649       if (ast_do_masquerade(chan)) {
02650          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
02651       }
02652       ast_channel_lock(chan);
02653    }
02654 
02655    if (chan->masq) {
02656       ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
02657       ast_channel_unlock(chan);
02658       return 0;
02659    }
02660    /* If this channel is one which will be masqueraded into something,
02661       mark it as a zombie already, so we know to free it later */
02662    if (chan->masqr) {
02663       ast_set_flag(chan, AST_FLAG_ZOMBIE);
02664       ast_channel_unlock(chan);
02665       return 0;
02666    }
02667    ast_channel_unlock(chan);
02668 
02669    ao2_unlink(channels, chan);
02670 
02671    ast_channel_lock(chan);
02672    free_translation(chan);
02673    /* Close audio stream */
02674    if (chan->stream) {
02675       ast_closestream(chan->stream);
02676       chan->stream = NULL;
02677    }
02678    /* Close video stream */
02679    if (chan->vstream) {
02680       ast_closestream(chan->vstream);
02681       chan->vstream = NULL;
02682    }
02683    if (chan->sched) {
02684       sched_context_destroy(chan->sched);
02685       chan->sched = NULL;
02686    }
02687 
02688    if (chan->generatordata)   /* Clear any tone stuff remaining */
02689       if (chan->generator && chan->generator->release)
02690          chan->generator->release(chan, chan->generatordata);
02691    chan->generatordata = NULL;
02692    chan->generator = NULL;
02693 
02694    snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
02695    ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
02696 
02697    if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
02698       ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
02699                "is blocked by thread %ld in procedure %s!  Expect a failure\n",
02700                (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
02701       ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
02702    }
02703    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
02704       ast_debug(1, "Hanging up channel '%s'\n", chan->name);
02705       if (chan->tech->hangup)
02706          res = chan->tech->hangup(chan);
02707    } else {
02708       ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
02709    }
02710          
02711    ast_channel_unlock(chan);
02712    ast_cc_offer(chan);
02713    ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
02714       "Channel: %s\r\n"
02715       "Uniqueid: %s\r\n"
02716       "CallerIDNum: %s\r\n"
02717       "CallerIDName: %s\r\n"
02718       "Cause: %d\r\n"
02719       "Cause-txt: %s\r\n",
02720       chan->name,
02721       chan->uniqueid,
02722       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
02723       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
02724       chan->hangupcause,
02725       ast_cause2str(chan->hangupcause)
02726       );
02727 
02728    if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
02729       !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
02730        (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
02731       ast_channel_lock(chan);
02732          
02733       ast_cdr_end(chan->cdr);
02734       ast_cdr_detach(chan->cdr);
02735       chan->cdr = NULL;
02736       ast_channel_unlock(chan);
02737    }
02738 
02739    chan = ast_channel_release(chan);
02740 
02741    return res;
02742 }
02743 
02744 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
02745 {
02746    int res = 0;
02747 
02748    ast_channel_lock(chan);
02749 
02750    /* You can't answer an outbound call */
02751    if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
02752       ast_channel_unlock(chan);
02753       return 0;
02754    }
02755 
02756    /* Stop if we're a zombie or need a soft hangup */
02757    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
02758       ast_channel_unlock(chan);
02759       return -1;
02760    }
02761 
02762    ast_channel_unlock(chan);
02763 
02764    switch (chan->_state) {
02765    case AST_STATE_RINGING:
02766    case AST_STATE_RING:
02767       ast_channel_lock(chan);
02768       if (chan->tech->answer) {
02769          res = chan->tech->answer(chan);
02770       }
02771       ast_setstate(chan, AST_STATE_UP);
02772       if (cdr_answer) {
02773          ast_cdr_answer(chan->cdr);
02774       }
02775       ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
02776       ast_channel_unlock(chan);
02777       break;
02778    case AST_STATE_UP:
02779       ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
02780       /* Calling ast_cdr_answer when it it has previously been called
02781        * is essentially a no-op, so it is safe.
02782        */
02783       if (cdr_answer) {
02784          ast_cdr_answer(chan->cdr);
02785       }
02786       break;
02787    default:
02788       break;
02789    }
02790 
02791    ast_indicate(chan, -1);
02792    chan->visible_indication = 0;
02793 
02794    return res;
02795 }
02796 
02797 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
02798 {
02799    int res = 0;
02800    enum ast_channel_state old_state;
02801 
02802    old_state = chan->_state;
02803    if ((res = ast_raw_answer(chan, cdr_answer))) {
02804       return res;
02805    }
02806 
02807    switch (old_state) {
02808    case AST_STATE_RINGING:
02809    case AST_STATE_RING:
02810       /* wait for media to start flowing, but don't wait any longer
02811        * than 'delay' or 500 milliseconds, whichever is longer
02812        */
02813       do {
02814          AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
02815          struct ast_frame *cur, *new;
02816          int ms = MAX(delay, 500);
02817          unsigned int done = 0;
02818 
02819          AST_LIST_HEAD_INIT_NOLOCK(&frames);
02820 
02821          for (;;) {
02822             ms = ast_waitfor(chan, ms);
02823             if (ms < 0) {
02824                ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
02825                res = -1;
02826                break;
02827             }
02828             if (ms == 0) {
02829                ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
02830                break;
02831             }
02832             cur = ast_read(chan);
02833             if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
02834                     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
02835                if (cur) {
02836                   ast_frfree(cur);
02837                }
02838                res = -1;
02839                ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
02840                break;
02841             }
02842 
02843             if ((new = ast_frisolate(cur)) != cur) {
02844                ast_frfree(cur);
02845             }
02846 
02847             AST_LIST_INSERT_HEAD(&frames, new, frame_list);
02848 
02849             /* if a specific delay period was requested, continue
02850              * until that delay has passed. don't stop just because
02851              * incoming media has arrived.
02852              */
02853             if (delay) {
02854                continue;
02855             }
02856 
02857             switch (new->frametype) {
02858                /* all of these frametypes qualify as 'media' */
02859             case AST_FRAME_VOICE:
02860             case AST_FRAME_VIDEO:
02861             case AST_FRAME_TEXT:
02862             case AST_FRAME_DTMF_BEGIN:
02863             case AST_FRAME_DTMF_END:
02864             case AST_FRAME_IMAGE:
02865             case AST_FRAME_HTML:
02866             case AST_FRAME_MODEM:
02867                done = 1;
02868                break;
02869             case AST_FRAME_CONTROL:
02870             case AST_FRAME_IAX:
02871             case AST_FRAME_NULL:
02872             case AST_FRAME_CNG:
02873                break;
02874             }
02875 
02876             if (done) {
02877                break;
02878             }
02879          }
02880 
02881          if (res == 0) {
02882             ast_channel_lock(chan);
02883             while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
02884                ast_queue_frame_head(chan, cur);
02885                ast_frfree(cur);
02886             }
02887             ast_channel_unlock(chan);
02888          }
02889       } while (0);
02890       break;
02891    default:
02892       break;
02893    }
02894 
02895    return res;
02896 }
02897 
02898 int ast_answer(struct ast_channel *chan)
02899 {
02900    return __ast_answer(chan, 0, 1);
02901 }
02902 
02903 void ast_deactivate_generator(struct ast_channel *chan)
02904 {
02905    ast_channel_lock(chan);
02906    if (chan->generatordata) {
02907       if (chan->generator && chan->generator->release)
02908          chan->generator->release(chan, chan->generatordata);
02909       chan->generatordata = NULL;
02910       chan->generator = NULL;
02911       ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
02912       ast_clear_flag(chan, AST_FLAG_WRITE_INT);
02913       ast_settimeout(chan, 0, NULL, NULL);
02914    }
02915    ast_channel_unlock(chan);
02916 }
02917 
02918 static int generator_force(const void *data)
02919 {
02920    /* Called if generator doesn't have data */
02921    void *tmp;
02922    int res;
02923    int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
02924    struct ast_channel *chan = (struct ast_channel *)data;
02925 
02926    ast_channel_lock(chan);
02927    tmp = chan->generatordata;
02928    chan->generatordata = NULL;
02929    if (chan->generator)
02930       generate = chan->generator->generate;
02931    ast_channel_unlock(chan);
02932 
02933    if (!tmp || !generate)
02934       return 0;
02935 
02936    res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
02937 
02938    chan->generatordata = tmp;
02939 
02940    if (res) {
02941       ast_debug(1, "Auto-deactivating generator\n");
02942       ast_deactivate_generator(chan);
02943    }
02944 
02945    return 0;
02946 }
02947 
02948 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
02949 {
02950    int res = 0;
02951 
02952    ast_channel_lock(chan);
02953    if (chan->generatordata) {
02954       if (chan->generator && chan->generator->release)
02955          chan->generator->release(chan, chan->generatordata);
02956       chan->generatordata = NULL;
02957    }
02958    if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
02959       res = -1;
02960    }
02961    if (!res) {
02962       ast_settimeout(chan, 50, generator_force, chan);
02963       chan->generator = gen;
02964    }
02965    ast_channel_unlock(chan);
02966 
02967    ast_prod(chan);
02968 
02969    return res;
02970 }
02971 
02972 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02973 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
02974 {
02975    int winner = -1;
02976    ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
02977    return winner;
02978 }
02979 
02980 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02981 #ifdef HAVE_EPOLL
02982 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
02983                int *exception, int *outfd, int *ms)
02984 #else
02985 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
02986                int *exception, int *outfd, int *ms)
02987 #endif
02988 {
02989    struct timeval start = { 0 , 0 };
02990    struct pollfd *pfds = NULL;
02991    int res;
02992    long rms;
02993    int x, y, max;
02994    int sz;
02995    struct timeval now = { 0, 0 };
02996    struct timeval whentohangup = { 0, 0 }, diff;
02997    struct ast_channel *winner = NULL;
02998    struct fdmap {
02999       int chan;
03000       int fdno;
03001    } *fdmap = NULL;
03002 
03003    if ((sz = n * AST_MAX_FDS + nfds)) {
03004       pfds = alloca(sizeof(*pfds) * sz);
03005       fdmap = alloca(sizeof(*fdmap) * sz);
03006    }
03007 
03008    if (outfd)
03009       *outfd = -99999;
03010    if (exception)
03011       *exception = 0;
03012    
03013    /* Perform any pending masquerades */
03014    for (x = 0; x < n; x++) {
03015       if (c[x]->masq && ast_do_masquerade(c[x])) {
03016          ast_log(LOG_WARNING, "Masquerade failed\n");
03017          *ms = -1;
03018          return NULL;
03019       }
03020 
03021       ast_channel_lock(c[x]);
03022       if (!ast_tvzero(c[x]->whentohangup)) {
03023          if (ast_tvzero(whentohangup))
03024             now = ast_tvnow();
03025          diff = ast_tvsub(c[x]->whentohangup, now);
03026          if (diff.tv_sec < 0 || ast_tvzero(diff)) {
03027             /* Should already be hungup */
03028             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03029             ast_channel_unlock(c[x]);
03030             return c[x];
03031          }
03032          if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
03033             whentohangup = diff;
03034       }
03035       ast_channel_unlock(c[x]);
03036    }
03037    /* Wait full interval */
03038    rms = *ms;
03039    /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
03040    if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
03041       rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
03042       if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
03043          rms =  *ms;
03044       }
03045    } else if (!ast_tvzero(whentohangup) && rms < 0) {
03046       /* Tiny corner case... call would need to last >24 days */
03047       rms = INT_MAX;
03048    }
03049    /*
03050     * Build the pollfd array, putting the channels' fds first,
03051     * followed by individual fds. Order is important because
03052     * individual fd's must have priority over channel fds.
03053     */
03054    max = 0;
03055    for (x = 0; x < n; x++) {
03056       for (y = 0; y < AST_MAX_FDS; y++) {
03057          fdmap[max].fdno = y;  /* fd y is linked to this pfds */
03058          fdmap[max].chan = x;  /* channel x is linked to this pfds */
03059          max += ast_add_fd(&pfds[max], c[x]->fds[y]);
03060       }
03061       CHECK_BLOCKING(c[x]);
03062    }
03063    /* Add the individual fds */
03064    for (x = 0; x < nfds; x++) {
03065       fdmap[max].chan = -1;
03066       max += ast_add_fd(&pfds[max], fds[x]);
03067    }
03068 
03069    if (*ms > 0)
03070       start = ast_tvnow();
03071    
03072    if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
03073       do {
03074          int kbrms = rms;
03075          if (kbrms > 600000)
03076             kbrms = 600000;
03077          res = ast_poll(pfds, max, kbrms);
03078          if (!res)
03079             rms -= kbrms;
03080       } while (!res && (rms > 0));
03081    } else {
03082       res = ast_poll(pfds, max, rms);
03083    }
03084    for (x = 0; x < n; x++)
03085       ast_clear_flag(c[x], AST_FLAG_BLOCKING);
03086    if (res < 0) { /* Simulate a timeout if we were interrupted */
03087       if (errno != EINTR)
03088          *ms = -1;
03089       return NULL;
03090    }
03091    if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
03092       now = ast_tvnow();
03093       for (x = 0; x < n; x++) {
03094          if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
03095             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03096             if (winner == NULL)
03097                winner = c[x];
03098          }
03099       }
03100    }
03101    if (res == 0) { /* no fd ready, reset timeout and done */
03102       *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
03103       return winner;
03104    }
03105    /*
03106     * Then check if any channel or fd has a pending event.
03107     * Remember to check channels first and fds last, as they
03108     * must have priority on setting 'winner'
03109     */
03110    for (x = 0; x < max; x++) {
03111       res = pfds[x].revents;
03112       if (res == 0)
03113          continue;
03114       if (fdmap[x].chan >= 0) {  /* this is a channel */
03115          winner = c[fdmap[x].chan]; /* override previous winners */
03116          if (res & POLLPRI)
03117             ast_set_flag(winner, AST_FLAG_EXCEPTION);
03118          else
03119             ast_clear_flag(winner, AST_FLAG_EXCEPTION);
03120          winner->fdno = fdmap[x].fdno;
03121       } else {       /* this is an fd */
03122          if (outfd)
03123             *outfd = pfds[x].fd;
03124          if (exception)
03125             *exception = (res & POLLPRI) ? -1 : 0;
03126          winner = NULL;
03127       }
03128    }
03129    if (*ms > 0) {
03130       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03131       if (*ms < 0)
03132          *ms = 0;
03133    }
03134    return winner;
03135 }
03136 
03137 #ifdef HAVE_EPOLL
03138 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
03139 {
03140    struct timeval start = { 0 , 0 };
03141    int res = 0;
03142    struct epoll_event ev[1];
03143    long diff, rms = *ms;
03144    struct ast_channel *winner = NULL;
03145    struct ast_epoll_data *aed = NULL;
03146 
03147 
03148    /* See if this channel needs to be masqueraded */
03149    if (chan->masq && ast_do_masquerade(chan)) {
03150       ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
03151       *ms = -1;
03152       return NULL;
03153    }
03154 
03155    ast_channel_lock(chan);
03156    /* Figure out their timeout */
03157    if (!ast_tvzero(chan->whentohangup)) {
03158       if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
03159          /* They should already be hungup! */
03160          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03161          ast_channel_unlock(chan);
03162          return NULL;
03163       }
03164       /* If this value is smaller then the current one... make it priority */
03165       if (rms > diff)
03166          rms = diff;
03167    }
03168 
03169    ast_channel_unlock(chan);
03170 
03171    /* Time to make this channel block... */
03172    CHECK_BLOCKING(chan);
03173 
03174    if (*ms > 0)
03175       start = ast_tvnow();
03176 
03177    /* We don't have to add any file descriptors... they are already added, we just have to wait! */
03178    res = epoll_wait(chan->epfd, ev, 1, rms);
03179 
03180    /* Stop blocking */
03181    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03182 
03183    /* Simulate a timeout if we were interrupted */
03184    if (res < 0) {
03185       if (errno != EINTR)
03186          *ms = -1;
03187       return NULL;
03188    }
03189 
03190    /* If this channel has a timeout see if it expired */
03191    if (!ast_tvzero(chan->whentohangup)) {
03192       if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
03193          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03194          winner = chan;
03195       }
03196    }
03197 
03198    /* No fd ready, reset timeout and be done for now */
03199    if (!res) {
03200       *ms = 0;
03201       return winner;
03202    }
03203 
03204    /* See what events are pending */
03205    aed = ev[0].data.ptr;
03206    chan->fdno = aed->which;
03207    if (ev[0].events & EPOLLPRI)
03208       ast_set_flag(chan, AST_FLAG_EXCEPTION);
03209    else
03210       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03211 
03212    if (*ms > 0) {
03213       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03214       if (*ms < 0)
03215          *ms = 0;
03216    }
03217 
03218    return chan;
03219 }
03220 
03221 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
03222 {
03223    struct timeval start = { 0 , 0 };
03224    int res = 0, i;
03225    struct epoll_event ev[25] = { { 0, } };
03226    struct timeval now = { 0, 0 };
03227    long whentohangup = 0, diff = 0, rms = *ms;
03228    struct ast_channel *winner = NULL;
03229 
03230    for (i = 0; i < n; i++) {
03231       if (c[i]->masq && ast_do_masquerade(c[i])) {
03232          ast_log(LOG_WARNING, "Masquerade failed\n");
03233          *ms = -1;
03234          return NULL;
03235       }
03236 
03237       ast_channel_lock(c[i]);
03238       if (!ast_tvzero(c[i]->whentohangup)) {
03239          if (whentohangup == 0)
03240             now = ast_tvnow();
03241          if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
03242             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03243             ast_channel_unlock(c[i]);
03244             return c[i];
03245          }
03246          if (!whentohangup || whentohangup > diff)
03247             whentohangup = diff;
03248       }
03249       ast_channel_unlock(c[i]);
03250       CHECK_BLOCKING(c[i]);
03251    }
03252 
03253    rms = *ms;
03254    if (whentohangup) {
03255       rms = whentohangup;
03256       if (*ms >= 0 && *ms < rms)
03257          rms = *ms;
03258    }
03259 
03260    if (*ms > 0)
03261       start = ast_tvnow();
03262 
03263    res = epoll_wait(c[0]->epfd, ev, 25, rms);
03264 
03265    for (i = 0; i < n; i++)
03266       ast_clear_flag(c[i], AST_FLAG_BLOCKING);
03267 
03268    if (res < 0) {
03269       if (errno != EINTR)
03270          *ms = -1;
03271       return NULL;
03272    }
03273 
03274    if (whentohangup) {
03275       now = ast_tvnow();
03276       for (i = 0; i < n; i++) {
03277          if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
03278             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03279             if (!winner)
03280                winner = c[i];
03281          }
03282       }
03283    }
03284 
03285    if (!res) {
03286       *ms = 0;
03287       return winner;
03288    }
03289 
03290    for (i = 0; i < res; i++) {
03291       struct ast_epoll_data *aed = ev[i].data.ptr;
03292 
03293       if (!ev[i].events || !aed)
03294          continue;
03295 
03296       winner = aed->chan;
03297       if (ev[i].events & EPOLLPRI)
03298          ast_set_flag(winner, AST_FLAG_EXCEPTION);
03299       else
03300          ast_clear_flag(winner, AST_FLAG_EXCEPTION);
03301       winner->fdno = aed->which;
03302    }
03303 
03304    if (*ms > 0) {
03305       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03306       if (*ms < 0)
03307          *ms = 0;
03308    }
03309 
03310    return winner;
03311 }
03312 
03313 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
03314                int *exception, int *outfd, int *ms)
03315 {
03316    /* Clear all provided values in one place. */
03317    if (outfd)
03318       *outfd = -99999;
03319    if (exception)
03320       *exception = 0;
03321 
03322    /* If no epoll file descriptor is available resort to classic nandfds */
03323    if (!n || nfds || c[0]->epfd == -1)
03324       return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
03325    else if (!nfds && n == 1)
03326       return ast_waitfor_nandfds_simple(c[0], ms);
03327    else
03328       return ast_waitfor_nandfds_complex(c, n, ms);
03329 }
03330 #endif
03331 
03332 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
03333 {
03334    return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
03335 }
03336 
03337 int ast_waitfor(struct ast_channel *c, int ms)
03338 {
03339    int oldms = ms;   /* -1 if no timeout */
03340 
03341    ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
03342    if ((ms < 0) && (oldms < 0))
03343       ms = 0;
03344    return ms;
03345 }
03346 
03347 /* XXX never to be called with ms = -1 */
03348 int ast_waitfordigit(struct ast_channel *c, int ms)
03349 {
03350    return ast_waitfordigit_full(c, ms, -1, -1);
03351 }
03352 
03353 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
03354 {
03355    int res;
03356    unsigned int real_rate = rate, max_rate;
03357 
03358    ast_channel_lock(c);
03359 
03360    if (c->timingfd == -1) {
03361       ast_channel_unlock(c);
03362       return -1;
03363    }
03364 
03365    if (!func) {
03366       rate = 0;
03367       data = NULL;
03368    }
03369 
03370    if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
03371       real_rate = max_rate;
03372    }
03373 
03374    ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
03375 
03376    res = ast_timer_set_rate(c->timer, real_rate);
03377 
03378    c->timingfunc = func;
03379    c->timingdata = data;
03380 
03381    ast_channel_unlock(c);
03382 
03383    return res;
03384 }
03385 
03386 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
03387 {
03388    /* Stop if we're a zombie or need a soft hangup */
03389    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
03390       return -1;
03391 
03392    /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
03393    ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
03394 
03395    /* Wait for a digit, no more than ms milliseconds total. */
03396    
03397    while (ms) {
03398       struct ast_channel *rchan;
03399       int outfd=-1;
03400 
03401       errno = 0;
03402       rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
03403       
03404       if (!rchan && outfd < 0 && ms) {
03405          if (errno == 0 || errno == EINTR)
03406             continue;
03407          ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
03408          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03409          return -1;
03410       } else if (outfd > -1) {
03411          /* The FD we were watching has something waiting */
03412          ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
03413          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03414          return 1;
03415       } else if (rchan) {
03416          int res;
03417          struct ast_frame *f = ast_read(c);
03418          if (!f)
03419             return -1;
03420 
03421          switch (f->frametype) {
03422          case AST_FRAME_DTMF_BEGIN:
03423             break;
03424          case AST_FRAME_DTMF_END:
03425             res = f->subclass.integer;
03426             ast_frfree(f);
03427             ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03428             return res;
03429          case AST_FRAME_CONTROL:
03430             switch (f->subclass.integer) {
03431             case AST_CONTROL_HANGUP:
03432                ast_frfree(f);
03433                ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03434                return -1;
03435             case AST_CONTROL_RINGING:
03436             case AST_CONTROL_ANSWER:
03437             case AST_CONTROL_SRCUPDATE:
03438             case AST_CONTROL_SRCCHANGE:
03439             case AST_CONTROL_CONNECTED_LINE:
03440             case AST_CONTROL_REDIRECTING:
03441             case -1:
03442                /* Unimportant */
03443                break;
03444             default:
03445                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
03446                break;
03447             }
03448             break;
03449          case AST_FRAME_VOICE:
03450             /* Write audio if appropriate */
03451             if (audiofd > -1) {
03452                if (write(audiofd, f->data.ptr, f->datalen) < 0) {
03453                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
03454                }
03455             }
03456          default:
03457             /* Ignore */
03458             break;
03459          }
03460          ast_frfree(f);
03461       }
03462    }
03463 
03464    ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03465 
03466    return 0; /* Time is up */
03467 }
03468 
03469 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
03470 {
03471    ast_manager_event(chan, EVENT_FLAG_DTMF,
03472          "DTMF",
03473          "Channel: %s\r\n"
03474          "Uniqueid: %s\r\n"
03475          "Digit: %c\r\n"
03476          "Direction: %s\r\n"
03477          "Begin: %s\r\n"
03478          "End: %s\r\n",
03479          chan->name, chan->uniqueid, digit, direction, begin, end);
03480 }
03481 
03482 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
03483 {
03484    if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
03485       void *tmp = chan->generatordata;
03486       int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
03487       int res;
03488       int samples;
03489 
03490       if (chan->timingfunc) {
03491          ast_debug(1, "Generator got voice, switching to phase locked mode\n");
03492          ast_settimeout(chan, 0, NULL, NULL);
03493       }
03494 
03495       chan->generatordata = NULL;     /* reset, to let writes go through */
03496 
03497       if (f->subclass.codec != chan->writeformat) {
03498          float factor;
03499          factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
03500          samples = (int) ( ((float) f->samples) * factor );
03501       } else {
03502          samples = f->samples;
03503       }
03504       
03505       /* This unlock is here based on two assumptions that hold true at this point in the
03506        * code. 1) this function is only called from within __ast_read() and 2) all generators
03507        * call ast_write() in their generate callback.
03508        *
03509        * The reason this is added is so that when ast_write is called, the lock that occurs 
03510        * there will not recursively lock the channel. Doing this will cause intended deadlock 
03511        * avoidance not to work in deeper functions
03512        */
03513       ast_channel_unlock(chan);
03514       res = generate(chan, tmp, f->datalen, samples);
03515       ast_channel_lock(chan);
03516       chan->generatordata = tmp;
03517       if (res) {
03518          ast_debug(1, "Auto-deactivating generator\n");
03519          ast_deactivate_generator(chan);
03520       }
03521 
03522    } else if (f->frametype == AST_FRAME_CNG) {
03523       if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
03524          ast_debug(1, "Generator got CNG, switching to timed mode\n");
03525          ast_settimeout(chan, 50, generator_force, chan);
03526       }
03527    }
03528 }
03529 
03530 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
03531 {
03532    struct ast_frame *fr = &chan->dtmff;
03533 
03534    fr->frametype = AST_FRAME_DTMF_END;
03535    fr->subclass.integer = f->subclass.integer;
03536    fr->len = f->len;
03537 
03538    /* The only time this function will be called is for a frame that just came
03539     * out of the channel driver.  So, we want to stick it on the tail of the
03540     * readq. */
03541 
03542    ast_queue_frame(chan, fr);
03543 }
03544 
03545 /*!
03546  * \brief Determine whether or not we should ignore DTMF in the readq
03547  */
03548 static inline int should_skip_dtmf(struct ast_channel *chan)
03549 {
03550    if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
03551       /* We're in the middle of emulating a digit, or DTMF has been
03552        * explicitly deferred.  Skip this digit, then. */
03553       return 1;
03554    }
03555          
03556    if (!ast_tvzero(chan->dtmf_tv) && 
03557          ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
03558       /* We're not in the middle of a digit, but it hasn't been long enough
03559        * since the last digit, so we'll have to skip DTMF for now. */
03560       return 1;
03561    }
03562 
03563    return 0;
03564 }
03565 
03566 /*!
03567  * \brief calculates the number of samples to jump forward with in a monitor stream.
03568  
03569  * \note When using ast_seekstream() with the read and write streams of a monitor,
03570  * the number of samples to seek forward must be of the same sample rate as the stream
03571  * or else the jump will not be calculated correctly.
03572  *
03573  * \retval number of samples to seek forward after rate conversion.
03574  */
03575 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
03576 {
03577    int diff = sample_rate - seek_rate;
03578 
03579    if (diff > 0) {
03580       samples = samples / (float) (sample_rate / seek_rate);
03581    } else if (diff < 0) {
03582       samples = samples * (float) (seek_rate / sample_rate);
03583    }
03584 
03585    return samples;
03586 }
03587 
03588 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
03589 {
03590    struct ast_frame *f = NULL;   /* the return value */
03591    int blah;
03592    int prestate;
03593    int cause = 0;
03594 
03595    /* this function is very long so make sure there is only one return
03596     * point at the end (there are only two exceptions to this).
03597     */
03598 
03599    if (chan->masq) {
03600       if (ast_do_masquerade(chan))
03601          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
03602       else
03603          f =  &ast_null_frame;
03604       return f;
03605    }
03606 
03607    /* if here, no masq has happened, lock the channel and proceed */
03608    ast_channel_lock(chan);
03609 
03610    /* Stop if we're a zombie or need a soft hangup */
03611    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03612       if (chan->generator)
03613          ast_deactivate_generator(chan);
03614 
03615       /* It is possible for chan->_softhangup to be set, yet there still be control
03616        * frames that still need to be read. Instead of just going to 'done' in the
03617        * case of ast_check_hangup(), we instead need to send the HANGUP frame so that
03618        * it can mark the end of the read queue. If there are frames to be read, 
03619        * ast_queue_control will be called repeatedly, but will only queue one hangup
03620        * frame. */
03621       if (ast_check_hangup(chan)) {
03622          ast_queue_control(chan, AST_CONTROL_HANGUP);
03623       } else {
03624          goto done;
03625       }
03626    }
03627 
03628 #ifdef AST_DEVMODE
03629    /* 
03630     * The ast_waitfor() code records which of the channel's file descriptors reported that
03631     * data is available.  In theory, ast_read() should only be called after ast_waitfor()
03632     * reports that a channel has data available for reading.  However, there still may be
03633     * some edge cases throughout the code where ast_read() is called improperly.  This can
03634     * potentially cause problems, so if this is a developer build, make a lot of noise if
03635     * this happens so that it can be addressed. 
03636     */
03637    if (chan->fdno == -1) {
03638       ast_log(LOG_ERROR,
03639          "ast_read() on chan '%s' called with no recorded file descriptor.\n",
03640          chan->name);
03641    }
03642 #endif
03643 
03644    prestate = chan->_state;
03645 
03646    /* Read and ignore anything on the alertpipe, but read only
03647       one sizeof(blah) per frame that we send from it */
03648    if (chan->alertpipe[0] > -1) {
03649       int flags = fcntl(chan->alertpipe[0], F_GETFL);
03650       /* For some odd reason, the alertpipe occasionally loses nonblocking status,
03651        * which immediately causes a deadlock scenario.  Detect and prevent this. */
03652       if ((flags & O_NONBLOCK) == 0) {
03653          ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
03654          if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
03655             ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
03656             f = &ast_null_frame;
03657             goto done;
03658          }
03659       }
03660       if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
03661          if (errno != EINTR && errno != EAGAIN)
03662             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
03663       }
03664    }
03665 
03666    if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
03667       enum ast_timer_event res;
03668 
03669       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03670 
03671       res = ast_timer_get_event(chan->timer);
03672 
03673       switch (res) {
03674       case AST_TIMING_EVENT_EXPIRED:
03675          ast_timer_ack(chan->timer, 1);
03676 
03677          if (chan->timingfunc) {
03678             /* save a copy of func/data before unlocking the channel */
03679             int (*func)(const void *) = chan->timingfunc;
03680             void *data = chan->timingdata;
03681             chan->fdno = -1;
03682             ast_channel_unlock(chan);
03683             func(data);
03684          } else {
03685             ast_timer_set_rate(chan->timer, 0);
03686             chan->fdno = -1;
03687             ast_channel_unlock(chan);
03688          }
03689 
03690          /* cannot 'goto done' because the channel is already unlocked */
03691          return &ast_null_frame;
03692 
03693       case AST_TIMING_EVENT_CONTINUOUS:
03694          if (AST_LIST_EMPTY(&chan->readq) || 
03695             !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
03696             ast_timer_disable_continuous(chan->timer);
03697          }
03698          break;
03699       }
03700 
03701    } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
03702       /* if the AST_GENERATOR_FD is set, call the generator with args
03703        * set to -1 so it can do whatever it needs to.
03704        */
03705       void *tmp = chan->generatordata;
03706       chan->generatordata = NULL;     /* reset to let ast_write get through */
03707       chan->generator->generate(chan, tmp, -1, -1);
03708       chan->generatordata = tmp;
03709       f = &ast_null_frame;
03710       chan->fdno = -1;
03711       goto done;
03712    }
03713 
03714    /* Check for pending read queue */
03715    if (!AST_LIST_EMPTY(&chan->readq)) {
03716       int skip_dtmf = should_skip_dtmf(chan);
03717 
03718       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
03719          /* We have to be picky about which frame we pull off of the readq because
03720           * there are cases where we want to leave DTMF frames on the queue until
03721           * some later time. */
03722 
03723          if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
03724             continue;
03725          }
03726 
03727          AST_LIST_REMOVE_CURRENT(frame_list);
03728          break;
03729       }
03730       AST_LIST_TRAVERSE_SAFE_END;
03731       
03732       if (!f) {
03733          /* There were no acceptable frames on the readq. */
03734          f = &ast_null_frame;
03735          if (chan->alertpipe[0] > -1) {
03736             int poke = 0;
03737             /* Restore the state of the alertpipe since we aren't ready for any
03738              * of the frames in the readq. */
03739             if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
03740                ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
03741             }
03742          }
03743       }
03744 
03745       /* Interpret hangup and return NULL */
03746       /* XXX why not the same for frames from the channel ? */
03747       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
03748          cause = f->data.uint32;
03749          ast_frfree(f);
03750          f = NULL;
03751       }
03752    } else {
03753       chan->blocker = pthread_self();
03754       if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
03755          if (chan->tech->exception)
03756             f = chan->tech->exception(chan);
03757          else {
03758             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
03759             f = &ast_null_frame;
03760          }
03761          /* Clear the exception flag */
03762          ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03763       } else if (chan->tech->read)
03764          f = chan->tech->read(chan);
03765       else
03766          ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
03767    }
03768 
03769    /*
03770     * Reset the recorded file descriptor that triggered this read so that we can
03771     * easily detect when ast_read() is called without properly using ast_waitfor().
03772     */
03773    chan->fdno = -1;
03774 
03775    /* Perform the framehook read event here. After the frame enters the framehook list
03776     * there is no telling what will happen, <insert mad scientist laugh here>!!! */
03777    f = ast_framehook_list_read_event(chan->framehooks, f);
03778 
03779    if (f) {
03780       struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
03781       struct ast_control_read_action_payload *read_action_payload;
03782       struct ast_party_connected_line connected;
03783 
03784       /* if the channel driver returned more than one frame, stuff the excess
03785          into the readq for the next ast_read call
03786       */
03787       if (AST_LIST_NEXT(f, frame_list)) {
03788          ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
03789          ast_frfree(AST_LIST_NEXT(f, frame_list));
03790          AST_LIST_NEXT(f, frame_list) = NULL;
03791       }
03792 
03793       switch (f->frametype) {
03794       case AST_FRAME_CONTROL:
03795          if (f->subclass.integer == AST_CONTROL_ANSWER) {
03796             if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
03797                ast_debug(1, "Ignoring answer on an inbound call!\n");
03798                ast_frfree(f);
03799                f = &ast_null_frame;
03800             } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
03801                ast_debug(1, "Dropping duplicate answer!\n");
03802                ast_frfree(f);
03803                f = &ast_null_frame;
03804             } else {
03805                /* Answer the CDR */
03806                ast_setstate(chan, AST_STATE_UP);
03807                /* removed a call to ast_cdr_answer(chan->cdr) from here. */
03808                ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
03809             }
03810          } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
03811             read_action_payload = f->data.ptr;
03812             switch (read_action_payload->action) {
03813             case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
03814                ast_party_connected_line_init(&connected);
03815                ast_party_connected_line_copy(&connected, &chan->connected);
03816                if (ast_connected_line_parse_data(read_action_payload->payload,
03817                   read_action_payload->payload_size, &connected)) {
03818                   ast_party_connected_line_free(&connected);
03819                   break;
03820                }
03821                if (ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
03822                   ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
03823                      read_action_payload->payload,
03824                      read_action_payload->payload_size);
03825                }
03826                ast_party_connected_line_free(&connected);
03827                break;
03828             }
03829             ast_frfree(f);
03830             f = &ast_null_frame;
03831          }
03832          break;
03833       case AST_FRAME_DTMF_END:
03834          send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
03835          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
03836          /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
03837          if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
03838             queue_dtmf_readq(chan, f);
03839             ast_frfree(f);
03840             f = &ast_null_frame;
03841          } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
03842             if (!ast_tvzero(chan->dtmf_tv) && 
03843                 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
03844                /* If it hasn't been long enough, defer this digit */
03845                queue_dtmf_readq(chan, f);
03846                ast_frfree(f);
03847                f = &ast_null_frame;
03848             } else {
03849                /* There was no begin, turn this into a begin and send the end later */
03850                f->frametype = AST_FRAME_DTMF_BEGIN;
03851                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
03852                chan->emulate_dtmf_digit = f->subclass.integer;
03853                chan->dtmf_tv = ast_tvnow();
03854                if (f->len) {
03855                   if (f->len > AST_MIN_DTMF_DURATION)
03856                      chan->emulate_dtmf_duration = f->len;
03857                   else 
03858                      chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
03859                } else
03860                   chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
03861                ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, chan->emulate_dtmf_duration, chan->name);
03862             }
03863             if (chan->audiohooks) {
03864                struct ast_frame *old_frame = f;
03865                /*!
03866                 * \todo XXX It is possible to write a digit to the audiohook twice
03867                 * if the digit was originally read while the channel was in autoservice. */
03868                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03869                if (old_frame != f)
03870                   ast_frfree(old_frame);
03871             }
03872          } else {
03873             struct timeval now = ast_tvnow();
03874             if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03875                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
03876                ast_clear_flag(chan, AST_FLAG_IN_DTMF);
03877                if (!f->len)
03878                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03879 
03880                /* detect tones that were received on
03881                 * the wire with durations shorter than
03882                 * AST_MIN_DTMF_DURATION and set f->len
03883                 * to the actual duration of the DTMF
03884                 * frames on the wire.  This will cause
03885                 * dtmf emulation to be triggered later
03886                 * on.
03887                 */
03888                if (ast_tvdiff_ms(now, chan->dtmf_tv) < AST_MIN_DTMF_DURATION) {
03889                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03890                   ast_log(LOG_DTMF, "DTMF end '%c' detected to have actual duration %ld on the wire, emulation will be triggered on %s\n", f->subclass.integer, f->len, chan->name);
03891                }
03892             } else if (!f->len) {
03893                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
03894                f->len = AST_MIN_DTMF_DURATION;
03895             }
03896             if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
03897                ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass.integer, f->len, AST_MIN_DTMF_DURATION, chan->name);
03898                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
03899                chan->emulate_dtmf_digit = f->subclass.integer;
03900                chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
03901                ast_frfree(f);
03902                f = &ast_null_frame;
03903             } else {
03904                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
03905                if (f->len < AST_MIN_DTMF_DURATION) {
03906                   f->len = AST_MIN_DTMF_DURATION;
03907                }
03908                chan->dtmf_tv = now;
03909             }
03910             if (chan->audiohooks) {
03911                struct ast_frame *old_frame = f;
03912                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03913                if (old_frame != f)
03914                   ast_frfree(old_frame);
03915             }
03916          }
03917          break;
03918       case AST_FRAME_DTMF_BEGIN:
03919          send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
03920          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
03921          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
03922              (!ast_tvzero(chan->dtmf_tv) && 
03923                ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
03924             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
03925             ast_frfree(f);
03926             f = &ast_null_frame;
03927          } else {
03928             ast_set_flag(chan, AST_FLAG_IN_DTMF);
03929             chan->dtmf_tv = ast_tvnow();
03930             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
03931          }
03932          break;
03933       case AST_FRAME_NULL:
03934          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
03935           * is reached , because we want to make sure we pass at least one
03936           * voice frame through before starting the next digit, to ensure a gap
03937           * between DTMF digits. */
03938          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
03939             struct timeval now = ast_tvnow();
03940             if (!chan->emulate_dtmf_duration) {
03941                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03942                chan->emulate_dtmf_digit = 0;
03943             } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
03944                chan->emulate_dtmf_duration = 0;
03945                ast_frfree(f);
03946                f = &chan->dtmff;
03947                f->frametype = AST_FRAME_DTMF_END;
03948                f->subclass.integer = chan->emulate_dtmf_digit;
03949                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03950                chan->dtmf_tv = now;
03951                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03952                chan->emulate_dtmf_digit = 0;
03953                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
03954                if (chan->audiohooks) {
03955                   struct ast_frame *old_frame = f;
03956                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03957                   if (old_frame != f) {
03958                      ast_frfree(old_frame);
03959                   }
03960                }
03961             }
03962          }
03963          break;
03964       case AST_FRAME_VOICE:
03965          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
03966           * is reached , because we want to make sure we pass at least one
03967           * voice frame through before starting the next digit, to ensure a gap
03968           * between DTMF digits. */
03969          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
03970             ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03971             chan->emulate_dtmf_digit = 0;
03972          }
03973 
03974          if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03975             if (dropaudio)
03976                ast_read_generator_actions(chan, f);
03977             ast_frfree(f);
03978             f = &ast_null_frame;
03979          }
03980 
03981          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03982             struct timeval now = ast_tvnow();
03983             if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
03984                chan->emulate_dtmf_duration = 0;
03985                ast_frfree(f);
03986                f = &chan->dtmff;
03987                f->frametype = AST_FRAME_DTMF_END;
03988                f->subclass.integer = chan->emulate_dtmf_digit;
03989                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03990                chan->dtmf_tv = now;
03991                if (chan->audiohooks) {
03992                   struct ast_frame *old_frame = f;
03993                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03994                   if (old_frame != f)
03995                      ast_frfree(old_frame);
03996                }
03997                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
03998             } else {
03999                /* Drop voice frames while we're still in the middle of the digit */
04000                ast_frfree(f);
04001                f = &ast_null_frame;
04002             }
04003          } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass.codec & chan->nativeformats)) {
04004             /* This frame is not one of the current native formats -- drop it on the floor */
04005             char to[200];
04006             ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
04007                chan->name, ast_getformatname(f->subclass.codec), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
04008             ast_frfree(f);
04009             f = &ast_null_frame;
04010          } else if ((f->frametype == AST_FRAME_VOICE)) {
04011             /* Send frame to audiohooks if present */
04012             if (chan->audiohooks) {
04013                struct ast_frame *old_frame = f;
04014                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04015                if (old_frame != f)
04016                   ast_frfree(old_frame);
04017             }
04018             if (chan->monitor && chan->monitor->read_stream ) {
04019                /* XXX what does this do ? */
04020 #ifndef MONITOR_CONSTANT_DELAY
04021                int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
04022                if (jump >= 0) {
04023                   jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04024                   if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
04025                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
04026                   chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
04027                } else
04028                   chan->insmpl+= f->samples;
04029 #else
04030                int jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04031                if (jump - MONITOR_DELAY >= 0) {
04032                   if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
04033                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
04034                   chan->insmpl += chan->outsmpl - chan->insmpl;
04035                } else
04036                   chan->insmpl += f->samples;
04037 #endif
04038                if (chan->monitor->state == AST_MONITOR_RUNNING) {
04039                   if (ast_writestream(chan->monitor->read_stream, f) < 0)
04040                      ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
04041                }
04042             }
04043 
04044             if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL) {
04045                f = &ast_null_frame;
04046             }
04047 
04048             /* it is possible for the translation process on chan->readtrans to have
04049                produced multiple frames from the single input frame we passed it; if
04050                this happens, queue the additional frames *before* the frames we may
04051                have queued earlier. if the readq was empty, put them at the head of
04052                the queue, and if it was not, put them just after the frame that was
04053                at the end of the queue.
04054             */
04055             if (AST_LIST_NEXT(f, frame_list)) {
04056                if (!readq_tail) {
04057                   ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
04058                } else {
04059                   __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
04060                }
04061                ast_frfree(AST_LIST_NEXT(f, frame_list));
04062                AST_LIST_NEXT(f, frame_list) = NULL;
04063             }
04064 
04065             /* Run generator sitting on the line if timing device not available
04066             * and synchronous generation of outgoing frames is necessary       */
04067             ast_read_generator_actions(chan, f);
04068          }
04069          break;
04070       default:
04071          /* Just pass it on! */
04072          break;
04073       }
04074    } else {
04075       /* Make sure we always return NULL in the future */
04076       chan->_softhangup |= AST_SOFTHANGUP_DEV;
04077       if (cause)
04078          chan->hangupcause = cause;
04079       if (chan->generator)
04080          ast_deactivate_generator(chan);
04081       /* We no longer End the CDR here */
04082    }
04083 
04084    /* High bit prints debugging */
04085    if (chan->fin & DEBUGCHAN_FLAG)
04086       ast_frame_dump(chan->name, f, "<<");
04087    chan->fin = FRAMECOUNT_INC(chan->fin);
04088 
04089 done:
04090    if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
04091       chan->generator->digit(chan, f->subclass.integer);
04092 
04093    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
04094       /* The list gets recreated if audiohooks are added again later */
04095       ast_audiohook_detach_list(chan->audiohooks);
04096       chan->audiohooks = NULL;
04097    }
04098    ast_channel_unlock(chan);
04099    return f;
04100 }
04101 
04102 int ast_internal_timing_enabled(struct ast_channel *chan)
04103 {
04104    return (ast_opt_internal_timing && chan->timingfd > -1);
04105 }
04106 
04107 struct ast_frame *ast_read(struct ast_channel *chan)
04108 {
04109    return __ast_read(chan, 0);
04110 }
04111 
04112 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
04113 {
04114    return __ast_read(chan, 1);
04115 }
04116 
04117 int ast_indicate(struct ast_channel *chan, int condition)
04118 {
04119    return ast_indicate_data(chan, condition, NULL, 0);
04120 }
04121 
04122 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
04123 {
04124    /* Don't include a default case here so that we get compiler warnings
04125     * when a new type is added. */
04126 
04127    switch (condition) {
04128    case AST_CONTROL_PROGRESS:
04129    case AST_CONTROL_PROCEEDING:
04130    case AST_CONTROL_VIDUPDATE:
04131    case AST_CONTROL_SRCUPDATE:
04132    case AST_CONTROL_SRCCHANGE:
04133    case AST_CONTROL_RADIO_KEY:
04134    case AST_CONTROL_RADIO_UNKEY:
04135    case AST_CONTROL_OPTION:
04136    case AST_CONTROL_WINK:
04137    case AST_CONTROL_FLASH:
04138    case AST_CONTROL_OFFHOOK:
04139    case AST_CONTROL_TAKEOFFHOOK:
04140    case AST_CONTROL_ANSWER:
04141    case AST_CONTROL_HANGUP:
04142    case AST_CONTROL_CONNECTED_LINE:
04143    case AST_CONTROL_REDIRECTING:
04144    case AST_CONTROL_TRANSFER:
04145    case AST_CONTROL_T38_PARAMETERS:
04146    case _XXX_AST_CONTROL_T38:
04147    case AST_CONTROL_CC:
04148    case AST_CONTROL_READ_ACTION:
04149    case AST_CONTROL_AOC:
04150       break;
04151 
04152    case AST_CONTROL_CONGESTION:
04153    case AST_CONTROL_BUSY:
04154    case AST_CONTROL_RINGING:
04155    case AST_CONTROL_RING:
04156    case AST_CONTROL_HOLD:
04157    case AST_CONTROL_UNHOLD:
04158       return 1;
04159    }
04160 
04161    return 0;
04162 }
04163 
04164 int ast_indicate_data(struct ast_channel *chan, int _condition,
04165       const void *data, size_t datalen)
04166 {
04167    /* By using an enum, we'll get compiler warnings for values not handled 
04168     * in switch statements. */
04169    enum ast_control_frame_type condition = _condition;
04170    struct ast_tone_zone_sound *ts = NULL;
04171    int res;
04172    /* this frame is used by framehooks. if it is set, we must free it at the end of this function */
04173    struct ast_frame *awesome_frame = NULL;
04174 
04175    ast_channel_lock(chan);
04176 
04177    /* Don't bother if the channel is about to go away, anyway. */
04178    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
04179       ast_channel_unlock(chan);
04180       res = -1;
04181       goto indicate_cleanup;
04182    }
04183 
04184    if (!ast_framehook_list_is_empty(chan->framehooks)) {
04185       /* Do framehooks now, do it, go, go now */
04186       struct ast_frame frame = {
04187          .frametype = AST_FRAME_CONTROL,
04188          .subclass.integer = condition,
04189          .data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
04190          .datalen = datalen
04191       };
04192 
04193       /* we have now committed to freeing this frame */
04194       awesome_frame = ast_frdup(&frame);
04195 
04196       /* who knows what we will get back! the anticipation is killing me. */
04197       if (!(awesome_frame = ast_framehook_list_read_event(chan->framehooks, &frame))) {
04198          ast_channel_unlock(chan);
04199          res = 0;
04200          goto indicate_cleanup;
04201       }
04202 
04203       condition = awesome_frame->subclass.integer;
04204       data = awesome_frame->data.ptr;
04205       datalen = awesome_frame->datalen;
04206    }
04207 
04208    switch (condition) {
04209    case AST_CONTROL_CONNECTED_LINE:
04210       {
04211          struct ast_party_connected_line connected;
04212 
04213          ast_party_connected_line_set_init(&connected, &chan->connected);
04214          res = ast_connected_line_parse_data(data, datalen, &connected);
04215          if (!res) {
04216             ast_channel_set_connected_line(chan, &connected, NULL);
04217          }
04218          ast_party_connected_line_free(&connected);
04219       }
04220       break;
04221 
04222    case AST_CONTROL_REDIRECTING:
04223       {
04224          struct ast_party_redirecting redirecting;
04225 
04226          ast_party_redirecting_set_init(&redirecting, &chan->redirecting);
04227          res = ast_redirecting_parse_data(data, datalen, &redirecting);
04228          if (!res) {
04229             ast_channel_set_redirecting(chan, &redirecting, NULL);
04230          }
04231          ast_party_redirecting_free(&redirecting);
04232       }
04233       break;
04234    
04235    default:
04236       break;
04237    }
04238 
04239    if (chan->tech->indicate) {
04240       /* See if the channel driver can handle this condition. */
04241       res = chan->tech->indicate(chan, condition, data, datalen);
04242    } else {
04243       res = -1;
04244    }
04245 
04246    ast_channel_unlock(chan);
04247 
04248    if (!res) {
04249       /* The channel driver successfully handled this indication */
04250       if (is_visible_indication(condition)) {
04251          chan->visible_indication = condition;
04252       }
04253       res = 0;
04254       goto indicate_cleanup;
04255    }
04256 
04257    /* The channel driver does not support this indication, let's fake
04258     * it by doing our own tone generation if applicable. */
04259 
04260    /*!\note If we compare the enumeration type, which does not have any
04261     * negative constants, the compiler may optimize this code away.
04262     * Therefore, we must perform an integer comparison here. */
04263    if (_condition < 0) {
04264       /* Stop any tones that are playing */
04265       ast_playtones_stop(chan);
04266       res = 0;
04267       goto indicate_cleanup;
04268    }
04269 
04270    /* Handle conditions that we have tones for. */
04271    switch (condition) {
04272    case _XXX_AST_CONTROL_T38:
04273       /* deprecated T.38 control frame */
04274       res = -1;
04275       goto indicate_cleanup;
04276    case AST_CONTROL_T38_PARAMETERS:
04277       /* there is no way to provide 'default' behavior for these
04278        * control frames, so we need to return failure, but there
04279        * is also no value in the log message below being emitted
04280        * since failure to handle these frames is not an 'error'
04281        * so just return right now. in addition, we want to return
04282        * whatever value the channel driver returned, in case it
04283        * has some meaning.*/
04284       goto indicate_cleanup;
04285    case AST_CONTROL_RINGING:
04286       ts = ast_get_indication_tone(chan->zone, "ring");
04287       /* It is common practice for channel drivers to return -1 if trying
04288        * to indicate ringing on a channel which is up. The idea is to let the
04289        * core generate the ringing inband. However, we don't want the
04290        * warning message about not being able to handle the specific indication
04291        * to print nor do we want ast_indicate_data to return an "error" for this
04292        * condition
04293        */
04294       if (chan->_state == AST_STATE_UP) {
04295          res = 0;
04296       }
04297       break;
04298    case AST_CONTROL_BUSY:
04299       ts = ast_get_indication_tone(chan->zone, "busy");
04300       break;
04301    case AST_CONTROL_CONGESTION:
04302       ts = ast_get_indication_tone(chan->zone, "congestion");
04303       break;
04304    case AST_CONTROL_PROGRESS:
04305    case AST_CONTROL_PROCEEDING:
04306    case AST_CONTROL_VIDUPDATE:
04307    case AST_CONTROL_SRCUPDATE:
04308    case AST_CONTROL_SRCCHANGE:
04309    case AST_CONTROL_RADIO_KEY:
04310    case AST_CONTROL_RADIO_UNKEY:
04311    case AST_CONTROL_OPTION:
04312    case AST_CONTROL_WINK:
04313    case AST_CONTROL_FLASH:
04314    case AST_CONTROL_OFFHOOK:
04315    case AST_CONTROL_TAKEOFFHOOK:
04316    case AST_CONTROL_ANSWER:
04317    case AST_CONTROL_HANGUP:
04318    case AST_CONTROL_RING:
04319    case AST_CONTROL_HOLD:
04320    case AST_CONTROL_UNHOLD:
04321    case AST_CONTROL_TRANSFER:
04322    case AST_CONTROL_CONNECTED_LINE:
04323    case AST_CONTROL_REDIRECTING:
04324    case AST_CONTROL_CC:
04325    case AST_CONTROL_READ_ACTION:
04326    case AST_CONTROL_AOC:
04327       /* Nothing left to do for these. */
04328       res = 0;
04329       break;
04330    }
04331 
04332    if (ts) {
04333       /* We have a tone to play, yay. */
04334       ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
04335       ast_playtones_start(chan, 0, ts->data, 1);
04336       ts = ast_tone_zone_sound_unref(ts);
04337       res = 0;
04338       chan->visible_indication = condition;
04339    }
04340 
04341    if (res) {
04342       /* not handled */
04343       ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
04344    }
04345 
04346 indicate_cleanup:
04347    if (awesome_frame) {
04348       ast_frfree(awesome_frame);
04349    }
04350 
04351    return res;
04352 }
04353 
04354 int ast_recvchar(struct ast_channel *chan, int timeout)
04355 {
04356    int c;
04357    char *buf = ast_recvtext(chan, timeout);
04358    if (buf == NULL)
04359       return -1;  /* error or timeout */
04360    c = *(unsigned char *)buf;
04361    ast_free(buf);
04362    return c;
04363 }
04364 
04365 char *ast_recvtext(struct ast_channel *chan, int timeout)
04366 {
04367    int res, done = 0;
04368    char *buf = NULL;
04369    
04370    while (!done) {
04371       struct ast_frame *f;
04372       if (ast_check_hangup(chan))
04373          break;
04374       res = ast_waitfor(chan, timeout);
04375       if (res <= 0) /* timeout or error */
04376          break;
04377       timeout = res; /* update timeout */
04378       f = ast_read(chan);
04379       if (f == NULL)
04380          break; /* no frame */
04381       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP)
04382          done = 1;   /* force a break */
04383       else if (f->frametype == AST_FRAME_TEXT) {      /* what we want */
04384          buf = ast_strndup((char *) f->data.ptr, f->datalen);  /* dup and break */
04385          done = 1;
04386       }
04387       ast_frfree(f);
04388    }
04389    return buf;
04390 }
04391 
04392 int ast_sendtext(struct ast_channel *chan, const char *text)
04393 {
04394    int res = 0;
04395    /* Stop if we're a zombie or need a soft hangup */
04396    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
04397       return -1;
04398    CHECK_BLOCKING(chan);
04399    if (chan->tech->send_text)
04400       res = chan->tech->send_text(chan, text);
04401    ast_clear_flag(chan, AST_FLAG_BLOCKING);
04402    return res;
04403 }
04404 
04405 int ast_senddigit_begin(struct ast_channel *chan, char digit)
04406 {
04407    /* Device does not support DTMF tones, lets fake
04408     * it by doing our own generation. */
04409    static const char * const dtmf_tones[] = {
04410       "941+1336", /* 0 */
04411       "697+1209", /* 1 */
04412       "697+1336", /* 2 */
04413       "697+1477", /* 3 */
04414       "770+1209", /* 4 */
04415       "770+1336", /* 5 */
04416       "770+1477", /* 6 */
04417       "852+1209", /* 7 */
04418       "852+1336", /* 8 */
04419       "852+1477", /* 9 */
04420       "697+1633", /* A */
04421       "770+1633", /* B */
04422       "852+1633", /* C */
04423       "941+1633", /* D */
04424       "941+1209", /* * */
04425       "941+1477"  /* # */
04426    };
04427 
04428    if (!chan->tech->send_digit_begin)
04429       return 0;
04430 
04431    if (!chan->tech->send_digit_begin(chan, digit))
04432       return 0;
04433 
04434    if (digit >= '0' && digit <='9')
04435       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
04436    else if (digit >= 'A' && digit <= 'D')
04437       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
04438    else if (digit == '*')
04439       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
04440    else if (digit == '#')
04441       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
04442    else {
04443       /* not handled */
04444       ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
04445    }
04446 
04447    return 0;
04448 }
04449 
04450 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
04451 {
04452    int res = -1;
04453 
04454    if (chan->tech->send_digit_end)
04455       res = chan->tech->send_digit_end(chan, digit, duration);
04456 
04457    if (res && chan->generator)
04458       ast_playtones_stop(chan);
04459    
04460    return 0;
04461 }
04462 
04463 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
04464 {
04465    if (chan->tech->send_digit_begin) {
04466       ast_senddigit_begin(chan, digit);
04467       ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04468    }
04469    
04470    return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04471 }
04472 
04473 int ast_prod(struct ast_channel *chan)
04474 {
04475    struct ast_frame a = { AST_FRAME_VOICE };
04476    char nothing[128];
04477 
04478    /* Send an empty audio frame to get things moving */
04479    if (chan->_state != AST_STATE_UP) {
04480       ast_debug(1, "Prodding channel '%s'\n", chan->name);
04481       a.subclass.codec = chan->rawwriteformat;
04482       a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
04483       a.src = "ast_prod"; /* this better match check in ast_write */
04484       if (ast_write(chan, &a))
04485          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
04486    }
04487    return 0;
04488 }
04489 
04490 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
04491 {
04492    int res;
04493    if (!chan->tech->write_video)
04494       return 0;
04495    res = ast_write(chan, fr);
04496    if (!res)
04497       res = 1;
04498    return res;
04499 }
04500 
04501 struct plc_ds {
04502    /* A buffer in which to store SLIN PLC
04503     * samples generated by the generic PLC
04504     * functionality in plc.c
04505     */
04506    int16_t *samples_buf;
04507    /* The current number of samples in the
04508     * samples_buf
04509     */
04510    size_t num_samples;
04511    plc_state_t plc_state;
04512 };
04513 
04514 static void plc_ds_destroy(void *data)
04515 {
04516    struct plc_ds *plc = data;
04517    ast_free(plc->samples_buf);
04518    ast_free(plc);
04519 }
04520 
04521 static struct ast_datastore_info plc_ds_info = {
04522    .type = "plc",
04523    .destroy = plc_ds_destroy,
04524 };
04525 
04526 static void adjust_frame_for_plc(struct ast_channel *chan, struct ast_frame *frame, struct ast_datastore *datastore)
04527 {
04528    int num_new_samples = frame->samples;
04529    struct plc_ds *plc = datastore->data;
04530 
04531    /* As a general note, let me explain the somewhat odd calculations used when taking
04532     * the frame offset into account here. According to documentation in frame.h, the frame's
04533     * offset field indicates the number of bytes that the audio is offset. The plc->samples_buf
04534     * is not an array of bytes, but rather an array of 16-bit integers since it holds SLIN
04535     * samples. So I had two choices to make here with the offset.
04536     * 
04537     * 1. Make the offset AST_FRIENDLY_OFFSET bytes. The main downside for this is that
04538     *    I can't just add AST_FRIENDLY_OFFSET to the plc->samples_buf and have the pointer
04539     *    arithmetic come out right. I would have to do some odd casting or division for this to
04540     *    work as I wanted.
04541     * 2. Make the offset AST_FRIENDLY_OFFSET * 2 bytes. This allows the pointer arithmetic
04542     *    to work out better with the plc->samples_buf. The downside here is that the buffer's
04543     *    allocation contains an extra 64 bytes of unused space.
04544     * 
04545     * I decided to go with option 2. This is why in the calloc statement and the statement that
04546     * sets the frame's offset, AST_FRIENDLY_OFFSET is multiplied by 2.
04547     */
04548 
04549    /* If this audio frame has no samples to fill in, ignore it */
04550    if (!num_new_samples) {
04551       return;
04552    }
04553 
04554    /* First, we need to be sure that our buffer is large enough to accomodate
04555     * the samples we need to fill in. This will likely only occur on the first
04556     * frame we write.
04557     */
04558    if (plc->num_samples < num_new_samples) {
04559       ast_free(plc->samples_buf);
04560       plc->samples_buf = ast_calloc(1, (num_new_samples * sizeof(*plc->samples_buf)) + (AST_FRIENDLY_OFFSET * 2));
04561       if (!plc->samples_buf) {
04562          ast_channel_datastore_remove(chan, datastore);
04563          ast_datastore_free(datastore);
04564          return;
04565       }
04566       plc->num_samples = num_new_samples;
04567    }
04568 
04569    if (frame->datalen == 0) {
04570       plc_fillin(&plc->plc_state, plc->samples_buf + AST_FRIENDLY_OFFSET, frame->samples);
04571       frame->data.ptr = plc->samples_buf + AST_FRIENDLY_OFFSET;
04572       frame->datalen = num_new_samples * 2;
04573       frame->offset = AST_FRIENDLY_OFFSET * 2;
04574    } else {
04575       plc_rx(&plc->plc_state, frame->data.ptr, frame->samples);
04576    }
04577 }
04578 
04579 static void apply_plc(struct ast_channel *chan, struct ast_frame *frame)
04580 {
04581    struct ast_datastore *datastore;
04582    struct plc_ds *plc;
04583 
04584    datastore = ast_channel_datastore_find(chan, &plc_ds_info, NULL);
04585    if (datastore) {
04586       plc = datastore->data;
04587       adjust_frame_for_plc(chan, frame, datastore);
04588       return;
04589    }
04590 
04591    datastore = ast_datastore_alloc(&plc_ds_info, NULL);
04592    if (!datastore) {
04593       return;
04594    }
04595    plc = ast_calloc(1, sizeof(*plc));
04596    if (!plc) {
04597       ast_datastore_free(datastore);
04598       return;
04599    }
04600    datastore->data = plc;
04601    ast_channel_datastore_add(chan, datastore);
04602    adjust_frame_for_plc(chan, frame, datastore);
04603 }
04604 
04605 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
04606 {
04607    int res = -1;
04608    struct ast_frame *f = NULL;
04609    int count = 0;
04610 
04611    /*Deadlock avoidance*/
04612    while(ast_channel_trylock(chan)) {
04613       /*cannot goto done since the channel is not locked*/
04614       if(count++ > 10) {
04615          ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
04616          return 0;
04617       }
04618       usleep(1);
04619    }
04620    /* Stop if we're a zombie or need a soft hangup */
04621    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
04622       goto done;
04623 
04624    /* Handle any pending masquerades */
04625    if (chan->masq) {
04626       ast_channel_unlock(chan);
04627       if (ast_do_masquerade(chan)) {
04628          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
04629          return res; /* no need to goto done: chan is already unlocked for masq */
04630       }
04631       ast_channel_lock(chan);
04632    }
04633    if (chan->masqr) {
04634       res = 0; /* XXX explain, why 0 ? */
04635       goto done;
04636    }
04637 
04638    /* Perform the framehook write event here. After the frame enters the framehook list
04639     * there is no telling what will happen, how awesome is that!!! */
04640    if (!(fr = ast_framehook_list_write_event(chan->framehooks, fr))) {
04641       res = 0;
04642       goto done;
04643    }
04644 
04645    if (chan->generatordata && (!fr->src || strcasecmp(fr->src, "ast_prod"))) {
04646       if (ast_test_flag(chan, AST_FLAG_WRITE_INT)) {
04647             ast_deactivate_generator(chan);
04648       } else {
04649          if (fr->frametype == AST_FRAME_DTMF_END) {
04650             /* There is a generator running while we're in the middle of a digit.
04651              * It's probably inband DTMF, so go ahead and pass it so it can
04652              * stop the generator */
04653             ast_clear_flag(chan, AST_FLAG_BLOCKING);
04654             ast_channel_unlock(chan);
04655             res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
04656             ast_channel_lock(chan);
04657             CHECK_BLOCKING(chan);
04658          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_UNHOLD) {
04659             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
04660             res = (chan->tech->indicate == NULL) ? 0 :
04661                chan->tech->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
04662          }
04663          res = 0; /* XXX explain, why 0 ? */
04664          goto done;
04665       }
04666    }
04667    /* High bit prints debugging */
04668    if (chan->fout & DEBUGCHAN_FLAG)
04669       ast_frame_dump(chan->name, fr, ">>");
04670    CHECK_BLOCKING(chan);
04671    switch (fr->frametype) {
04672    case AST_FRAME_CONTROL:
04673       res = (chan->tech->indicate == NULL) ? 0 :
04674          chan->tech->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
04675       break;
04676    case AST_FRAME_DTMF_BEGIN:
04677       if (chan->audiohooks) {
04678          struct ast_frame *old_frame = fr;
04679          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
04680          if (old_frame != fr)
04681             f = fr;
04682       }
04683       send_dtmf_event(chan, "Sent", fr->subclass.integer, "Yes", "No");
04684       ast_clear_flag(chan, AST_FLAG_BLOCKING);
04685       ast_channel_unlock(chan);
04686       res = ast_senddigit_begin(chan, fr->subclass.integer);
04687       ast_channel_lock(chan);
04688       CHECK_BLOCKING(chan);
04689       break;
04690    case AST_FRAME_DTMF_END:
04691       if (chan->audiohooks) {
04692          struct ast_frame *new_frame = fr;
04693 
04694          new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
04695          if (new_frame != fr) {
04696             ast_frfree(new_frame);
04697          }
04698       }
04699       send_dtmf_event(chan, "Sent", fr->subclass.integer, "No", "Yes");
04700       ast_clear_flag(chan, AST_FLAG_BLOCKING);
04701       ast_channel_unlock(chan);
04702       res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
04703       ast_channel_lock(chan);
04704       CHECK_BLOCKING(chan);
04705       break;
04706    case AST_FRAME_TEXT:
04707       if (fr->subclass.integer == AST_FORMAT_T140) {
04708          res = (chan->tech->write_text == NULL) ? 0 :
04709             chan->tech->write_text(chan, fr);
04710       } else {
04711          res = (chan->tech->send_text == NULL) ? 0 :
04712             chan->tech->send_text(chan, (char *) fr->data.ptr);
04713       }
04714       break;
04715    case AST_FRAME_HTML:
04716       res = (chan->tech->send_html == NULL) ? 0 :
04717          chan->tech->send_html(chan, fr->subclass.integer, (char *) fr->data.ptr, fr->datalen);
04718       break;
04719    case AST_FRAME_VIDEO:
04720       /* XXX Handle translation of video codecs one day XXX */
04721       res = (chan->tech->write_video == NULL) ? 0 :
04722          chan->tech->write_video(chan, fr);
04723       break;
04724    case AST_FRAME_MODEM:
04725       res = (chan->tech->write == NULL) ? 0 :
04726          chan->tech->write(chan, fr);
04727       break;
04728    case AST_FRAME_VOICE:
04729       if (chan->tech->write == NULL)
04730          break;   /*! \todo XXX should return 0 maybe ? */
04731 
04732       if (ast_opt_generic_plc && fr->subclass.codec == AST_FORMAT_SLINEAR) {
04733          apply_plc(chan, fr);
04734       }
04735 
04736       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
04737       if (fr->subclass.codec == chan->rawwriteformat)
04738          f = fr;
04739       else
04740          f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
04741 
04742       if (!f) {
04743          res = 0;
04744          break;
04745       }
04746 
04747       if (chan->audiohooks) {
04748          struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
04749          int freeoldlist = 0;
04750 
04751          if (f != fr) {
04752             freeoldlist = 1;
04753          }
04754 
04755          /* Since ast_audiohook_write may return a new frame, and the cur frame is
04756           * an item in a list of frames, create a new list adding each cur frame back to it
04757           * regardless if the cur frame changes or not. */
04758          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
04759             new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, cur);
04760 
04761             /* if this frame is different than cur, preserve the end of the list,
04762              * free the old frames, and set cur to be the new frame */
04763             if (new_frame != cur) {
04764 
04765                /* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
04766                 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
04767                 * times it may override the previous frame we got from it unless we dup it */
04768                if ((dup = ast_frisolate(new_frame))) {
04769                   AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
04770                   if (freeoldlist) {
04771                      AST_LIST_NEXT(cur, frame_list) = NULL;
04772                      ast_frfree(cur);
04773                   }
04774                   if (new_frame != dup) {
04775                      ast_frfree(new_frame);
04776                   }
04777                   cur = dup;
04778                }
04779             }
04780 
04781             /* now, regardless if cur is new or not, add it to the new list,
04782              * if the new list has not started, cur will become the first item. */
04783             if (prev) {
04784                AST_LIST_NEXT(prev, frame_list) = cur;
04785             } else {
04786                f = cur; /* set f to be the beginning of our new list */
04787             }
04788             prev = cur;
04789          }
04790       }
04791       
04792       /* If Monitor is running on this channel, then we have to write frames out there too */
04793       /* the translator on chan->writetrans may have returned multiple frames
04794          from the single frame we passed in; if so, feed each one of them to the
04795          monitor */
04796       if (chan->monitor && chan->monitor->write_stream) {
04797          struct ast_frame *cur;
04798 
04799          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
04800          /* XXX must explain this code */
04801 #ifndef MONITOR_CONSTANT_DELAY
04802             int jump = chan->insmpl - chan->outsmpl - 4 * cur->samples;
04803             if (jump >= 0) {
04804                jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04805                if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
04806                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
04807                chan->outsmpl += (chan->insmpl - chan->outsmpl) + cur->samples;
04808             } else {
04809                chan->outsmpl += cur->samples;
04810             }
04811 #else
04812             int jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04813             if (jump - MONITOR_DELAY >= 0) {
04814                if (ast_seekstream(chan->monitor->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1)
04815                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
04816                chan->outsmpl += chan->insmpl - chan->outsmpl;
04817             } else {
04818                chan->outsmpl += cur->samples;
04819             }
04820 #endif
04821             if (chan->monitor->state == AST_MONITOR_RUNNING) {
04822                if (ast_writestream(chan->monitor->write_stream, cur) < 0)
04823                   ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
04824             }
04825          }
04826       }
04827 
04828       /* the translator on chan->writetrans may have returned multiple frames
04829          from the single frame we passed in; if so, feed each one of them to the
04830          channel, freeing each one after it has been written */
04831       if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
04832          struct ast_frame *cur, *next;
04833          unsigned int skip = 0;
04834 
04835          for (cur = f, next = AST_LIST_NEXT(cur, frame_list);
04836               cur;
04837               cur = next, next = cur ? AST_LIST_NEXT(cur, frame_list) : NULL) {
04838             if (!skip) {
04839                if ((res = chan->tech->write(chan, cur)) < 0) {
04840                   chan->_softhangup |= AST_SOFTHANGUP_DEV;
04841                   skip = 1;
04842                } else if (next) {
04843                   /* don't do this for the last frame in the list,
04844                      as the code outside the loop will do it once
04845                   */
04846                   chan->fout = FRAMECOUNT_INC(chan->fout);
04847                }
04848             }
04849             ast_frfree(cur);
04850          }
04851 
04852          /* reset f so the code below doesn't attempt to free it */
04853          f = NULL;
04854       } else {
04855          res = chan->tech->write(chan, f);
04856       }
04857       break;
04858    case AST_FRAME_NULL:
04859    case AST_FRAME_IAX:
04860       /* Ignore these */
04861       res = 0;
04862       break;
04863    default:
04864       /* At this point, fr is the incoming frame and f is NULL.  Channels do
04865        * not expect to get NULL as a frame pointer and will segfault.  Hence,
04866        * we output the original frame passed in. */
04867       res = chan->tech->write(chan, fr);
04868       break;
04869    }
04870 
04871    if (f && f != fr)
04872       ast_frfree(f);
04873    ast_clear_flag(chan, AST_FLAG_BLOCKING);
04874 
04875    /* Consider a write failure to force a soft hangup */
04876    if (res < 0) {
04877       chan->_softhangup |= AST_SOFTHANGUP_DEV;
04878    } else {
04879       chan->fout = FRAMECOUNT_INC(chan->fout);
04880    }
04881 done:
04882    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
04883       /* The list gets recreated if audiohooks are added again later */
04884       ast_audiohook_detach_list(chan->audiohooks);
04885       chan->audiohooks = NULL;
04886    }
04887    ast_channel_unlock(chan);
04888    return res;
04889 }
04890 
04891 static int set_format(struct ast_channel *chan, format_t fmt, format_t *rawformat, format_t *format,
04892             struct ast_trans_pvt **trans, const int direction)
04893 {
04894    format_t native, native_fmt = ast_best_codec(fmt);
04895    int res;
04896    char from[200], to[200];
04897    
04898    /* Make sure we only consider audio */
04899    fmt &= AST_FORMAT_AUDIO_MASK;
04900    
04901    native = chan->nativeformats;
04902 
04903    if (!fmt || !native) /* No audio requested */
04904       return 0;   /* Let's try a call without any sounds (video, text) */
04905 
04906    /* See if the underlying channel driver is capable of performing transcoding for us */
04907    if (!ast_channel_setoption(chan, direction ? AST_OPTION_FORMAT_WRITE : AST_OPTION_FORMAT_READ, &native_fmt, sizeof(int*), 0)) {
04908       ast_debug(1, "Channel driver natively set channel %s to %s format %s\n", chan->name,
04909            direction ? "write" : "read", ast_getformatname(native_fmt));
04910       chan->nativeformats = *rawformat = *format = native_fmt;
04911       if (*trans) {
04912          ast_translator_free_path(*trans);
04913       }
04914       *trans = NULL;
04915       return 0;
04916    }
04917 
04918    /* Find a translation path from the native format to one of the desired formats */
04919    if (!direction)
04920       /* reading */
04921       res = ast_translator_best_choice(&fmt, &native);
04922    else
04923       /* writing */
04924       res = ast_translator_best_choice(&native, &fmt);
04925 
04926    if (res < 0) {
04927       ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
04928          ast_getformatname_multiple(from, sizeof(from), native),
04929          ast_getformatname_multiple(to, sizeof(to), fmt));
04930       return -1;
04931    }
04932    
04933    /* Now we have a good choice for both. */
04934    ast_channel_lock(chan);
04935 
04936    if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
04937       /* the channel is already in these formats, so nothing to do */
04938       ast_channel_unlock(chan);
04939       return 0;
04940    }
04941 
04942    *rawformat = native;
04943    /* User perspective is fmt */
04944    *format = fmt;
04945    /* Free any read translation we have right now */
04946    if (*trans)
04947       ast_translator_free_path(*trans);
04948    /* Build a translation path from the raw format to the desired format */
04949    if (!direction)
04950       /* reading */
04951       *trans = ast_translator_build_path(*format, *rawformat);
04952    else
04953       /* writing */
04954       *trans = ast_translator_build_path(*rawformat, *format);
04955    ast_channel_unlock(chan);
04956    ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
04957       direction ? "write" : "read", ast_getformatname(fmt));
04958    return 0;
04959 }
04960 
04961 int ast_set_read_format(struct ast_channel *chan, format_t fmt)
04962 {
04963    return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
04964            &chan->readtrans, 0);
04965 }
04966 
04967 int ast_set_write_format(struct ast_channel *chan, format_t fmt)
04968 {
04969    return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
04970            &chan->writetrans, 1);
04971 }
04972 
04973 const char *ast_channel_reason2str(int reason)
04974 {
04975    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
04976    {
04977    case 0:
04978       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
04979    case AST_CONTROL_HANGUP:
04980       return "Hangup";
04981    case AST_CONTROL_RING:
04982       return "Local Ring";
04983    case AST_CONTROL_RINGING:
04984       return "Remote end Ringing";
04985    case AST_CONTROL_ANSWER:
04986       return "Remote end has Answered";
04987    case AST_CONTROL_BUSY:
04988       return "Remote end is Busy";
04989    case AST_CONTROL_CONGESTION:
04990       return "Congestion (circuits busy)";
04991    default:
04992       return "Unknown Reason!!";
04993    }
04994 }
04995 
04996 static void handle_cause(int cause, int *outstate)
04997 {
04998    if (outstate) {
04999       /* compute error and return */
05000       if (cause == AST_CAUSE_BUSY)
05001          *outstate = AST_CONTROL_BUSY;
05002       else if (cause == AST_CAUSE_CONGESTION)
05003          *outstate = AST_CONTROL_CONGESTION;
05004       else
05005          *outstate = 0;
05006    }
05007 }
05008 
05009 struct ast_channel *ast_call_forward(struct ast_channel *caller, struct ast_channel *orig, int *timeout, format_t format, struct outgoing_helper *oh, int *outstate)
05010 {
05011    char tmpchan[256];
05012    struct ast_channel *new = NULL;
05013    struct ast_party_redirecting *apr = &orig->redirecting;
05014    char *data, *type;
05015    int cause = 0;
05016    int res;
05017 
05018    /* gather data and request the new forward channel */
05019    ast_copy_string(tmpchan, orig->call_forward, sizeof(tmpchan));
05020    if ((data = strchr(tmpchan, '/'))) {
05021       *data++ = '\0';
05022       type = tmpchan;
05023    } else {
05024       const char *forward_context;
05025       ast_channel_lock(orig);
05026       forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
05027       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", orig->call_forward, S_OR(forward_context, orig->context));
05028       ast_channel_unlock(orig);
05029       data = tmpchan;
05030       type = "Local";
05031    }
05032    if (!(new = ast_request(type, format, orig, data, &cause))) {
05033       ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
05034       handle_cause(cause, outstate);
05035       ast_hangup(orig);
05036       return NULL;
05037    }
05038 
05039    ast_channel_set_redirecting(new, apr, NULL);
05040 
05041    /* Copy/inherit important information into new channel */
05042    if (oh) {
05043       if (oh->vars) {
05044          ast_set_variables(new, oh->vars);
05045       }
05046       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
05047          ast_set_callerid(new, oh->cid_num, oh->cid_name, oh->cid_num);
05048       }
05049       if (oh->parent_channel) {
05050          ast_channel_update_redirecting(oh->parent_channel, apr, NULL);
05051          ast_channel_inherit_variables(oh->parent_channel, new);
05052          ast_channel_datastore_inherit(oh->parent_channel, new);
05053       }
05054       if (oh->account) {
05055          ast_cdr_setaccount(new, oh->account);
05056       }
05057    } else if (caller) { /* no outgoing helper so use caller if avaliable */
05058       ast_channel_update_redirecting(caller, apr, NULL);
05059       ast_channel_inherit_variables(caller, new);
05060       ast_channel_datastore_inherit(caller, new);
05061    }
05062 
05063    ast_channel_lock(orig);
05064    while (ast_channel_trylock(new)) {
05065       CHANNEL_DEADLOCK_AVOIDANCE(orig);
05066    }
05067    ast_copy_flags(new->cdr, orig->cdr, AST_CDR_FLAG_ORIGINATED);
05068    ast_string_field_set(new, accountcode, orig->accountcode);
05069    ast_party_caller_copy(&new->caller, &orig->caller);
05070    ast_party_connected_line_copy(&new->connected, &orig->connected);
05071    ast_channel_unlock(new);
05072    ast_channel_unlock(orig);
05073 
05074    /* call new channel */
05075    res = ast_call(new, data, 0);
05076    if (timeout) {
05077       *timeout = res;
05078    }
05079    if (res) {
05080       ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
05081       ast_hangup(orig);
05082       ast_hangup(new);
05083       return NULL;
05084    }
05085    ast_hangup(orig);
05086 
05087    return new;
05088 }
05089 
05090 struct ast_channel *__ast_request_and_dial(const char *type, format_t format, const struct ast_channel *requestor, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
05091 {
05092    int dummy_outstate;
05093    int cause = 0;
05094    struct ast_channel *chan;
05095    int res = 0;
05096    int last_subclass = 0;
05097    struct ast_party_connected_line connected;
05098    
05099    if (outstate)
05100       *outstate = 0;
05101    else
05102       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
05103 
05104    chan = ast_request(type, format, requestor, data, &cause);
05105    if (!chan) {
05106       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
05107       handle_cause(cause, outstate);
05108       return NULL;
05109    }
05110 
05111    if (oh) {
05112       if (oh->vars)  
05113          ast_set_variables(chan, oh->vars);
05114       /* XXX why is this necessary, for the parent_channel perhaps ? */
05115       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
05116          ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
05117       if (oh->parent_channel) {
05118          ast_channel_inherit_variables(oh->parent_channel, chan);
05119          ast_channel_datastore_inherit(oh->parent_channel, chan);
05120       }
05121       if (oh->account)
05122          ast_cdr_setaccount(chan, oh->account); 
05123    }
05124 
05125    ast_set_callerid(chan, cid_num, cid_name, cid_num);
05126    ast_set_flag(chan->cdr, AST_CDR_FLAG_ORIGINATED);
05127    ast_party_connected_line_set_init(&connected, &chan->connected);
05128    if (cid_num) {
05129       connected.id.number.valid = 1;
05130       connected.id.number.str = (char *) cid_num;
05131       connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05132    }
05133    if (cid_name) {
05134       connected.id.name.valid = 1;
05135       connected.id.name.str = (char *) cid_name;
05136       connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05137    }
05138    ast_channel_set_connected_line(chan, &connected, NULL);
05139 
05140    if (ast_call(chan, data, 0)) {   /* ast_call failed... */
05141       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
05142    } else {
05143       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
05144       while (timeout && chan->_state != AST_STATE_UP) {
05145          struct ast_frame *f;
05146          res = ast_waitfor(chan, timeout);
05147          if (res == 0) { /* timeout, treat it like ringing */
05148             *outstate = AST_CONTROL_RINGING;
05149             break;
05150          }
05151          if (res < 0) /* error or done */
05152             break;
05153          if (timeout > -1)
05154             timeout = res;
05155          if (!ast_strlen_zero(chan->call_forward)) {
05156             if (!(chan = ast_call_forward(NULL, chan, NULL, format, oh, outstate))) {
05157                return NULL;
05158             }
05159             continue;
05160          }
05161 
05162          f = ast_read(chan);
05163          if (!f) {
05164             *outstate = AST_CONTROL_HANGUP;
05165             res = 0;
05166             break;
05167          }
05168          if (f->frametype == AST_FRAME_CONTROL) {
05169             switch (f->subclass.integer) {
05170             case AST_CONTROL_RINGING:  /* record but keep going */
05171                *outstate = f->subclass.integer;
05172                break;
05173 
05174             case AST_CONTROL_BUSY:
05175                ast_cdr_busy(chan->cdr);
05176                *outstate = f->subclass.integer;
05177                timeout = 0;
05178                break;
05179 
05180             case AST_CONTROL_CONGESTION:
05181                ast_cdr_failed(chan->cdr);
05182                *outstate = f->subclass.integer;
05183                timeout = 0;
05184                break;
05185 
05186             case AST_CONTROL_ANSWER:
05187                ast_cdr_answer(chan->cdr);
05188                *outstate = f->subclass.integer;
05189                timeout = 0;      /* trick to force exit from the while() */
05190                break;
05191 
05192             /* Ignore these */
05193             case AST_CONTROL_PROGRESS:
05194             case AST_CONTROL_PROCEEDING:
05195             case AST_CONTROL_HOLD:
05196             case AST_CONTROL_UNHOLD:
05197             case AST_CONTROL_VIDUPDATE:
05198             case AST_CONTROL_SRCUPDATE:
05199             case AST_CONTROL_SRCCHANGE:
05200             case AST_CONTROL_CONNECTED_LINE:
05201             case AST_CONTROL_REDIRECTING:
05202             case AST_CONTROL_CC:
05203             case -1:       /* Ignore -- just stopping indications */
05204                break;
05205 
05206             default:
05207                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass.integer);
05208             }
05209             last_subclass = f->subclass.integer;
05210          }
05211          ast_frfree(f);
05212       }
05213    }
05214 
05215    /* Final fixups */
05216    if (oh) {
05217       if (!ast_strlen_zero(oh->context))
05218          ast_copy_string(chan->context, oh->context, sizeof(chan->context));
05219       if (!ast_strlen_zero(oh->exten))
05220          ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
05221       if (oh->priority) 
05222          chan->priority = oh->priority;
05223    }
05224    if (chan->_state == AST_STATE_UP)
05225       *outstate = AST_CONTROL_ANSWER;
05226 
05227    if (res <= 0) {
05228       if ( AST_CONTROL_RINGING == last_subclass ) 
05229          chan->hangupcause = AST_CAUSE_NO_ANSWER;
05230       if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
05231          ast_cdr_init(chan->cdr, chan);
05232       if (chan->cdr) {
05233          char tmp[256];
05234          snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
05235          ast_cdr_setapp(chan->cdr,"Dial",tmp);
05236          ast_cdr_update(chan);
05237          ast_cdr_start(chan->cdr);
05238          ast_cdr_end(chan->cdr);
05239          /* If the cause wasn't handled properly */
05240          if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
05241             ast_cdr_failed(chan->cdr);
05242       }
05243       ast_hangup(chan);
05244       chan = NULL;
05245    }
05246    return chan;
05247 }
05248 
05249 struct ast_channel *ast_request_and_dial(const char *type, format_t format, const struct ast_channel *requestor, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
05250 {
05251    return __ast_request_and_dial(type, format, requestor, data, timeout, outstate, cidnum, cidname, NULL);
05252 }
05253 
05254 static int set_security_requirements(const struct ast_channel *requestor, struct ast_channel *out)
05255 {
05256    int ops[2][2] = {
05257       {AST_OPTION_SECURE_SIGNALING, 0},
05258       {AST_OPTION_SECURE_MEDIA, 0},
05259    };
05260    int i;
05261    struct ast_channel *r = (struct ast_channel *) requestor; /* UGLY */
05262    struct ast_datastore *ds;
05263 
05264    if (!requestor || !out) {
05265       return 0;
05266    }
05267 
05268    ast_channel_lock(r);
05269    if ((ds = ast_channel_datastore_find(r, &secure_call_info, NULL))) {
05270       struct ast_secure_call_store *encrypt = ds->data;
05271       ops[0][1] = encrypt->signaling;
05272       ops[1][1] = encrypt->media;
05273    } else {
05274       ast_channel_unlock(r);
05275       return 0;
05276    }
05277    ast_channel_unlock(r);
05278 
05279    for (i = 0; i < 2; i++) {
05280       if (ops[i][1]) {
05281          if (ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0)) {
05282             /* We require a security feature, but the channel won't provide it */
05283             return -1;
05284          }
05285       } else {
05286          /* We don't care if we can't clear the option on a channel that doesn't support it */
05287          ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0);
05288       }
05289    }
05290 
05291    return 0;
05292 }
05293 
05294 struct ast_channel *ast_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
05295 {
05296    struct chanlist *chan;
05297    struct ast_channel *c;
05298    format_t capabilities;
05299    format_t fmt;
05300    int res;
05301    int foo;
05302    format_t videoformat = format & AST_FORMAT_VIDEO_MASK;
05303    format_t textformat = format & AST_FORMAT_TEXT_MASK;
05304 
05305    if (!cause)
05306       cause = &foo;
05307    *cause = AST_CAUSE_NOTDEFINED;
05308 
05309    if (AST_RWLIST_RDLOCK(&backends)) {
05310       ast_log(LOG_WARNING, "Unable to lock technology backend list\n");
05311       return NULL;
05312    }
05313 
05314    AST_RWLIST_TRAVERSE(&backends, chan, list) {
05315       if (strcasecmp(type, chan->tech->type))
05316          continue;
05317 
05318       capabilities = chan->tech->capabilities;
05319       fmt = format & AST_FORMAT_AUDIO_MASK;
05320       if (fmt) {
05321          /* We have audio - is it possible to connect the various calls to each other? 
05322             (Avoid this check for calls without audio, like text+video calls)
05323          */
05324          res = ast_translator_best_choice(&fmt, &capabilities);
05325          if (res < 0) {
05326             char tmp1[256], tmp2[256];
05327             ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %s) to %s\n", type,
05328                ast_getformatname_multiple(tmp1, sizeof(tmp1), chan->tech->capabilities),
05329                ast_getformatname_multiple(tmp2, sizeof(tmp2), format));
05330             *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05331             AST_RWLIST_UNLOCK(&backends);
05332             return NULL;
05333          }
05334       }
05335       AST_RWLIST_UNLOCK(&backends);
05336       if (!chan->tech->requester)
05337          return NULL;
05338 
05339       if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, requestor, data, cause)))
05340          return NULL;
05341 
05342       if (set_security_requirements(requestor, c)) {
05343          ast_log(LOG_WARNING, "Setting security requirements failed\n");
05344          c = ast_channel_release(c);
05345          *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05346          return NULL;
05347       }
05348 
05349       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
05350       return c;
05351    }
05352 
05353    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
05354    *cause = AST_CAUSE_NOSUCHDRIVER;
05355    AST_RWLIST_UNLOCK(&backends);
05356 
05357    return NULL;
05358 }
05359 
05360 int ast_call(struct ast_channel *chan, char *addr, int timeout)
05361 {
05362    /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
05363       If the remote end does not answer within the timeout, then do NOT hang up, but
05364       return anyway.  */
05365    int res = -1;
05366    /* Stop if we're a zombie or need a soft hangup */
05367    ast_channel_lock(chan);
05368    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
05369       if (chan->cdr) {
05370          ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
05371       }
05372       if (chan->tech->call)
05373          res = chan->tech->call(chan, addr, timeout);
05374       ast_set_flag(chan, AST_FLAG_OUTGOING);
05375    }
05376    ast_channel_unlock(chan);
05377    return res;
05378 }
05379 
05380 /*!
05381   \brief Transfer a call to dest, if the channel supports transfer
05382 
05383   Called by:
05384    \arg app_transfer
05385    \arg the manager interface
05386 */
05387 int ast_transfer(struct ast_channel *chan, char *dest)
05388 {
05389    int res = -1;
05390 
05391    /* Stop if we're a zombie or need a soft hangup */
05392    ast_channel_lock(chan);
05393    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
05394       if (chan->tech->transfer) {
05395          res = chan->tech->transfer(chan, dest);
05396          if (!res)
05397             res = 1;
05398       } else
05399          res = 0;
05400    }
05401    ast_channel_unlock(chan);
05402 
05403    if (res <= 0) {
05404       return res;
05405    }
05406 
05407    for (;;) {
05408       struct ast_frame *fr;
05409 
05410       res = ast_waitfor(chan, -1);
05411 
05412       if (res < 0 || !(fr = ast_read(chan))) {
05413          res = -1;
05414          break;
05415       }
05416 
05417       if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_TRANSFER) {
05418          enum ast_control_transfer *message = fr->data.ptr;
05419 
05420          if (*message == AST_TRANSFER_SUCCESS) {
05421             res = 1;
05422          } else {
05423             res = -1;
05424          }
05425 
05426          ast_frfree(fr);
05427          break;
05428       }
05429 
05430       ast_frfree(fr);
05431    }
05432 
05433    return res;
05434 }
05435 
05436 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
05437 {
05438    return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
05439 }
05440 
05441 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
05442 {
05443    int pos = 0;   /* index in the buffer where we accumulate digits */
05444    int to = ftimeout;
05445 
05446    struct ast_silence_generator *silgen = NULL;
05447 
05448    /* Stop if we're a zombie or need a soft hangup */
05449    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
05450       return -1;
05451    if (!len)
05452       return -1;
05453    for (;;) {
05454       int d;
05455       if (c->stream) {
05456          d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
05457          ast_stopstream(c);
05458          if (!silgen && ast_opt_transmit_silence)
05459             silgen = ast_channel_start_silence_generator(c);
05460          usleep(1000);
05461          if (!d)
05462             d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
05463       } else {
05464          if (!silgen && ast_opt_transmit_silence)
05465             silgen = ast_channel_start_silence_generator(c);
05466          d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
05467       }
05468       if (d < 0) {
05469          ast_channel_stop_silence_generator(c, silgen);
05470          return AST_GETDATA_FAILED;
05471       }
05472       if (d == 0) {
05473          s[pos] = '\0';
05474          ast_channel_stop_silence_generator(c, silgen);
05475          return AST_GETDATA_TIMEOUT;
05476       }
05477       if (d == 1) {
05478          s[pos] = '\0';
05479          ast_channel_stop_silence_generator(c, silgen);
05480          return AST_GETDATA_INTERRUPTED;
05481       }
05482       if (strchr(enders, d) && (pos == 0)) {
05483          s[pos] = '\0';
05484          ast_channel_stop_silence_generator(c, silgen);
05485          return AST_GETDATA_EMPTY_END_TERMINATED;
05486       }
05487       if (!strchr(enders, d)) {
05488          s[pos++] = d;
05489       }
05490       if (strchr(enders, d) || (pos >= len)) {
05491          s[pos] = '\0';
05492          ast_channel_stop_silence_generator(c, silgen);
05493          return AST_GETDATA_COMPLETE;
05494       }
05495       to = timeout;
05496    }
05497    /* Never reached */
05498    return 0;
05499 }
05500 
05501 int ast_channel_supports_html(struct ast_channel *chan)
05502 {
05503    return (chan->tech->send_html) ? 1 : 0;
05504 }
05505 
05506 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
05507 {
05508    if (chan->tech->send_html)
05509       return chan->tech->send_html(chan, subclass, data, datalen);
05510    return -1;
05511 }
05512 
05513 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
05514 {
05515    return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
05516 }
05517 
05518 /*! \brief Set up translation from one channel to another */
05519 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
05520 {
05521    format_t src, dst;
05522    int use_slin;
05523 
05524    /* See if the channel driver can natively make these two channels compatible */
05525    if (from->tech->bridge && from->tech->bridge == to->tech->bridge &&
05526        !ast_channel_setoption(from, AST_OPTION_MAKE_COMPATIBLE, to, sizeof(struct ast_channel *), 0)) {
05527       return 0;
05528    }
05529 
05530    if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
05531       /* Already compatible!  Moving on ... */
05532       return 0;
05533    }
05534 
05535    /* Set up translation from the 'from' channel to the 'to' channel */
05536    src = from->nativeformats;
05537    dst = to->nativeformats;
05538 
05539    /* If there's no audio in this call, don't bother with trying to find a translation path */
05540    if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
05541       return 0;
05542 
05543    if (ast_translator_best_choice(&dst, &src) < 0) {
05544       ast_log(LOG_WARNING, "No path to translate from %s to %s\n", from->name, to->name);
05545       return -1;
05546    }
05547 
05548    /* if the best path is not 'pass through', then
05549     * transcoding is needed; if desired, force transcode path
05550     * to use SLINEAR between channels, but only if there is
05551     * no direct conversion available. If generic PLC is
05552     * desired, then transcoding via SLINEAR is a requirement
05553     */
05554    use_slin = (src == AST_FORMAT_SLINEAR || dst == AST_FORMAT_SLINEAR);
05555    if ((src != dst) && (ast_opt_generic_plc || ast_opt_transcode_via_slin) &&
05556        (ast_translate_path_steps(dst, src) != 1 || use_slin))
05557       dst = AST_FORMAT_SLINEAR;
05558    if (ast_set_read_format(from, dst) < 0) {
05559       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %s\n", from->name, ast_getformatname(dst));
05560       return -1;
05561    }
05562    if (ast_set_write_format(to, dst) < 0) {
05563       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %s\n", to->name, ast_getformatname(dst));
05564       return -1;
05565    }
05566    return 0;
05567 }
05568 
05569 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
05570 {
05571    /* Some callers do not check return code, and we must try to set all call legs correctly */
05572    int rc = 0;
05573 
05574    /* Set up translation from the chan to the peer */
05575    rc = ast_channel_make_compatible_helper(chan, peer);
05576 
05577    if (rc < 0)
05578       return rc;
05579 
05580    /* Set up translation from the peer to the chan */
05581    rc = ast_channel_make_compatible_helper(peer, chan);
05582 
05583    return rc;
05584 }
05585 
05586 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clonechan)
05587 {
05588    int res = -1;
05589    struct ast_channel *final_orig, *final_clone, *base;
05590 
05591 retrymasq:
05592    final_orig = original;
05593    final_clone = clonechan;
05594 
05595    ast_channel_lock(original);
05596    while (ast_channel_trylock(clonechan)) {
05597       ast_channel_unlock(original);
05598       usleep(1);
05599       ast_channel_lock(original);
05600    }
05601 
05602    /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
05603       and if so, we don't really want to masquerade it, but its proxy */
05604    if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
05605       final_orig = original->_bridge;
05606 
05607    if (clonechan->_bridge && (clonechan->_bridge != ast_bridged_channel(clonechan)) && (clonechan->_bridge->_bridge != clonechan))
05608       final_clone = clonechan->_bridge;
05609    
05610    if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
05611       final_clone = base;
05612    }
05613 
05614    if ((final_orig != original) || (final_clone != clonechan)) {
05615       /* Lots and lots of deadlock avoidance.  The main one we're competing with
05616        * is ast_write(), which locks channels recursively, when working with a
05617        * proxy channel. */
05618       if (ast_channel_trylock(final_orig)) {
05619          ast_channel_unlock(clonechan);
05620          ast_channel_unlock(original);
05621          goto retrymasq;
05622       }
05623       if (ast_channel_trylock(final_clone)) {
05624          ast_channel_unlock(final_orig);
05625          ast_channel_unlock(clonechan);
05626          ast_channel_unlock(original);
05627          goto retrymasq;
05628       }
05629       ast_channel_unlock(clonechan);
05630       ast_channel_unlock(original);
05631       original = final_orig;
05632       clonechan = final_clone;
05633    }
05634 
05635    if (original == clonechan) {
05636       ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
05637       ast_channel_unlock(clonechan);
05638       ast_channel_unlock(original);
05639       return -1;
05640    }
05641 
05642    ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
05643       clonechan->name, original->name);
05644 
05645    if (!original->masqr && !original->masq && !clonechan->masq && !clonechan->masqr) {
05646       original->masq = clonechan;
05647       clonechan->masqr = original;
05648       ast_queue_frame(original, &ast_null_frame);
05649       ast_queue_frame(clonechan, &ast_null_frame);
05650       ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan->name, original->name);
05651       res = 0;
05652    } else if (original->masq) {
05653       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05654          original->masq->name, original->name);
05655    } else if (original->masqr) {
05656       /* not yet as a previously planned masq hasn't yet happened */
05657       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05658          original->name, original->masqr->name);
05659    } else if (clonechan->masq) {
05660       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05661          clonechan->masq->name, clonechan->name);
05662    } else { /* (clonechan->masqr) */
05663       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05664       clonechan->name, clonechan->masqr->name);
05665    }
05666 
05667    ast_channel_unlock(clonechan);
05668    ast_channel_unlock(original);
05669 
05670    return res;
05671 }
05672 
05673 /*! \brief this function simply changes the name of the channel and issues a manager_event
05674  *         with out unlinking and linking the channel from the ao2_container.  This should
05675  *         only be used when the channel has already been unlinked from the ao2_container.
05676  */
05677 static void __ast_change_name_nolink(struct ast_channel *chan, const char *newname)
05678 {
05679    ast_manager_event(chan, EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
05680    ast_string_field_set(chan, name, newname);
05681 }
05682 
05683 void ast_change_name(struct ast_channel *chan, const char *newname)
05684 {
05685    /* We must re-link, as the hash value will change here. */
05686    ao2_unlink(channels, chan);
05687    ast_channel_lock(chan);
05688    __ast_change_name_nolink(chan, newname);
05689    ast_channel_unlock(chan);
05690    ao2_link(channels, chan);
05691 }
05692 
05693 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
05694 {
05695    struct ast_var_t *current, *newvar;
05696    const char *varname;
05697 
05698    AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
05699       int vartype = 0;
05700 
05701       varname = ast_var_full_name(current);
05702       if (!varname)
05703          continue;
05704 
05705       if (varname[0] == '_') {
05706          vartype = 1;
05707          if (varname[1] == '_')
05708             vartype = 2;
05709       }
05710 
05711       switch (vartype) {
05712       case 1:
05713          newvar = ast_var_assign(&varname[1], ast_var_value(current));
05714          if (newvar) {
05715             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
05716             ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
05717          }
05718          break;
05719       case 2:
05720          newvar = ast_var_assign(varname, ast_var_value(current));
05721          if (newvar) {
05722             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
05723             ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
05724          }
05725          break;
05726       default:
05727          ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
05728          break;
05729       }
05730    }
05731 }
05732 
05733 /*!
05734   \brief Clone channel variables from 'clone' channel into 'original' channel
05735 
05736   All variables except those related to app_groupcount are cloned.
05737   Variables are actually _removed_ from 'clone' channel, presumably
05738   because it will subsequently be destroyed.
05739 
05740   \note Assumes locks will be in place on both channels when called.
05741 */
05742 static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
05743 {
05744    struct ast_var_t *current, *newvar;
05745    /* Append variables from clone channel into original channel */
05746    /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
05747    if (AST_LIST_FIRST(&clonechan->varshead))
05748       AST_LIST_APPEND_LIST(&original->varshead, &clonechan->varshead, entries);
05749 
05750    /* then, dup the varshead list into the clone */
05751    
05752    AST_LIST_TRAVERSE(&original->varshead, current, entries) {
05753       newvar = ast_var_assign(current->name, current->value);
05754       if (newvar)
05755          AST_LIST_INSERT_TAIL(&clonechan->varshead, newvar, entries);
05756    }
05757 }
05758 
05759 
05760 
05761 /* return the oldest of two linkedids.  linkedid is derived from
05762    uniqueid which is formed like this: [systemname-]ctime.seq
05763 
05764    The systemname, and the dash are optional, followed by the epoch
05765    time followed by an integer sequence.  Note that this is not a
05766    decimal number, since 1.2 is less than 1.11 in uniqueid land.
05767 
05768    To compare two uniqueids, we parse out the integer values of the
05769    time and the sequence numbers and compare them, with time trumping
05770    sequence.
05771 */
05772 static const char *oldest_linkedid(const char *a, const char *b)
05773 {
05774    const char *satime, *saseq;
05775    const char *sbtime, *sbseq;
05776    const char *dash;
05777 
05778    unsigned int atime, aseq, btime, bseq;
05779 
05780    if (ast_strlen_zero(a))
05781       return b;
05782 
05783    if (ast_strlen_zero(b))
05784       return a;
05785 
05786    satime = a;
05787    sbtime = b;
05788 
05789    /* jump over the system name */
05790    if ((dash = strrchr(satime, '-'))) {
05791       satime = dash+1;
05792    }
05793    if ((dash = strrchr(sbtime, '-'))) {
05794       sbtime = dash+1;
05795    }
05796 
05797    /* the sequence comes after the '.' */
05798    saseq = strchr(satime, '.');
05799    sbseq = strchr(sbtime, '.');
05800    if (!saseq || !sbseq)
05801       return NULL;
05802    saseq++;
05803    sbseq++;
05804 
05805    /* convert it all to integers */
05806    atime = atoi(satime); /* note that atoi is ignoring the '.' after the time string */
05807    btime = atoi(sbtime); /* note that atoi is ignoring the '.' after the time string */
05808    aseq = atoi(saseq);
05809    bseq = atoi(sbseq);
05810 
05811    /* and finally compare */
05812    if (atime == btime) {
05813       return (aseq < bseq) ? a : b;
05814    }
05815    else {
05816       return (atime < btime) ? a : b;
05817    }
05818 }
05819 
05820 /*! Set the channel's linkedid to the given string, and also check to
05821  *  see if the channel's old linkedid is now being retired */
05822 static void ast_channel_change_linkedid(struct ast_channel *chan, const char *linkedid)
05823 {
05824    /* if the linkedid for this channel is being changed from something, check... */
05825    if (!ast_strlen_zero(chan->linkedid) && 0 != strcmp(chan->linkedid, linkedid)) {
05826       ast_cel_check_retire_linkedid(chan);
05827    }
05828 
05829    ast_string_field_set(chan, linkedid, linkedid);
05830 }
05831 
05832 
05833 /*!
05834   \brief Propagate the oldest linkedid between associated channels
05835 
05836 */
05837 void ast_channel_set_linkgroup(struct ast_channel *chan, struct ast_channel *peer)
05838 {
05839    const char* linkedid=NULL;
05840    struct ast_channel *bridged;
05841 
05842    linkedid = oldest_linkedid(chan->linkedid, peer->linkedid);
05843    linkedid = oldest_linkedid(linkedid, chan->uniqueid);
05844    linkedid = oldest_linkedid(linkedid, peer->uniqueid);
05845    if (chan->_bridge) {
05846       bridged = ast_bridged_channel(chan);
05847       if (bridged != peer) {
05848          linkedid = oldest_linkedid(linkedid, bridged->linkedid);
05849          linkedid = oldest_linkedid(linkedid, bridged->uniqueid);
05850       }
05851    }
05852    if (peer->_bridge) {
05853       bridged = ast_bridged_channel(peer);
05854       if (bridged != chan) {
05855          linkedid = oldest_linkedid(linkedid, bridged->linkedid);
05856          linkedid = oldest_linkedid(linkedid, bridged->uniqueid);
05857       }
05858    }
05859 
05860    /* just in case setting a stringfield to itself causes problems */
05861    linkedid = ast_strdupa(linkedid);
05862 
05863    ast_channel_change_linkedid(chan, linkedid);
05864    ast_channel_change_linkedid(peer, linkedid);
05865    if (chan->_bridge) {
05866       bridged = ast_bridged_channel(chan);
05867       if (bridged != peer) {
05868          ast_channel_change_linkedid(bridged, linkedid);
05869       }
05870    }
05871    if (peer->_bridge) {
05872       bridged = ast_bridged_channel(peer);
05873       if (bridged != chan) {
05874          ast_channel_change_linkedid(bridged, linkedid);
05875       }
05876    }
05877 }
05878 
05879 /* copy accountcode and peeraccount across during a link */
05880 static void ast_set_owners_and_peers(struct ast_channel *chan1,
05881                             struct ast_channel *chan2)
05882 {
05883    if (!ast_strlen_zero(chan1->accountcode) && ast_strlen_zero(chan2->peeraccount)) {
05884       ast_log(LOG_DEBUG, "setting peeraccount to %s for %s from data on channel %s\n",
05885             chan1->accountcode, chan2->name, chan1->name);
05886       ast_string_field_set(chan2, peeraccount, chan1->accountcode);
05887    }
05888    if (!ast_strlen_zero(chan2->accountcode) && ast_strlen_zero(chan1->peeraccount)) {
05889       ast_log(LOG_DEBUG, "setting peeraccount to %s for %s from data on channel %s\n",
05890             chan2->accountcode, chan1->name, chan2->name);
05891       ast_string_field_set(chan1, peeraccount, chan2->accountcode);
05892    }
05893    if (!ast_strlen_zero(chan1->peeraccount) && ast_strlen_zero(chan2->accountcode)) {
05894       ast_log(LOG_DEBUG, "setting accountcode to %s for %s from data on channel %s\n",
05895             chan1->peeraccount, chan2->name, chan1->name);
05896       ast_string_field_set(chan2, accountcode, chan1->peeraccount);
05897    }
05898    if (!ast_strlen_zero(chan2->peeraccount) && ast_strlen_zero(chan1->accountcode)) {
05899       ast_log(LOG_DEBUG, "setting accountcode to %s for %s from data on channel %s\n",
05900             chan2->peeraccount, chan1->name, chan2->name);
05901       ast_string_field_set(chan1, accountcode, chan2->peeraccount);
05902    }
05903    if (0 != strcmp(chan1->accountcode, chan2->peeraccount)) {
05904       ast_log(LOG_DEBUG, "changing peeraccount from %s to %s on %s to match channel %s\n",
05905             chan2->peeraccount, chan1->peeraccount, chan2->name, chan1->name);
05906       ast_string_field_set(chan2, peeraccount, chan1->accountcode);
05907    }
05908    if (0 != strcmp(chan2->accountcode, chan1->peeraccount)) {
05909       ast_log(LOG_DEBUG, "changing peeraccount from %s to %s on %s to match channel %s\n",
05910             chan1->peeraccount, chan2->peeraccount, chan1->name, chan2->name);
05911       ast_string_field_set(chan1, peeraccount, chan2->accountcode);
05912    }
05913 }
05914 
05915 /*!
05916  * \pre chan is locked
05917  */
05918 static void report_new_callerid(struct ast_channel *chan)
05919 {
05920    int pres;
05921 
05922    pres = ast_party_id_presentation(&chan->caller.id);
05923    ast_manager_event(chan, EVENT_FLAG_CALL, "NewCallerid",
05924       "Channel: %s\r\n"
05925       "CallerIDNum: %s\r\n"
05926       "CallerIDName: %s\r\n"
05927       "Uniqueid: %s\r\n"
05928       "CID-CallingPres: %d (%s)\r\n",
05929       chan->name,
05930       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
05931       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, ""),
05932       chan->uniqueid,
05933       pres,
05934       ast_describe_caller_presentation(pres)
05935       );
05936 }
05937 
05938 /*!
05939   \brief Masquerade a channel
05940 
05941   \note Assumes _NO_ channels and _NO_ channel pvt's are locked.  If a channel is locked while calling
05942         this function, it invalidates our channel container locking order.  All channels
05943       must be unlocked before it is permissible to lock the channels' ao2 container.
05944 */
05945 int ast_do_masquerade(struct ast_channel *original)
05946 {
05947    format_t x;
05948    int i;
05949    int res=0;
05950    int origstate;
05951    struct ast_frame *current;
05952    const struct ast_channel_tech *t;
05953    void *t_pvt;
05954    union {
05955       struct ast_party_dialed dialed;
05956       struct ast_party_caller caller;
05957       struct ast_party_connected_line connected;
05958       struct ast_party_redirecting redirecting;
05959    } exchange;
05960    struct ast_channel *clonechan, *chans[2];
05961    struct ast_channel *bridged;
05962    struct ast_cdr *cdr;
05963    format_t rformat = original->readformat;
05964    format_t wformat = original->writeformat;
05965    char newn[AST_CHANNEL_NAME];
05966    char orig[AST_CHANNEL_NAME];
05967    char masqn[AST_CHANNEL_NAME];
05968    char zombn[AST_CHANNEL_NAME];
05969 
05970    /* XXX This operation is a bit odd.  We're essentially putting the guts of
05971     * the clone channel into the original channel.  Start by killing off the
05972     * original channel's backend.  While the features are nice, which is the
05973     * reason we're keeping it, it's still awesomely weird. XXX */
05974 
05975    /* The reasoning for the channels ao2_container lock here is complex.
05976     * 
05977     * In order to check for a race condition, the original channel must
05978     * be locked.  If it is determined that the masquerade should proceed
05979     * the original channel can absolutely not be unlocked until the end
05980     * of the function.  Since after determining the masquerade should
05981     * continue requires the channels to be unlinked from the ao2_container,
05982     * the container lock must be held first to achieve proper locking order.
05983     */
05984    ao2_lock(channels);
05985 
05986    /* lock the original channel to determine if the masquerade is require or not */
05987    ast_channel_lock(original);
05988 
05989    /* This checks to see if the masquerade has already happened or not.  There is a
05990     * race condition that exists for this function. Since all pvt and channel locks
05991     * must be let go before calling do_masquerade, it is possible that it could be
05992     * called multiple times for the same channel.  This check verifies whether
05993     * or not the masquerade has already been completed by another thread */
05994    if (!original->masq) {
05995       ast_channel_unlock(original);
05996       ao2_unlock(channels);
05997       return 0; /* masq already completed by another thread, or never needed to be done to begin with */
05998    }
05999 
06000    /* now that we have verified no race condition exists, set the clone channel */
06001    clonechan = original->masq;
06002 
06003    /* since this function already holds the global container lock, unlocking original
06004     * for deadlock avoidance will not result in any sort of masquerade race condition.
06005     * If masq is called by a different thread while this happens, it will be stuck waiting
06006     * until we unlock the container. */
06007    while (ast_channel_trylock(clonechan)) {
06008       CHANNEL_DEADLOCK_AVOIDANCE(original);
06009    }
06010 
06011    /* clear the masquerade channels */
06012    original->masq = NULL;
06013    clonechan->masqr = NULL;
06014 
06015    /* unlink from channels container as name (which is the hash value) will change */
06016    ao2_unlink(channels, original);
06017    ao2_unlink(channels, clonechan);
06018 
06019    ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
06020       clonechan->name, clonechan->_state, original->name, original->_state);
06021 
06022    chans[0] = clonechan;
06023    chans[1] = original;
06024    ast_manager_event_multichan(EVENT_FLAG_CALL, "Masquerade", 2, chans, "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
06025             clonechan->name, ast_state2str(clonechan->_state), original->name, ast_state2str(original->_state));
06026 
06027    /* Having remembered the original read/write formats, we turn off any translation on either
06028       one */
06029    free_translation(clonechan);
06030    free_translation(original);
06031 
06032    /* Save the original name */
06033    ast_copy_string(orig, original->name, sizeof(orig));
06034    /* Save the new name */
06035    ast_copy_string(newn, clonechan->name, sizeof(newn));
06036    /* Create the masq name */
06037    snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
06038 
06039    /* Mangle the name of the clone channel */
06040    __ast_change_name_nolink(clonechan, masqn);
06041 
06042    /* Copy the name from the clone channel */
06043    __ast_change_name_nolink(original, newn);
06044 
06045    /* share linked id's */
06046    ast_channel_set_linkgroup(original, clonechan);
06047 
06048    /* Swap the technologies */
06049    t = original->tech;
06050    original->tech = clonechan->tech;
06051    clonechan->tech = t;
06052 
06053    /* Swap the cdrs */
06054    cdr = original->cdr;
06055    original->cdr = clonechan->cdr;
06056    clonechan->cdr = cdr;
06057 
06058    t_pvt = original->tech_pvt;
06059    original->tech_pvt = clonechan->tech_pvt;
06060    clonechan->tech_pvt = t_pvt;
06061 
06062    /* Swap the alertpipes */
06063    for (i = 0; i < 2; i++) {
06064       x = original->alertpipe[i];
06065       original->alertpipe[i] = clonechan->alertpipe[i];
06066       clonechan->alertpipe[i] = x;
06067    }
06068 
06069    /* 
06070     * Swap the readq's.  The end result should be this:
06071     *
06072     *  1) All frames should be on the new (original) channel.
06073     *  2) Any frames that were already on the new channel before this
06074     *     masquerade need to be at the end of the readq, after all of the
06075     *     frames on the old (clone) channel.
06076     *  3) The alertpipe needs to get poked for every frame that was already
06077     *     on the new channel, since we are now using the alert pipe from the
06078     *     old (clone) channel.
06079     */
06080    {
06081       AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
06082       AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
06083 
06084       AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
06085       AST_LIST_APPEND_LIST(&original->readq, &clonechan->readq, frame_list);
06086 
06087       while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
06088          AST_LIST_INSERT_TAIL(&original->readq, current, frame_list);
06089          if (original->alertpipe[1] > -1) {
06090             int poke = 0;
06091 
06092             if (write(original->alertpipe[1], &poke, sizeof(poke)) < 0) {
06093                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
06094             }
06095          }
06096       }
06097    }
06098 
06099    /* Swap the raw formats */
06100    x = original->rawreadformat;
06101    original->rawreadformat = clonechan->rawreadformat;
06102    clonechan->rawreadformat = x;
06103    x = original->rawwriteformat;
06104    original->rawwriteformat = clonechan->rawwriteformat;
06105    clonechan->rawwriteformat = x;
06106 
06107    clonechan->_softhangup = AST_SOFTHANGUP_DEV;
06108 
06109    /* And of course, so does our current state.  Note we need not
06110       call ast_setstate since the event manager doesn't really consider
06111       these separate.  We do this early so that the clone has the proper
06112       state of the original channel. */
06113    origstate = original->_state;
06114    original->_state = clonechan->_state;
06115    clonechan->_state = origstate;
06116 
06117    if (clonechan->tech->fixup && clonechan->tech->fixup(original, clonechan)) {
06118       ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clonechan->name);
06119    }
06120 
06121    /* Start by disconnecting the original's physical side */
06122    if (clonechan->tech->hangup && clonechan->tech->hangup(clonechan)) {
06123       ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
06124       res = -1;
06125       goto done;
06126    }
06127 
06128    /* Mangle the name of the clone channel */
06129    snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig); /* quick, hide the brains! */
06130    __ast_change_name_nolink(clonechan, zombn);
06131 
06132    /* Update the type. */
06133    t_pvt = original->monitor;
06134    original->monitor = clonechan->monitor;
06135    clonechan->monitor = t_pvt;
06136 
06137    /* Keep the same language.  */
06138    ast_string_field_set(original, language, clonechan->language);
06139    /* Copy the FD's other than the generator fd */
06140    for (x = 0; x < AST_MAX_FDS; x++) {
06141       if (x != AST_GENERATOR_FD)
06142          ast_channel_set_fd(original, x, clonechan->fds[x]);
06143    }
06144 
06145    ast_app_group_update(clonechan, original);
06146 
06147    /* Move data stores over */
06148    if (AST_LIST_FIRST(&clonechan->datastores)) {
06149       struct ast_datastore *ds;
06150       /* We use a safe traversal here because some fixup routines actually
06151        * remove the datastore from the list and free them.
06152        */
06153       AST_LIST_TRAVERSE_SAFE_BEGIN(&clonechan->datastores, ds, entry) {
06154          if (ds->info->chan_fixup)
06155             ds->info->chan_fixup(ds->data, clonechan, original);
06156       }
06157       AST_LIST_TRAVERSE_SAFE_END;
06158       AST_LIST_APPEND_LIST(&original->datastores, &clonechan->datastores, entry);
06159    }
06160 
06161    ast_autochan_new_channel(clonechan, original);
06162 
06163    clone_variables(original, clonechan);
06164    /* Presense of ADSI capable CPE follows clone */
06165    original->adsicpe = clonechan->adsicpe;
06166    /* Bridge remains the same */
06167    /* CDR fields remain the same */
06168    /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
06169    /* Application and data remain the same */
06170    /* Clone exception  becomes real one, as with fdno */
06171    ast_set_flag(original, ast_test_flag(clonechan, AST_FLAG_EXCEPTION | AST_FLAG_OUTGOING));
06172    original->fdno = clonechan->fdno;
06173    /* Schedule context remains the same */
06174    /* Stream stuff stays the same */
06175    /* Keep the original state.  The fixup code will need to work with it most likely */
06176 
06177    /*
06178     * Just swap the whole structures, nevermind the allocations,
06179     * they'll work themselves out.
06180     */
06181    exchange.dialed = original->dialed;
06182    original->dialed = clonechan->dialed;
06183    clonechan->dialed = exchange.dialed;
06184 
06185    exchange.caller = original->caller;
06186    original->caller = clonechan->caller;
06187    clonechan->caller = exchange.caller;
06188 
06189    exchange.connected = original->connected;
06190    original->connected = clonechan->connected;
06191    clonechan->connected = exchange.connected;
06192 
06193    exchange.redirecting = original->redirecting;
06194    original->redirecting = clonechan->redirecting;
06195    clonechan->redirecting = exchange.redirecting;
06196 
06197    report_new_callerid(original);
06198 
06199    /* Restore original timing file descriptor */
06200    ast_channel_set_fd(original, AST_TIMING_FD, original->timingfd);
06201 
06202    /* Our native formats are different now */
06203    original->nativeformats = clonechan->nativeformats;
06204 
06205    /* Context, extension, priority, app data, jump table,  remain the same */
06206    /* pvt switches.  pbx stays the same, as does next */
06207 
06208    /* Set the write format */
06209    ast_set_write_format(original, wformat);
06210 
06211    /* Set the read format */
06212    ast_set_read_format(original, rformat);
06213 
06214    /* Copy the music class */
06215    ast_string_field_set(original, musicclass, clonechan->musicclass);
06216 
06217    /* copy over accuntcode and set peeraccount across the bridge */
06218    ast_string_field_set(original, accountcode, S_OR(clonechan->accountcode, ""));
06219    if (original->_bridge) {
06220       /* XXX - should we try to lock original->_bridge here? */
06221       ast_string_field_set(original->_bridge, peeraccount, S_OR(clonechan->accountcode, ""));
06222       ast_cel_report_event(original, AST_CEL_BRIDGE_UPDATE, NULL, NULL, NULL);
06223    }
06224 
06225    ast_debug(1, "Putting channel %s in %s/%s formats\n", original->name,
06226       ast_getformatname(wformat), ast_getformatname(rformat));
06227 
06228    /* Okay.  Last thing is to let the channel driver know about all this mess, so he
06229       can fix up everything as best as possible */
06230    if (original->tech->fixup) {
06231       if (original->tech->fixup(clonechan, original)) {
06232          ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
06233             original->tech->type, original->name);
06234          res = -1;
06235          goto done;
06236       }
06237    } else
06238       ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
06239          original->tech->type, original->name);
06240 
06241    /* 
06242     * If an indication is currently playing, maintain it on the channel 
06243     * that is taking the place of original 
06244     *
06245     * This is needed because the masquerade is swapping out in the internals
06246     * of this channel, and the new channel private data needs to be made
06247     * aware of the current visible indication (RINGING, CONGESTION, etc.)
06248     */
06249    if (original->visible_indication) {
06250       ast_indicate(original, original->visible_indication);
06251    }
06252 
06253    /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
06254       a zombie so nothing tries to touch it.  If it's already been marked as a
06255       zombie, then free it now (since it already is considered invalid). */
06256    if (ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
06257       ast_debug(1, "Destroying channel clone '%s'\n", clonechan->name);
06258       ast_channel_unlock(clonechan);
06259       ast_manager_event(clonechan, EVENT_FLAG_CALL, "Hangup",
06260          "Channel: %s\r\n"
06261          "Uniqueid: %s\r\n"
06262          "Cause: %d\r\n"
06263          "Cause-txt: %s\r\n",
06264          clonechan->name,
06265          clonechan->uniqueid,
06266          clonechan->hangupcause,
06267          ast_cause2str(clonechan->hangupcause)
06268          );
06269       clonechan = ast_channel_release(clonechan);
06270    } else {
06271       ast_debug(1, "Released clone lock on '%s'\n", clonechan->name);
06272       ast_set_flag(clonechan, AST_FLAG_ZOMBIE);
06273       ast_queue_frame(clonechan, &ast_null_frame);
06274    }
06275 
06276    /* Signal any blocker */
06277    if (ast_test_flag(original, AST_FLAG_BLOCKING))
06278       pthread_kill(original->blocker, SIGURG);
06279    ast_debug(1, "Done Masquerading %s (%d)\n", original->name, original->_state);
06280 
06281    if ((bridged = ast_bridged_channel(original))) {
06282       ast_channel_lock(bridged);
06283       ast_indicate(bridged, AST_CONTROL_SRCCHANGE);
06284       ast_channel_unlock(bridged);
06285    }
06286 
06287    ast_indicate(original, AST_CONTROL_SRCCHANGE);
06288 
06289 done:
06290    /* it is possible for the clone channel to disappear during this */
06291    if (clonechan) {
06292       ast_channel_unlock(original);
06293       ast_channel_unlock(clonechan);
06294       ao2_link(channels, clonechan);
06295       ao2_link(channels, original);
06296    } else {
06297       ast_channel_unlock(original);
06298       ao2_link(channels, original);
06299    }
06300 
06301    ao2_unlock(channels);
06302 
06303    return 0;
06304 }
06305 
06306 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
06307 {
06308    ast_channel_lock(chan);
06309 
06310    if (cid_num) {
06311       chan->caller.id.number.valid = 1;
06312       ast_free(chan->caller.id.number.str);
06313       chan->caller.id.number.str = ast_strdup(cid_num);
06314    }
06315    if (cid_name) {
06316       chan->caller.id.name.valid = 1;
06317       ast_free(chan->caller.id.name.str);
06318       chan->caller.id.name.str = ast_strdup(cid_name);
06319    }
06320    if (cid_ani) {
06321       chan->caller.ani.number.valid = 1;
06322       ast_free(chan->caller.ani.number.str);
06323       chan->caller.ani.number.str = ast_strdup(cid_ani);
06324    }
06325    if (chan->cdr) {
06326       ast_cdr_setcid(chan->cdr, chan);
06327    }
06328 
06329    report_new_callerid(chan);
06330 
06331    ast_channel_unlock(chan);
06332 }
06333 
06334 void ast_channel_set_caller(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
06335 {
06336    if (&chan->caller == caller) {
06337       /* Don't set to self */
06338       return;
06339    }
06340 
06341    ast_channel_lock(chan);
06342    ast_party_caller_set(&chan->caller, caller, update);
06343    ast_channel_unlock(chan);
06344 }
06345 
06346 void ast_channel_set_caller_event(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
06347 {
06348    struct ast_party_caller pre_set;
06349 
06350    if (&chan->caller == caller) {
06351       /* Don't set to self */
06352       return;
06353    }
06354 
06355    ast_channel_lock(chan);
06356    pre_set = chan->caller;
06357    ast_party_caller_set(&chan->caller, caller, update);
06358    if (S_COR(pre_set.id.number.valid, pre_set.id.number.str, NULL)
06359          != S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)
06360       || S_COR(pre_set.id.name.valid, pre_set.id.name.str, NULL)
06361          != S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL)) {
06362       /* The caller id name or number changed. */
06363       report_new_callerid(chan);
06364    }
06365    if (chan->cdr) {
06366       ast_cdr_setcid(chan->cdr, chan);
06367    }
06368    ast_channel_unlock(chan);
06369 }
06370 
06371 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
06372 {
06373    int oldstate = chan->_state;
06374    char name[AST_CHANNEL_NAME], *dashptr;
06375 
06376    if (oldstate == state)
06377       return 0;
06378 
06379    ast_copy_string(name, chan->name, sizeof(name));
06380    if ((dashptr = strrchr(name, '-'))) {
06381       *dashptr = '\0';
06382    }
06383 
06384    chan->_state = state;
06385 
06386    /* We have to pass AST_DEVICE_UNKNOWN here because it is entirely possible that the channel driver
06387     * for this channel is using the callback method for device state. If we pass in an actual state here
06388     * we override what they are saying the state is and things go amuck. */
06389    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
06390 
06391    /* setstate used to conditionally report Newchannel; this is no more */
06392    ast_manager_event(chan, EVENT_FLAG_CALL, "Newstate",
06393       "Channel: %s\r\n"
06394       "ChannelState: %d\r\n"
06395       "ChannelStateDesc: %s\r\n"
06396       "CallerIDNum: %s\r\n"
06397       "CallerIDName: %s\r\n"
06398       "Uniqueid: %s\r\n",
06399       chan->name, chan->_state, ast_state2str(chan->_state),
06400       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
06401       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, ""),
06402       chan->uniqueid);
06403 
06404    return 0;
06405 }
06406 
06407 /*! \brief Find bridged channel */
06408 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
06409 {
06410    struct ast_channel *bridged;
06411    bridged = chan->_bridge;
06412    if (bridged && bridged->tech->bridged_channel)
06413       bridged = bridged->tech->bridged_channel(chan, bridged);
06414    return bridged;
06415 }
06416 
06417 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
06418 {
06419    int min = 0, sec = 0, check;
06420 
06421    check = ast_autoservice_start(peer);
06422    if (check)
06423       return;
06424 
06425    if (remain > 0) {
06426       if (remain / 60 > 1) {
06427          min = remain / 60;
06428          sec = remain % 60;
06429       } else {
06430          sec = remain;
06431       }
06432    }
06433    
06434    if (!strcmp(sound,"timeleft")) { /* Queue support */
06435       ast_stream_and_wait(chan, "vm-youhave", "");
06436       if (min) {
06437          ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
06438          ast_stream_and_wait(chan, "queue-minutes", "");
06439       }
06440       if (sec) {
06441          ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
06442          ast_stream_and_wait(chan, "queue-seconds", "");
06443       }
06444    } else {
06445       ast_stream_and_wait(chan, sound, "");
06446    }
06447 
06448    ast_autoservice_stop(peer);
06449 }
06450 
06451 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
06452                    struct ast_bridge_config *config, struct ast_frame **fo,
06453                    struct ast_channel **rc)
06454 {
06455    /* Copy voice back and forth between the two channels. */
06456    struct ast_channel *cs[3];
06457    struct ast_frame *f;
06458    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
06459    format_t o0nativeformats;
06460    format_t o1nativeformats;
06461    int watch_c0_dtmf;
06462    int watch_c1_dtmf;
06463    void *pvt0, *pvt1;
06464    /* Indicates whether a frame was queued into a jitterbuffer */
06465    int frame_put_in_jb = 0;
06466    int jb_in_use;
06467    int to;
06468    
06469    cs[0] = c0;
06470    cs[1] = c1;
06471    pvt0 = c0->tech_pvt;
06472    pvt1 = c1->tech_pvt;
06473    o0nativeformats = c0->nativeformats;
06474    o1nativeformats = c1->nativeformats;
06475    watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
06476    watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
06477 
06478    /* Check the need of a jitterbuffer for each channel */
06479    jb_in_use = ast_jb_do_usecheck(c0, c1);
06480    if (jb_in_use)
06481       ast_jb_empty_and_reset(c0, c1);
06482 
06483    ast_poll_channel_add(c0, c1);
06484 
06485    if (config->feature_timer > 0 && ast_tvzero(config->nexteventts)) {
06486       /* nexteventts is not set when the bridge is not scheduled to
06487        * break, so calculate when the bridge should possibly break
06488        * if a partial feature match timed out */
06489       config->nexteventts = ast_tvadd(ast_tvnow(), ast_samp2tv(config->feature_timer, 1000));
06490    }
06491 
06492    for (;;) {
06493       struct ast_channel *who, *other;
06494 
06495       if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
06496           (o0nativeformats != c0->nativeformats) ||
06497           (o1nativeformats != c1->nativeformats)) {
06498          /* Check for Masquerade, codec changes, etc */
06499          res = AST_BRIDGE_RETRY;
06500          break;
06501       }
06502       if (config->nexteventts.tv_sec) {
06503          to = ast_tvdiff_ms(config->nexteventts, ast_tvnow());
06504          if (to <= 0) {
06505             if (config->timelimit && !config->feature_timer && !ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
06506                res = AST_BRIDGE_RETRY;
06507                /* generic bridge ending to play warning */
06508                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
06509             } else if (config->feature_timer) {
06510                /* feature timer expired - make sure we do not play warning */
06511                ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
06512                res = AST_BRIDGE_RETRY;
06513             } else {
06514                res = AST_BRIDGE_COMPLETE;
06515             }
06516             break;
06517          }
06518       } else {
06519          /* If a feature has been started and the bridge is configured to 
06520           * to not break, leave the channel bridge when the feature timer
06521           * time has elapsed so the DTMF will be sent to the other side. 
06522           */
06523          if (!ast_tvzero(config->nexteventts)) {
06524             int diff = ast_tvdiff_ms(config->nexteventts, ast_tvnow());
06525             if (diff <= 0) {
06526                res = AST_BRIDGE_RETRY;
06527                break;
06528             }
06529          }
06530          to = -1;
06531       }
06532       /* Calculate the appropriate max sleep interval - in general, this is the time,
06533          left to the closest jb delivery moment */
06534       if (jb_in_use)
06535          to = ast_jb_get_when_to_wakeup(c0, c1, to);
06536       who = ast_waitfor_n(cs, 2, &to);
06537       if (!who) {
06538          /* No frame received within the specified timeout - check if we have to deliver now */
06539          if (jb_in_use)
06540             ast_jb_get_and_deliver(c0, c1);
06541          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
06542             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
06543                c0->_softhangup = 0;
06544             if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
06545                c1->_softhangup = 0;
06546             c0->_bridge = c1;
06547             c1->_bridge = c0;
06548          }
06549          continue;
06550       }
06551       f = ast_read(who);
06552       if (!f) {
06553          *fo = NULL;
06554          *rc = who;
06555          ast_debug(1, "Didn't get a frame from channel: %s\n",who->name);
06556          break;
06557       }
06558 
06559       other = (who == c0) ? c1 : c0; /* the 'other' channel */
06560       /* Try add the frame info the who's bridged channel jitterbuff */
06561       if (jb_in_use)
06562          frame_put_in_jb = !ast_jb_put(other, f);
06563 
06564       if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
06565          int bridge_exit = 0;
06566 
06567          switch (f->subclass.integer) {
06568          case AST_CONTROL_AOC:
06569             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
06570             break;
06571          case AST_CONTROL_REDIRECTING:
06572             if (ast_channel_redirecting_macro(who, other, f, other == c0, 1)) {
06573                ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
06574             }
06575             break;
06576          case AST_CONTROL_CONNECTED_LINE:
06577             if (ast_channel_connected_line_macro(who, other, f, other == c0, 1)) {
06578                ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
06579             }
06580             break;
06581          case AST_CONTROL_HOLD:
06582          case AST_CONTROL_UNHOLD:
06583          case AST_CONTROL_VIDUPDATE:
06584          case AST_CONTROL_SRCUPDATE:
06585          case AST_CONTROL_SRCCHANGE:
06586          case AST_CONTROL_T38_PARAMETERS:
06587             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
06588             if (jb_in_use) {
06589                ast_jb_empty_and_reset(c0, c1);
06590             }
06591             break;
06592          default:
06593             *fo = f;
06594             *rc = who;
06595             bridge_exit = 1;
06596             ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass.integer, who->name);
06597             break;
06598          }
06599          if (bridge_exit)
06600             break;
06601       }
06602       if ((f->frametype == AST_FRAME_VOICE) ||
06603           (f->frametype == AST_FRAME_DTMF_BEGIN) ||
06604           (f->frametype == AST_FRAME_DTMF) ||
06605           (f->frametype == AST_FRAME_VIDEO) ||
06606           (f->frametype == AST_FRAME_IMAGE) ||
06607           (f->frametype == AST_FRAME_HTML) ||
06608           (f->frametype == AST_FRAME_MODEM) ||
06609           (f->frametype == AST_FRAME_TEXT)) {
06610          /* monitored dtmf causes exit from bridge */
06611          int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
06612 
06613          if (monitored_source &&
06614             (f->frametype == AST_FRAME_DTMF_END ||
06615             f->frametype == AST_FRAME_DTMF_BEGIN)) {
06616             *fo = f;
06617             *rc = who;
06618             ast_debug(1, "Got DTMF %s on channel (%s)\n", 
06619                f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
06620                who->name);
06621 
06622             break;
06623          }
06624          /* Write immediately frames, not passed through jb */
06625          if (!frame_put_in_jb)
06626             ast_write(other, f);
06627             
06628          /* Check if we have to deliver now */
06629          if (jb_in_use)
06630             ast_jb_get_and_deliver(c0, c1);
06631       }
06632       /* XXX do we want to pass on also frames not matched above ? */
06633       ast_frfree(f);
06634 
06635 #ifndef HAVE_EPOLL
06636       /* Swap who gets priority */
06637       cs[2] = cs[0];
06638       cs[0] = cs[1];
06639       cs[1] = cs[2];
06640 #endif
06641    }
06642 
06643    ast_poll_channel_del(c0, c1);
06644 
06645    return res;
06646 }
06647 
06648 /*! \brief Bridge two channels together (early) */
06649 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
06650 {
06651    /* Make sure we can early bridge, if not error out */
06652    if (!c0->tech->early_bridge || (c1 && (!c1->tech->early_bridge || c0->tech->early_bridge != c1->tech->early_bridge)))
06653       return -1;
06654 
06655    return c0->tech->early_bridge(c0, c1);
06656 }
06657 
06658 /*! \brief Send manager event for bridge link and unlink events.
06659  * \param onoff Link/Unlinked 
06660  * \param type 1 for core, 2 for native
06661  * \param c0 first channel in bridge
06662  * \param c1 second channel in bridge
06663 */
06664 static void manager_bridge_event(int onoff, int type, struct ast_channel *c0, struct ast_channel *c1)
06665 {
06666    struct ast_channel *chans[2] = { c0, c1 };
06667    ast_manager_event_multichan(EVENT_FLAG_CALL, "Bridge", 2, chans,
06668       "Bridgestate: %s\r\n"
06669       "Bridgetype: %s\r\n"
06670       "Channel1: %s\r\n"
06671       "Channel2: %s\r\n"
06672       "Uniqueid1: %s\r\n"
06673       "Uniqueid2: %s\r\n"
06674       "CallerID1: %s\r\n"
06675       "CallerID2: %s\r\n",
06676       onoff ? "Link" : "Unlink",
06677       type == 1 ? "core" : "native",
06678       c0->name, c1->name,
06679       c0->uniqueid, c1->uniqueid,
06680       S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, ""),
06681       S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, ""));
06682 }
06683 
06684 static void update_bridge_vars(struct ast_channel *c0, struct ast_channel *c1)
06685 {
06686    const char *c0_name;
06687    const char *c1_name;
06688    const char *c0_pvtid = NULL;
06689    const char *c1_pvtid = NULL;
06690 
06691    ast_channel_lock(c1);
06692    c1_name = ast_strdupa(c1->name);
06693    if (c1->tech->get_pvt_uniqueid) {
06694       c1_pvtid = ast_strdupa(c1->tech->get_pvt_uniqueid(c1));
06695    }
06696    ast_channel_unlock(c1);
06697 
06698    ast_channel_lock(c0);
06699    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER"))) {
06700       pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1_name);
06701    }
06702    if (c1_pvtid) {
06703       pbx_builtin_setvar_helper(c0, "BRIDGEPVTCALLID", c1_pvtid);
06704    }
06705    c0_name = ast_strdupa(c0->name);
06706    if (c0->tech->get_pvt_uniqueid) {
06707       c0_pvtid = ast_strdupa(c0->tech->get_pvt_uniqueid(c0));
06708    }
06709    ast_channel_unlock(c0);
06710 
06711    ast_channel_lock(c1);
06712    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER"))) {
06713       pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0_name);
06714    }
06715    if (c0_pvtid) {
06716       pbx_builtin_setvar_helper(c1, "BRIDGEPVTCALLID", c0_pvtid);
06717    }
06718    ast_channel_unlock(c1);
06719 }
06720 
06721 static void bridge_play_sounds(struct ast_channel *c0, struct ast_channel *c1)
06722 {
06723    const char *s, *sound;
06724 
06725    /* See if we need to play an audio file to any side of the bridge */
06726 
06727    ast_channel_lock(c0);
06728    if ((s = pbx_builtin_getvar_helper(c0, "BRIDGE_PLAY_SOUND"))) {
06729       sound = ast_strdupa(s);
06730       ast_channel_unlock(c0);
06731       bridge_playfile(c0, c1, sound, 0);
06732       pbx_builtin_setvar_helper(c0, "BRIDGE_PLAY_SOUND", NULL);
06733    } else {
06734       ast_channel_unlock(c0);
06735    }
06736 
06737    ast_channel_lock(c1);
06738    if ((s = pbx_builtin_getvar_helper(c1, "BRIDGE_PLAY_SOUND"))) {
06739       sound = ast_strdupa(s);
06740       ast_channel_unlock(c1);
06741       bridge_playfile(c1, c0, sound, 0);
06742       pbx_builtin_setvar_helper(c1, "BRIDGE_PLAY_SOUND", NULL);
06743    } else {
06744       ast_channel_unlock(c1);
06745    }
06746 }
06747 
06748 /*! \brief Bridge two channels together */
06749 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
06750                  struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
06751 {
06752    struct ast_channel *who = NULL, *chans[2] = { c0, c1 };
06753    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
06754    format_t o0nativeformats;
06755    format_t o1nativeformats;
06756    long time_left_ms=0;
06757    char caller_warning = 0;
06758    char callee_warning = 0;
06759 
06760    if (c0->_bridge) {
06761       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
06762          c0->name, c0->_bridge->name);
06763       return -1;
06764    }
06765    if (c1->_bridge) {
06766       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
06767          c1->name, c1->_bridge->name);
06768       return -1;
06769    }
06770    
06771    /* Stop if we're a zombie or need a soft hangup */
06772    if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
06773        ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
06774       return -1;
06775 
06776    *fo = NULL;
06777 
06778    if (ast_tvzero(config->start_time)) {
06779       config->start_time = ast_tvnow();
06780       if (config->start_sound) {
06781          if (caller_warning) {
06782             bridge_playfile(c0, c1, config->start_sound, config->timelimit / 1000);
06783          }
06784          if (callee_warning) {
06785             bridge_playfile(c1, c0, config->start_sound, config->timelimit / 1000);
06786          }
06787       }
06788    }
06789 
06790    /* Keep track of bridge */
06791    c0->_bridge = c1;
06792    c1->_bridge = c0;
06793 
06794    ast_set_owners_and_peers(c0, c1);
06795 
06796    o0nativeformats = c0->nativeformats;
06797    o1nativeformats = c1->nativeformats;
06798 
06799    if (config->feature_timer && !ast_tvzero(config->nexteventts)) {
06800       config->nexteventts = ast_tvadd(config->feature_start_time, ast_samp2tv(config->feature_timer, 1000));
06801    } else if (config->timelimit) {
06802       time_left_ms = config->timelimit - ast_tvdiff_ms(ast_tvnow(), config->start_time);
06803       caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
06804       callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
06805       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
06806       if ((caller_warning || callee_warning) && config->play_warning) {
06807          long next_warn = config->play_warning;
06808          if (time_left_ms < config->play_warning) {
06809             /* At least one warning was played, which means we are returning after feature */
06810             long warns_passed = (config->play_warning - time_left_ms) / config->warning_freq;
06811             /* It is 'warns_passed * warning_freq' NOT '(warns_passed + 1) * warning_freq',
06812                because nexteventts will be updated once again in the 'if (!to)' block */
06813             next_warn = config->play_warning - warns_passed * config->warning_freq;
06814          }
06815          config->nexteventts = ast_tvsub(config->nexteventts, ast_samp2tv(next_warn, 1000));
06816       }
06817    } else {
06818       config->nexteventts.tv_sec = 0;
06819       config->nexteventts.tv_usec = 0;
06820    }
06821 
06822    if (!c0->tech->send_digit_begin)
06823       ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
06824    if (!c1->tech->send_digit_begin)
06825       ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
06826    manager_bridge_event(1, 1, c0, c1);
06827 
06828    /* Before we enter in and bridge these two together tell them both the source of audio has changed */
06829    ast_indicate(c0, AST_CONTROL_SRCCHANGE);
06830    ast_indicate(c1, AST_CONTROL_SRCCHANGE);
06831 
06832    for (/* ever */;;) {
06833       struct timeval now = { 0, };
06834       int to;
06835 
06836       to = -1;
06837 
06838       if (!ast_tvzero(config->nexteventts)) {
06839          now = ast_tvnow();
06840          to = ast_tvdiff_ms(config->nexteventts, now);
06841          if (to <= 0) {
06842             if (!config->timelimit) {
06843                res = AST_BRIDGE_COMPLETE;
06844                break;
06845             }
06846             to = 0;
06847          }
06848       }
06849 
06850       if (config->timelimit) {
06851          time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
06852          if (time_left_ms < to)
06853             to = time_left_ms;
06854 
06855          if (time_left_ms <= 0) {
06856             if (caller_warning && config->end_sound)
06857                bridge_playfile(c0, c1, config->end_sound, 0);
06858             if (callee_warning && config->end_sound)
06859                bridge_playfile(c1, c0, config->end_sound, 0);
06860             *fo = NULL;
06861             if (who)
06862                *rc = who;
06863             res = 0;
06864             break;
06865          }
06866 
06867          if (!to) {
06868             if (time_left_ms >= 5000 && config->warning_sound && config->play_warning && ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
06869                int t = (time_left_ms + 500) / 1000; /* round to nearest second */
06870                if (caller_warning)
06871                   bridge_playfile(c0, c1, config->warning_sound, t);
06872                if (callee_warning)
06873                   bridge_playfile(c1, c0, config->warning_sound, t);
06874             }
06875 
06876             if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000))) {
06877                config->nexteventts = ast_tvadd(config->nexteventts, ast_samp2tv(config->warning_freq, 1000));
06878             } else {
06879                config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
06880             }
06881          }
06882          ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
06883       }
06884 
06885       if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
06886          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
06887             c0->_softhangup = 0;
06888          if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
06889             c1->_softhangup = 0;
06890          c0->_bridge = c1;
06891          c1->_bridge = c0;
06892          ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
06893          continue;
06894       }
06895 
06896       /* Stop if we're a zombie or need a soft hangup */
06897       if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
06898           ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
06899          *fo = NULL;
06900          if (who)
06901             *rc = who;
06902          res = 0;
06903          ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
06904             c0->name, c1->name,
06905             ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
06906             ast_check_hangup(c0) ? "Yes" : "No",
06907             ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
06908             ast_check_hangup(c1) ? "Yes" : "No");
06909          break;
06910       }
06911 
06912       update_bridge_vars(c0, c1);
06913 
06914       bridge_play_sounds(c0, c1);
06915 
06916       if (c0->tech->bridge &&
06917          /* if < 1 ms remains use generic bridging for accurate timing */
06918          (!config->timelimit || to > 1000 || to == 0) &&
06919           (c0->tech->bridge == c1->tech->bridge) &&
06920           !c0->monitor && !c1->monitor &&
06921           !c0->audiohooks && !c1->audiohooks &&
06922           !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
06923          int timeoutms = to - 1000 > 0 ? to - 1000 : to;
06924          /* Looks like they share a bridge method and nothing else is in the way */
06925          ast_set_flag(c0, AST_FLAG_NBRIDGE);
06926          ast_set_flag(c1, AST_FLAG_NBRIDGE);
06927          if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, timeoutms)) == AST_BRIDGE_COMPLETE) {
06928             ast_manager_event_multichan(EVENT_FLAG_CALL, "Unlink", 2, chans,
06929                "Channel1: %s\r\n"
06930                "Channel2: %s\r\n"
06931                "Uniqueid1: %s\r\n"
06932                "Uniqueid2: %s\r\n"
06933                "CallerID1: %s\r\n"
06934                "CallerID2: %s\r\n",
06935                c0->name, c1->name,
06936                c0->uniqueid, c1->uniqueid,
06937                S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, "<unknown>"),
06938                S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, "<unknown>"));
06939 
06940             ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
06941 
06942             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
06943             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
06944 
06945             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
06946                continue;
06947 
06948             c0->_bridge = NULL;
06949             c1->_bridge = NULL;
06950             return res;
06951          } else {
06952             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
06953             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
06954          }
06955          switch (res) {
06956          case AST_BRIDGE_RETRY:
06957             if (config->play_warning) {
06958                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
06959             }
06960             continue;
06961          default:
06962             ast_verb(3, "Native bridging %s and %s ended\n", c0->name, c1->name);
06963             /* fallthrough */
06964          case AST_BRIDGE_FAILED_NOWARN:
06965             break;
06966          }
06967       }
06968 
06969       if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
06970           (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
06971           !(c0->generator || c1->generator)) {
06972          if (ast_channel_make_compatible(c0, c1)) {
06973             ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
06974             manager_bridge_event(0, 1, c0, c1);
06975             return AST_BRIDGE_FAILED;
06976          }
06977          o0nativeformats = c0->nativeformats;
06978          o1nativeformats = c1->nativeformats;
06979       }
06980 
06981       update_bridge_vars(c0, c1);
06982 
06983       res = ast_generic_bridge(c0, c1, config, fo, rc);
06984       if (res != AST_BRIDGE_RETRY) {
06985          break;
06986       } else if (config->feature_timer) {
06987          /* feature timer expired but has not been updated, sending to ast_bridge_call to do so */
06988          break;
06989       }
06990    }
06991 
06992    ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
06993    ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
06994 
06995    /* Now that we have broken the bridge the source will change yet again */
06996    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
06997    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
06998 
06999    c0->_bridge = NULL;
07000    c1->_bridge = NULL;
07001 
07002    ast_manager_event_multichan(EVENT_FLAG_CALL, "Unlink", 2, chans,
07003       "Channel1: %s\r\n"
07004       "Channel2: %s\r\n"
07005       "Uniqueid1: %s\r\n"
07006       "Uniqueid2: %s\r\n"
07007       "CallerID1: %s\r\n"
07008       "CallerID2: %s\r\n",
07009       c0->name, c1->name,
07010       c0->uniqueid, c1->uniqueid,
07011       S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, "<unknown>"),
07012       S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, "<unknown>"));
07013    ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
07014 
07015    return res;
07016 }
07017 
07018 /*! \brief Sets an option on a channel */
07019 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
07020 {
07021    if (!chan->tech->setoption) {
07022       errno = ENOSYS;
07023       return -1;
07024    }
07025 
07026    if (block)
07027       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
07028 
07029    return chan->tech->setoption(chan, option, data, datalen);
07030 }
07031 
07032 int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
07033 {
07034    if (!chan->tech->queryoption) {
07035       errno = ENOSYS;
07036       return -1;
07037    }
07038 
07039    if (block)
07040       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
07041 
07042    return chan->tech->queryoption(chan, option, data, datalen);
07043 }
07044 
07045 struct tonepair_def {
07046    int freq1;
07047    int freq2;
07048    int duration;
07049    int vol;
07050 };
07051 
07052 struct tonepair_state {
07053    int fac1;
07054    int fac2;
07055    int v1_1;
07056    int v2_1;
07057    int v3_1;
07058    int v1_2;
07059    int v2_2;
07060    int v3_2;
07061    format_t origwfmt;
07062    int pos;
07063    int duration;
07064    int modulate;
07065    struct ast_frame f;
07066    unsigned char offset[AST_FRIENDLY_OFFSET];
07067    short data[4000];
07068 };
07069 
07070 static void tonepair_release(struct ast_channel *chan, void *params)
07071 {
07072    struct tonepair_state *ts = params;
07073 
07074    if (chan)
07075       ast_set_write_format(chan, ts->origwfmt);
07076    ast_free(ts);
07077 }
07078 
07079 static void *tonepair_alloc(struct ast_channel *chan, void *params)
07080 {
07081    struct tonepair_state *ts;
07082    struct tonepair_def *td = params;
07083 
07084    if (!(ts = ast_calloc(1, sizeof(*ts))))
07085       return NULL;
07086    ts->origwfmt = chan->writeformat;
07087    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
07088       ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
07089       tonepair_release(NULL, ts);
07090       ts = NULL;
07091    } else {
07092       ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
07093       ts->v1_1 = 0;
07094       ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
07095       ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
07096       ts->v2_1 = 0;
07097       ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
07098       ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
07099       ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
07100       ts->duration = td->duration;
07101       ts->modulate = 0;
07102    }
07103    /* Let interrupts interrupt :) */
07104    ast_set_flag(chan, AST_FLAG_WRITE_INT);
07105    return ts;
07106 }
07107 
07108 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
07109 {
07110    struct tonepair_state *ts = data;
07111    int x;
07112 
07113    /* we need to prepare a frame with 16 * timelen samples as we're
07114     * generating SLIN audio
07115     */
07116    len = samples * 2;
07117 
07118    if (len > sizeof(ts->data) / 2 - 1) {
07119       ast_log(LOG_WARNING, "Can't generate that much data!\n");
07120       return -1;
07121    }
07122    memset(&ts->f, 0, sizeof(ts->f));
07123    for (x=0;x<len/2;x++) {
07124       ts->v1_1 = ts->v2_1;
07125       ts->v2_1 = ts->v3_1;
07126       ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
07127       
07128       ts->v1_2 = ts->v2_2;
07129       ts->v2_2 = ts->v3_2;
07130       ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
07131       if (ts->modulate) {
07132          int p;
07133          p = ts->v3_2 - 32768;
07134          if (p < 0) p = -p;
07135          p = ((p * 9) / 10) + 1;
07136          ts->data[x] = (ts->v3_1 * p) >> 15;
07137       } else
07138          ts->data[x] = ts->v3_1 + ts->v3_2; 
07139    }
07140    ts->f.frametype = AST_FRAME_VOICE;
07141    ts->f.subclass.codec = AST_FORMAT_SLINEAR;
07142    ts->f.datalen = len;
07143    ts->f.samples = samples;
07144    ts->f.offset = AST_FRIENDLY_OFFSET;
07145    ts->f.data.ptr = ts->data;
07146    ast_write(chan, &ts->f);
07147    ts->pos += x;
07148    if (ts->duration > 0) {
07149       if (ts->pos >= ts->duration * 8)
07150          return -1;
07151    }
07152    return 0;
07153 }
07154 
07155 static struct ast_generator tonepair = {
07156    alloc: tonepair_alloc,
07157    release: tonepair_release,
07158    generate: tonepair_generator,
07159 };
07160 
07161 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
07162 {
07163    struct tonepair_def d = { 0, };
07164 
07165    d.freq1 = freq1;
07166    d.freq2 = freq2;
07167    d.duration = duration;
07168    d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
07169    if (ast_activate_generator(chan, &tonepair, &d))
07170       return -1;
07171    return 0;
07172 }
07173 
07174 void ast_tonepair_stop(struct ast_channel *chan)
07175 {
07176    ast_deactivate_generator(chan);
07177 }
07178 
07179 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
07180 {
07181    int res;
07182 
07183    if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
07184       return res;
07185 
07186    /* Give us some wiggle room */
07187    while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
07188       struct ast_frame *f = ast_read(chan);
07189       if (f)
07190          ast_frfree(f);
07191       else
07192          return -1;
07193    }
07194    return 0;
07195 }
07196 
07197 ast_group_t ast_get_group(const char *s)
07198 {
07199    char *piece;
07200    char *c;
07201    int start=0, finish=0, x;
07202    ast_group_t group = 0;
07203 
07204    if (ast_strlen_zero(s))
07205       return 0;
07206 
07207    c = ast_strdupa(s);
07208    
07209    while ((piece = strsep(&c, ","))) {
07210       if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) {
07211          /* Range */
07212       } else if (sscanf(piece, "%30d", &start)) {
07213          /* Just one */
07214          finish = start;
07215       } else {
07216          ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
07217          continue;
07218       }
07219       for (x = start; x <= finish; x++) {
07220          if ((x > 63) || (x < 0)) {
07221             ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
07222          } else
07223             group |= ((ast_group_t) 1 << x);
07224       }
07225    }
07226    return group;
07227 }
07228 
07229 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
07230 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
07231 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
07232 
07233 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
07234              void (*stop_ptr)(struct ast_channel *),
07235              void (*cleanup_ptr)(struct ast_channel *))
07236 {
07237    ast_moh_start_ptr = start_ptr;
07238    ast_moh_stop_ptr = stop_ptr;
07239    ast_moh_cleanup_ptr = cleanup_ptr;
07240 }
07241 
07242 void ast_uninstall_music_functions(void)
07243 {
07244    ast_moh_start_ptr = NULL;
07245    ast_moh_stop_ptr = NULL;
07246    ast_moh_cleanup_ptr = NULL;
07247 }
07248 
07249 /*! \brief Turn on music on hold on a given channel */
07250 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
07251 {
07252    if (ast_moh_start_ptr)
07253       return ast_moh_start_ptr(chan, mclass, interpclass);
07254 
07255    ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));
07256 
07257    return 0;
07258 }
07259 
07260 /*! \brief Turn off music on hold on a given channel */
07261 void ast_moh_stop(struct ast_channel *chan)
07262 {
07263    if (ast_moh_stop_ptr)
07264       ast_moh_stop_ptr(chan);
07265 }
07266 
07267 void ast_moh_cleanup(struct ast_channel *chan)
07268 {
07269    if (ast_moh_cleanup_ptr)
07270       ast_moh_cleanup_ptr(chan);
07271 }
07272 
07273 static int ast_channel_hash_cb(const void *obj, const int flags)
07274 {
07275    const struct ast_channel *chan = obj;
07276 
07277    /* If the name isn't set, return 0 so that the ao2_find() search will
07278     * start in the first bucket. */
07279    if (ast_strlen_zero(chan->name)) {
07280       return 0;
07281    }
07282 
07283    return ast_str_case_hash(chan->name);
07284 }
07285 
07286 int ast_plc_reload(void)
07287 {
07288    struct ast_variable *var;
07289    struct ast_flags config_flags = { 0 };
07290    struct ast_config *cfg = ast_config_load("codecs.conf", config_flags);
07291    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
07292       return 0;
07293    for (var = ast_variable_browse(cfg, "plc"); var; var = var->next) {
07294       if (!strcasecmp(var->name, "genericplc")) {
07295          ast_set2_flag(&ast_options, ast_true(var->value), AST_OPT_FLAG_GENERIC_PLC);
07296       }
07297    }
07298    ast_config_destroy(cfg);
07299    return 0;
07300 }
07301 
07302 /*!
07303  * \internal
07304  * \brief Implements the channels provider.
07305  */
07306 static int data_channels_provider_handler(const struct ast_data_search *search,
07307    struct ast_data *root)
07308 {
07309    struct ast_channel *c;
07310    struct ast_channel_iterator *iter = NULL;
07311    struct ast_data *data_channel;
07312 
07313    for (iter = ast_channel_iterator_all_new();
07314       iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
07315       ast_channel_lock(c);
07316 
07317       data_channel = ast_data_add_node(root, "channel");
07318       if (!data_channel) {
07319          ast_channel_unlock(c);
07320          continue;
07321       }
07322 
07323       if (ast_channel_data_add_structure(data_channel, c, 1) < 0) {
07324          ast_log(LOG_ERROR, "Unable to add channel structure for channel: %s\n", c->name);
07325       }
07326 
07327       ast_channel_unlock(c);
07328 
07329       if (!ast_data_search_match(search, data_channel)) {
07330          ast_data_remove_node(root, data_channel);
07331       }
07332    }
07333    if (iter) {
07334       ast_channel_iterator_destroy(iter);
07335    }
07336 
07337    return 0;
07338 }
07339 
07340 /*!
07341  * \internal
07342  * \brief Implements the channeltypes provider.
07343  */
07344 static int data_channeltypes_provider_handler(const struct ast_data_search *search,
07345    struct ast_data *data_root)
07346 {
07347    struct chanlist *cl;
07348    struct ast_data *data_type;
07349 
07350    AST_RWLIST_RDLOCK(&backends);
07351    AST_RWLIST_TRAVERSE(&backends, cl, list) {
07352       data_type = ast_data_add_node(data_root, "type");
07353       if (!data_type) {
07354          continue;
07355       }
07356       ast_data_add_str(data_type, "name", cl->tech->type);
07357       ast_data_add_str(data_type, "description", cl->tech->description);
07358       ast_data_add_bool(data_type, "devicestate", cl->tech->devicestate ? 1 : 0);
07359       ast_data_add_bool(data_type, "indications", cl->tech->indicate ? 1 : 0);
07360       ast_data_add_bool(data_type, "transfer", cl->tech->transfer ? 1 : 0);
07361       ast_data_add_bool(data_type, "send_digit_begin", cl->tech->send_digit_begin ? 1 : 0);
07362       ast_data_add_bool(data_type, "send_digit_end", cl->tech->send_digit_end ? 1 : 0);
07363       ast_data_add_bool(data_type, "call", cl->tech->call ? 1 : 0);
07364       ast_data_add_bool(data_type, "hangup", cl->tech->hangup ? 1 : 0);
07365       ast_data_add_bool(data_type, "answer", cl->tech->answer ? 1 : 0);
07366       ast_data_add_bool(data_type, "read", cl->tech->read ? 1 : 0);
07367       ast_data_add_bool(data_type, "write", cl->tech->write ? 1 : 0);
07368       ast_data_add_bool(data_type, "send_text", cl->tech->send_text ? 1 : 0);
07369       ast_data_add_bool(data_type, "send_image", cl->tech->send_image ? 1 : 0);
07370       ast_data_add_bool(data_type, "send_html", cl->tech->send_html ? 1 : 0);
07371       ast_data_add_bool(data_type, "exception", cl->tech->exception ? 1 : 0);
07372       ast_data_add_bool(data_type, "bridge", cl->tech->bridge ? 1 : 0);
07373       ast_data_add_bool(data_type, "early_bridge", cl->tech->early_bridge ? 1 : 0);
07374       ast_data_add_bool(data_type, "fixup", cl->tech->fixup ? 1 : 0);
07375       ast_data_add_bool(data_type, "setoption", cl->tech->setoption ? 1 : 0);
07376       ast_data_add_bool(data_type, "queryoption", cl->tech->queryoption ? 1 : 0);
07377       ast_data_add_bool(data_type, "write_video", cl->tech->write_video ? 1 : 0);
07378       ast_data_add_bool(data_type, "write_text", cl->tech->write_text ? 1 : 0);
07379       ast_data_add_bool(data_type, "bridged_channel", cl->tech->bridged_channel ? 1 : 0);
07380       ast_data_add_bool(data_type, "func_channel_read", cl->tech->func_channel_read ? 1 : 0);
07381       ast_data_add_bool(data_type, "func_channel_write", cl->tech->func_channel_write ? 1 : 0);
07382       ast_data_add_bool(data_type, "get_base_channel", cl->tech->get_base_channel ? 1 : 0);
07383       ast_data_add_bool(data_type, "set_base_channel", cl->tech->set_base_channel ? 1 : 0);
07384       ast_data_add_bool(data_type, "get_pvt_uniqueid", cl->tech->get_pvt_uniqueid ? 1 : 0);
07385       ast_data_add_bool(data_type, "cc_callback", cl->tech->cc_callback ? 1 : 0);
07386 
07387       ast_data_add_codecs(data_type, "capabilities", cl->tech->capabilities);
07388 
07389       if (!ast_data_search_match(search, data_type)) {
07390          ast_data_remove_node(data_root, data_type);
07391       }
07392    }
07393    AST_RWLIST_UNLOCK(&backends);
07394 
07395    return 0;
07396 }
07397 
07398 /*!
07399  * \internal
07400  * \brief /asterisk/core/channels provider.
07401  */
07402 static const struct ast_data_handler channels_provider = {
07403    .version = AST_DATA_HANDLER_VERSION,
07404    .get = data_channels_provider_handler
07405 };
07406 
07407 /*!
07408  * \internal
07409  * \brief /asterisk/core/channeltypes provider.
07410  */
07411 static const struct ast_data_handler channeltypes_provider = {
07412    .version = AST_DATA_HANDLER_VERSION,
07413    .get = data_channeltypes_provider_handler
07414 };
07415 
07416 static const struct ast_data_entry channel_providers[] = {
07417    AST_DATA_ENTRY("/asterisk/core/channels", &channels_provider),
07418    AST_DATA_ENTRY("/asterisk/core/channeltypes", &channeltypes_provider),
07419 };
07420 
07421 void ast_channels_init(void)
07422 {
07423    channels = ao2_container_alloc(NUM_CHANNEL_BUCKETS,
07424          ast_channel_hash_cb, ast_channel_cmp_cb);
07425 
07426    ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));
07427 
07428    ast_data_register_multiple_core(channel_providers, ARRAY_LEN(channel_providers));
07429 
07430    ast_plc_reload();
07431 }
07432 
07433 /*! \brief Print call group and pickup group ---*/
07434 char *ast_print_group(char *buf, int buflen, ast_group_t group)
07435 {
07436    unsigned int i;
07437    int first = 1;
07438    char num[3];
07439 
07440    buf[0] = '\0';
07441    
07442    if (!group) /* Return empty string if no group */
07443       return buf;
07444 
07445    for (i = 0; i <= 63; i++) {   /* Max group is 63 */
07446       if (group & ((ast_group_t) 1 << i)) {
07447             if (!first) {
07448             strncat(buf, ", ", buflen - strlen(buf) - 1);
07449          } else {
07450             first = 0;
07451          }
07452          snprintf(num, sizeof(num), "%u", i);
07453          strncat(buf, num, buflen - strlen(buf) - 1);
07454       }
07455    }
07456    return buf;
07457 }
07458 
07459 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
07460 {
07461    struct ast_variable *cur;
07462 
07463    for (cur = vars; cur; cur = cur->next)
07464       pbx_builtin_setvar_helper(chan, cur->name, cur->value);  
07465 }
07466 
07467 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
07468 {
07469    /* just store the data pointer in the channel structure */
07470    return data;
07471 }
07472 
07473 static void silence_generator_release(struct ast_channel *chan, void *data)
07474 {
07475    /* nothing to do */
07476 }
07477 
07478 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
07479 {
07480    short buf[samples];
07481    struct ast_frame frame = {
07482       .frametype = AST_FRAME_VOICE,
07483       .subclass.codec = AST_FORMAT_SLINEAR,
07484       .data.ptr = buf,
07485       .samples = samples,
07486       .datalen = sizeof(buf),
07487    };
07488 
07489    memset(buf, 0, sizeof(buf));
07490 
07491    if (ast_write(chan, &frame))
07492       return -1;
07493 
07494    return 0;
07495 }
07496 
07497 static struct ast_generator silence_generator = {
07498    .alloc = silence_generator_alloc,
07499    .release = silence_generator_release,
07500    .generate = silence_generator_generate,
07501 };
07502 
07503 struct ast_silence_generator {
07504    int old_write_format;
07505 };
07506 
07507 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
07508 {
07509    struct ast_silence_generator *state;
07510 
07511    if (!(state = ast_calloc(1, sizeof(*state)))) {
07512       return NULL;
07513    }
07514 
07515    state->old_write_format = chan->writeformat;
07516 
07517    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
07518       ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
07519       ast_free(state);
07520       return NULL;
07521    }
07522 
07523    ast_activate_generator(chan, &silence_generator, state);
07524 
07525    ast_debug(1, "Started silence generator on '%s'\n", chan->name);
07526 
07527    return state;
07528 }
07529 
07530 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
07531 {
07532    if (!state)
07533       return;
07534 
07535    ast_deactivate_generator(chan);
07536 
07537    ast_debug(1, "Stopped silence generator on '%s'\n", chan->name);
07538 
07539    if (ast_set_write_format(chan, state->old_write_format) < 0)
07540       ast_log(LOG_ERROR, "Could not return write format to its original state\n");
07541 
07542    ast_free(state);
07543 }
07544 
07545 
07546 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
07547 const char *channelreloadreason2txt(enum channelreloadreason reason)
07548 {
07549    switch (reason) {
07550    case CHANNEL_MODULE_LOAD:
07551       return "LOAD (Channel module load)";
07552 
07553    case CHANNEL_MODULE_RELOAD:
07554       return "RELOAD (Channel module reload)";
07555 
07556    case CHANNEL_CLI_RELOAD:
07557       return "CLIRELOAD (Channel module reload by CLI command)";
07558 
07559    default:
07560       return "MANAGERRELOAD (Channel module reload by manager)";
07561    }
07562 };
07563 
07564 /*
07565  * Wrappers for various ast_say_*() functions that call the full version
07566  * of the same functions.
07567  * The proper place would be say.c, but that file is optional and one
07568  * must be able to build asterisk even without it (using a loadable 'say'
07569  * implementation that only supplies the 'full' version of the functions.
07570  */
07571 
07572 int ast_say_number(struct ast_channel *chan, int num,
07573    const char *ints, const char *language, const char *options)
07574 {
07575    return ast_say_number_full(chan, num, ints, language, options, -1, -1);
07576 }
07577 
07578 int ast_say_enumeration(struct ast_channel *chan, int num,
07579    const char *ints, const char *language, const char *options)
07580 {
07581    return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
07582 }
07583 
07584 int ast_say_digits(struct ast_channel *chan, int num,
07585    const char *ints, const char *lang)
07586 {
07587    return ast_say_digits_full(chan, num, ints, lang, -1, -1);
07588 }
07589 
07590 int ast_say_digit_str(struct ast_channel *chan, const char *str,
07591    const char *ints, const char *lang)
07592 {
07593    return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
07594 }
07595 
07596 int ast_say_character_str(struct ast_channel *chan, const char *str,
07597    const char *ints, const char *lang)
07598 {
07599    return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
07600 }
07601 
07602 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
07603    const char *ints, const char *lang)
07604 {
07605    return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
07606 }
07607 
07608 int ast_say_digits_full(struct ast_channel *chan, int num,
07609    const char *ints, const char *lang, int audiofd, int ctrlfd)
07610 {
07611    char buf[256];
07612 
07613    snprintf(buf, sizeof(buf), "%d", num);
07614 
07615    return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
07616 }
07617 
07618 void ast_connected_line_copy_from_caller(struct ast_party_connected_line *dest, const struct ast_party_caller *src)
07619 {
07620    ast_party_id_copy(&dest->id, &src->id);
07621    ast_party_id_copy(&dest->ani, &src->ani);
07622    dest->ani2 = src->ani2;
07623 }
07624 
07625 void ast_connected_line_copy_to_caller(struct ast_party_caller *dest, const struct ast_party_connected_line *src)
07626 {
07627    ast_party_id_copy(&dest->id, &src->id);
07628    ast_party_id_copy(&dest->ani, &src->ani);
07629 
07630    dest->ani2 = src->ani2;
07631 }
07632 
07633 void ast_channel_set_connected_line(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
07634 {
07635    if (&chan->connected == connected) {
07636       /* Don't set to self */
07637       return;
07638    }
07639 
07640    ast_channel_lock(chan);
07641    ast_party_connected_line_set(&chan->connected, connected, update);
07642    ast_channel_unlock(chan);
07643 }
07644 
07645 /*! \note Should follow struct ast_party_name */
07646 struct ast_party_name_ies {
07647    /*! \brief Subscriber name ie */
07648    int str;
07649    /*! \brief Character set ie. */
07650    int char_set;
07651    /*! \brief presentation-indicator ie */
07652    int presentation;
07653    /*! \brief valid/present ie */
07654    int valid;
07655 };
07656 
07657 /*!
07658  * \internal
07659  * \since 1.8
07660  * \brief Build a party name information data frame component.
07661  *
07662  * \param data Buffer to fill with the frame data
07663  * \param datalen Size of the buffer to fill
07664  * \param name Party name information
07665  * \param label Name of particular party name
07666  * \param ies Data frame ie values for the party name components
07667  *
07668  * \retval -1 if error
07669  * \retval Amount of data buffer used
07670  */
07671 static int party_name_build_data(unsigned char *data, size_t datalen, const struct ast_party_name *name, const char *label, const struct ast_party_name_ies *ies)
07672 {
07673    size_t length;
07674    size_t pos = 0;
07675 
07676    /*
07677     * The size of integer values must be fixed in case the frame is
07678     * shipped to another machine.
07679     */
07680    if (name->str) {
07681       length = strlen(name->str);
07682       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
07683          ast_log(LOG_WARNING, "No space left for %s name\n", label);
07684          return -1;
07685       }
07686       data[pos++] = ies->str;
07687       data[pos++] = length;
07688       memcpy(data + pos, name->str, length);
07689       pos += length;
07690    }
07691 
07692    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07693       ast_log(LOG_WARNING, "No space left for %s name char set\n", label);
07694       return -1;
07695    }
07696    data[pos++] = ies->char_set;
07697    data[pos++] = 1;
07698    data[pos++] = name->char_set;
07699 
07700    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07701       ast_log(LOG_WARNING, "No space left for %s name presentation\n", label);
07702       return -1;
07703    }
07704    data[pos++] = ies->presentation;
07705    data[pos++] = 1;
07706    data[pos++] = name->presentation;
07707 
07708    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07709       ast_log(LOG_WARNING, "No space left for %s name valid\n", label);
07710       return -1;
07711    }
07712    data[pos++] = ies->valid;
07713    data[pos++] = 1;
07714    data[pos++] = name->valid;
07715 
07716    return pos;
07717 }
07718 
07719 /*! \note Should follow struct ast_party_number */
07720 struct ast_party_number_ies {
07721    /*! \brief Subscriber phone number ie */
07722    int str;
07723    /*! \brief Type-Of-Number and Numbering-Plan ie */
07724    int plan;
07725    /*! \brief presentation-indicator ie */
07726    int presentation;
07727    /*! \brief valid/present ie */
07728    int valid;
07729 };
07730 
07731 /*!
07732  * \internal
07733  * \since 1.8
07734  * \brief Build a party number information data frame component.
07735  *
07736  * \param data Buffer to fill with the frame data
07737  * \param datalen Size of the buffer to fill
07738  * \param number Party number information
07739  * \param label Name of particular party number
07740  * \param ies Data frame ie values for the party number components
07741  *
07742  * \retval -1 if error
07743  * \retval Amount of data buffer used
07744  */
07745 static int party_number_build_data(unsigned char *data, size_t datalen, const struct ast_party_number *number, const char *label, const struct ast_party_number_ies *ies)
07746 {
07747    size_t length;
07748    size_t pos = 0;
07749 
07750    /*
07751     * The size of integer values must be fixed in case the frame is
07752     * shipped to another machine.
07753     */
07754    if (number->str) {
07755       length = strlen(number->str);
07756       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
07757          ast_log(LOG_WARNING, "No space left for %s number\n", label);
07758          return -1;
07759       }
07760       data[pos++] = ies->str;
07761       data[pos++] = length;
07762       memcpy(data + pos, number->str, length);
07763       pos += length;
07764    }
07765 
07766    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07767       ast_log(LOG_WARNING, "No space left for %s numbering plan\n", label);
07768       return -1;
07769    }
07770    data[pos++] = ies->plan;
07771    data[pos++] = 1;
07772    data[pos++] = number->plan;
07773 
07774    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07775       ast_log(LOG_WARNING, "No space left for %s number presentation\n", label);
07776       return -1;
07777    }
07778    data[pos++] = ies->presentation;
07779    data[pos++] = 1;
07780    data[pos++] = number->presentation;
07781 
07782    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07783       ast_log(LOG_WARNING, "No space left for %s number valid\n", label);
07784       return -1;
07785    }
07786    data[pos++] = ies->valid;
07787    data[pos++] = 1;
07788    data[pos++] = number->valid;
07789 
07790    return pos;
07791 }
07792 
07793 /*! \note Should follow struct ast_party_subaddress */
07794 struct ast_party_subaddress_ies {
07795    /*! \brief subaddress ie. */
07796    int str;
07797    /*! \brief subaddress type ie */
07798    int type;
07799    /*! \brief odd/even indicator ie */
07800    int odd_even_indicator;
07801    /*! \brief valid/present ie */
07802    int valid;
07803 };
07804 
07805 /*!
07806  * \internal
07807  * \since 1.8
07808  * \brief Build a party subaddress information data frame component.
07809  *
07810  * \param data Buffer to fill with the frame data
07811  * \param datalen Size of the buffer to fill
07812  * \param subaddress Party subaddress information
07813  * \param label Name of particular party subaddress
07814  * \param ies Data frame ie values for the party subaddress components
07815  *
07816  * \retval -1 if error
07817  * \retval Amount of data buffer used
07818  */
07819 static int party_subaddress_build_data(unsigned char *data, size_t datalen, const struct ast_party_subaddress *subaddress, const char *label, const struct ast_party_subaddress_ies *ies)
07820 {
07821    size_t length;
07822    size_t pos = 0;
07823 
07824    /*
07825     * The size of integer values must be fixed in case the frame is
07826     * shipped to another machine.
07827     */
07828    if (subaddress->str) {
07829       length = strlen(subaddress->str);
07830       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
07831          ast_log(LOG_WARNING, "No space left for %s subaddress\n", label);
07832          return -1;
07833       }
07834       data[pos++] = ies->str;
07835       data[pos++] = length;
07836       memcpy(data + pos, subaddress->str, length);
07837       pos += length;
07838    }
07839 
07840    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07841       ast_log(LOG_WARNING, "No space left for %s type of subaddress\n", label);
07842       return -1;
07843    }
07844    data[pos++] = ies->type;
07845    data[pos++] = 1;
07846    data[pos++] = subaddress->type;
07847 
07848    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07849       ast_log(LOG_WARNING,
07850          "No space left for %s subaddress odd-even indicator\n", label);
07851       return -1;
07852    }
07853    data[pos++] = ies->odd_even_indicator;
07854    data[pos++] = 1;
07855    data[pos++] = subaddress->odd_even_indicator;
07856 
07857    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07858       ast_log(LOG_WARNING, "No space left for %s subaddress valid\n", label);
07859       return -1;
07860    }
07861    data[pos++] = ies->valid;
07862    data[pos++] = 1;
07863    data[pos++] = subaddress->valid;
07864 
07865    return pos;
07866 }
07867 
07868 /*! \note Should follow struct ast_party_id */
07869 struct ast_party_id_ies {
07870    /*! \brief Subscriber name ies */
07871    struct ast_party_name_ies name;
07872    /*! \brief Subscriber phone number ies */
07873    struct ast_party_number_ies number;
07874    /*! \brief Subscriber subaddress ies. */
07875    struct ast_party_subaddress_ies subaddress;
07876    /*! \brief User party id tag ie. */
07877    int tag;
07878    /*! \brief Combined name and number presentation ie. */
07879    int combined_presentation;
07880 };
07881 
07882 /*!
07883  * \internal
07884  * \since 1.8
07885  * \brief Build a party id information data frame component.
07886  *
07887  * \param data Buffer to fill with the frame data
07888  * \param datalen Size of the buffer to fill
07889  * \param id Party id information
07890  * \param label Name of particular party id
07891  * \param ies Data frame ie values for the party id components
07892  * \param update What id information to build.  NULL if all.
07893  *
07894  * \retval -1 if error
07895  * \retval Amount of data buffer used
07896  */
07897 static int party_id_build_data(unsigned char *data, size_t datalen,
07898    const struct ast_party_id *id, const char *label, const struct ast_party_id_ies *ies,
07899    const struct ast_set_party_id *update)
07900 {
07901    size_t length;
07902    size_t pos = 0;
07903    int res;
07904 
07905    /*
07906     * The size of integer values must be fixed in case the frame is
07907     * shipped to another machine.
07908     */
07909 
07910    if (!update || update->name) {
07911       res = party_name_build_data(data + pos, datalen - pos, &id->name, label,
07912          &ies->name);
07913       if (res < 0) {
07914          return -1;
07915       }
07916       pos += res;
07917    }
07918 
07919    if (!update || update->number) {
07920       res = party_number_build_data(data + pos, datalen - pos, &id->number, label,
07921          &ies->number);
07922       if (res < 0) {
07923          return -1;
07924       }
07925       pos += res;
07926    }
07927 
07928    if (!update || update->subaddress) {
07929       res = party_subaddress_build_data(data + pos, datalen - pos, &id->subaddress,
07930          label, &ies->subaddress);
07931       if (res < 0) {
07932          return -1;
07933       }
07934       pos += res;
07935    }
07936 
07937    /* *************** Party id user tag **************************** */
07938    if (id->tag) {
07939       length = strlen(id->tag);
07940       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
07941          ast_log(LOG_WARNING, "No space left for %s tag\n", label);
07942          return -1;
07943       }
07944       data[pos++] = ies->tag;
07945       data[pos++] = length;
07946       memcpy(data + pos, id->tag, length);
07947       pos += length;
07948    }
07949 
07950    /* *************** Party id combined presentation *************** */
07951    if (!update || update->number) {
07952       int presentation;
07953 
07954       if (!update || update->name) {
07955          presentation = ast_party_id_presentation(id);
07956       } else {
07957          /*
07958           * We must compromise because not all the information is available
07959           * to determine a combined presentation value.
07960           * We will only send the number presentation instead.
07961           */
07962          presentation = id->number.presentation;
07963       }
07964 
07965       if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
07966          ast_log(LOG_WARNING, "No space left for %s combined presentation\n", label);
07967          return -1;
07968       }
07969       data[pos++] = ies->combined_presentation;
07970       data[pos++] = 1;
07971       data[pos++] = presentation;
07972    }
07973 
07974    return pos;
07975 }
07976 
07977 /*!
07978  * \brief Element identifiers for connected line indication frame data
07979  * \note Only add to the end of this enum.
07980  */
07981 enum {
07982    AST_CONNECTED_LINE_NUMBER,
07983    AST_CONNECTED_LINE_NAME,
07984    AST_CONNECTED_LINE_NUMBER_PLAN,
07985    AST_CONNECTED_LINE_ID_PRESENTATION,/* Combined number and name presentation. */
07986    AST_CONNECTED_LINE_SOURCE,
07987    AST_CONNECTED_LINE_SUBADDRESS,
07988    AST_CONNECTED_LINE_SUBADDRESS_TYPE,
07989    AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
07990    AST_CONNECTED_LINE_SUBADDRESS_VALID,
07991    AST_CONNECTED_LINE_TAG,
07992    AST_CONNECTED_LINE_VERSION,
07993    AST_CONNECTED_LINE_NAME_VALID,
07994    AST_CONNECTED_LINE_NAME_CHAR_SET,
07995    AST_CONNECTED_LINE_NAME_PRESENTATION,
07996    AST_CONNECTED_LINE_NUMBER_VALID,
07997    AST_CONNECTED_LINE_NUMBER_PRESENTATION,
07998 };
07999 
08000 int ast_connected_line_build_data(unsigned char *data, size_t datalen, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
08001 {
08002    int32_t value;
08003    size_t pos = 0;
08004    int res;
08005 
08006    static const struct ast_party_id_ies ies = {
08007       .name.str = AST_CONNECTED_LINE_NAME,
08008       .name.char_set = AST_CONNECTED_LINE_NAME_CHAR_SET,
08009       .name.presentation = AST_CONNECTED_LINE_NAME_PRESENTATION,
08010       .name.valid = AST_CONNECTED_LINE_NAME_VALID,
08011 
08012       .number.str = AST_CONNECTED_LINE_NUMBER,
08013       .number.plan = AST_CONNECTED_LINE_NUMBER_PLAN,
08014       .number.presentation = AST_CONNECTED_LINE_NUMBER_PRESENTATION,
08015       .number.valid = AST_CONNECTED_LINE_NUMBER_VALID,
08016 
08017       .subaddress.str = AST_CONNECTED_LINE_SUBADDRESS,
08018       .subaddress.type = AST_CONNECTED_LINE_SUBADDRESS_TYPE,
08019       .subaddress.odd_even_indicator = AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
08020       .subaddress.valid = AST_CONNECTED_LINE_SUBADDRESS_VALID,
08021 
08022       .tag = AST_CONNECTED_LINE_TAG,
08023       .combined_presentation = AST_CONNECTED_LINE_ID_PRESENTATION,
08024    };
08025 
08026    /*
08027     * The size of integer values must be fixed in case the frame is
08028     * shipped to another machine.
08029     */
08030 
08031    /* Connected line frame version */
08032    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08033       ast_log(LOG_WARNING, "No space left for connected line frame version\n");
08034       return -1;
08035    }
08036    data[pos++] = AST_CONNECTED_LINE_VERSION;
08037    data[pos++] = 1;
08038    data[pos++] = 2;/* Version 1 did not have a version ie */
08039 
08040    res = party_id_build_data(data + pos, datalen - pos, &connected->id,
08041       "connected line", &ies, update ? &update->id : NULL);
08042    if (res < 0) {
08043       return -1;
08044    }
08045    pos += res;
08046 
08047    /* Connected line source */
08048    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08049       ast_log(LOG_WARNING, "No space left for connected line source\n");
08050       return -1;
08051    }
08052    data[pos++] = AST_CONNECTED_LINE_SOURCE;
08053    data[pos++] = sizeof(value);
08054    value = htonl(connected->source);
08055    memcpy(data + pos, &value, sizeof(value));
08056    pos += sizeof(value);
08057 
08058    return pos;
08059 }
08060 
08061 int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
08062 {
08063    size_t pos;
08064    unsigned char ie_len;
08065    unsigned char ie_id;
08066    int32_t value;
08067    int frame_version = 1;
08068    int combined_presentation = 0;
08069    int got_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08070 
08071    for (pos = 0; pos < datalen; pos += ie_len) {
08072       if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
08073          ast_log(LOG_WARNING, "Invalid connected line update\n");
08074          return -1;
08075       }
08076       ie_id = data[pos++];
08077       ie_len = data[pos++];
08078       if (datalen < pos + ie_len) {
08079          ast_log(LOG_WARNING, "Invalid connected line update\n");
08080          return -1;
08081       }
08082 
08083       switch (ie_id) {
08084 /* Connected line party frame version */
08085       case AST_CONNECTED_LINE_VERSION:
08086          if (ie_len != 1) {
08087             ast_log(LOG_WARNING, "Invalid connected line frame version (%u)\n",
08088                (unsigned) ie_len);
08089             break;
08090          }
08091          frame_version = data[pos];
08092          break;
08093 /* Connected line party id name */
08094       case AST_CONNECTED_LINE_NAME:
08095          ast_free(connected->id.name.str);
08096          connected->id.name.str = ast_malloc(ie_len + 1);
08097          if (connected->id.name.str) {
08098             memcpy(connected->id.name.str, data + pos, ie_len);
08099             connected->id.name.str[ie_len] = 0;
08100          }
08101          break;
08102       case AST_CONNECTED_LINE_NAME_CHAR_SET:
08103          if (ie_len != 1) {
08104             ast_log(LOG_WARNING, "Invalid connected line name char set (%u)\n",
08105                (unsigned) ie_len);
08106             break;
08107          }
08108          connected->id.name.char_set = data[pos];
08109          break;
08110       case AST_CONNECTED_LINE_NAME_PRESENTATION:
08111          if (ie_len != 1) {
08112             ast_log(LOG_WARNING, "Invalid connected line name presentation (%u)\n",
08113                (unsigned) ie_len);
08114             break;
08115          }
08116          connected->id.name.presentation = data[pos];
08117          break;
08118       case AST_CONNECTED_LINE_NAME_VALID:
08119          if (ie_len != 1) {
08120             ast_log(LOG_WARNING, "Invalid connected line name valid (%u)\n",
08121                (unsigned) ie_len);
08122             break;
08123          }
08124          connected->id.name.valid = data[pos];
08125          break;
08126 /* Connected line party id number */
08127       case AST_CONNECTED_LINE_NUMBER:
08128          ast_free(connected->id.number.str);
08129          connected->id.number.str = ast_malloc(ie_len + 1);
08130          if (connected->id.number.str) {
08131             memcpy(connected->id.number.str, data + pos, ie_len);
08132             connected->id.number.str[ie_len] = 0;
08133          }
08134          break;
08135       case AST_CONNECTED_LINE_NUMBER_PLAN:
08136          if (ie_len != 1) {
08137             ast_log(LOG_WARNING, "Invalid connected line numbering plan (%u)\n",
08138                (unsigned) ie_len);
08139             break;
08140          }
08141          connected->id.number.plan = data[pos];
08142          break;
08143       case AST_CONNECTED_LINE_NUMBER_PRESENTATION:
08144          if (ie_len != 1) {
08145             ast_log(LOG_WARNING, "Invalid connected line number presentation (%u)\n",
08146                (unsigned) ie_len);
08147             break;
08148          }
08149          connected->id.number.presentation = data[pos];
08150          break;
08151       case AST_CONNECTED_LINE_NUMBER_VALID:
08152          if (ie_len != 1) {
08153             ast_log(LOG_WARNING, "Invalid connected line number valid (%u)\n",
08154                (unsigned) ie_len);
08155             break;
08156          }
08157          connected->id.number.valid = data[pos];
08158          break;
08159 /* Connected line party id combined presentation */
08160       case AST_CONNECTED_LINE_ID_PRESENTATION:
08161          if (ie_len != 1) {
08162             ast_log(LOG_WARNING, "Invalid connected line combined presentation (%u)\n",
08163                (unsigned) ie_len);
08164             break;
08165          }
08166          combined_presentation = data[pos];
08167          got_combined_presentation = 1;
08168          break;
08169 /* Connected line party id subaddress */
08170       case AST_CONNECTED_LINE_SUBADDRESS:
08171          ast_free(connected->id.subaddress.str);
08172          connected->id.subaddress.str = ast_malloc(ie_len + 1);
08173          if (connected->id.subaddress.str) {
08174             memcpy(connected->id.subaddress.str, data + pos, ie_len);
08175             connected->id.subaddress.str[ie_len] = 0;
08176          }
08177          break;
08178       case AST_CONNECTED_LINE_SUBADDRESS_TYPE:
08179          if (ie_len != 1) {
08180             ast_log(LOG_WARNING, "Invalid connected line type of subaddress (%u)\n",
08181                (unsigned) ie_len);
08182             break;
08183          }
08184          connected->id.subaddress.type = data[pos];
08185          break;
08186       case AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN:
08187          if (ie_len != 1) {
08188             ast_log(LOG_WARNING,
08189                "Invalid connected line subaddress odd-even indicator (%u)\n",
08190                (unsigned) ie_len);
08191             break;
08192          }
08193          connected->id.subaddress.odd_even_indicator = data[pos];
08194          break;
08195       case AST_CONNECTED_LINE_SUBADDRESS_VALID:
08196          if (ie_len != 1) {
08197             ast_log(LOG_WARNING, "Invalid connected line subaddress valid (%u)\n",
08198                (unsigned) ie_len);
08199             break;
08200          }
08201          connected->id.subaddress.valid = data[pos];
08202          break;
08203 /* Connected line party tag */
08204       case AST_CONNECTED_LINE_TAG:
08205          ast_free(connected->id.tag);
08206          connected->id.tag = ast_malloc(ie_len + 1);
08207          if (connected->id.tag) {
08208             memcpy(connected->id.tag, data + pos, ie_len);
08209             connected->id.tag[ie_len] = 0;
08210          }
08211          break;
08212 /* Connected line party source */
08213       case AST_CONNECTED_LINE_SOURCE:
08214          if (ie_len != sizeof(value)) {
08215             ast_log(LOG_WARNING, "Invalid connected line source (%u)\n",
08216                (unsigned) ie_len);
08217             break;
08218          }
08219          memcpy(&value, data + pos, sizeof(value));
08220          connected->source = ntohl(value);
08221          break;
08222 /* Connected line party unknown element */
08223       default:
08224          ast_log(LOG_DEBUG, "Unknown connected line element: %u (%u)\n",
08225             (unsigned) ie_id, (unsigned) ie_len);
08226          break;
08227       }
08228    }
08229 
08230    switch (frame_version) {
08231    case 1:
08232       /*
08233        * The other end is an earlier version that we need to adjust
08234        * for compatibility.
08235        */
08236       connected->id.name.valid = 1;
08237       connected->id.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
08238       connected->id.number.valid = 1;
08239       if (got_combined_presentation) {
08240          connected->id.name.presentation = combined_presentation;
08241          connected->id.number.presentation = combined_presentation;
08242       }
08243       break;
08244    case 2:
08245       /* The other end is at the same level as we are. */
08246       break;
08247    default:
08248       /*
08249        * The other end is newer than we are.
08250        * We need to assume that they are compatible with us.
08251        */
08252       ast_log(LOG_DEBUG, "Connected line frame has newer version: %u\n",
08253          (unsigned) frame_version);
08254       break;
08255    }
08256 
08257    return 0;
08258 }
08259 
08260 void ast_channel_update_connected_line(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
08261 {
08262    unsigned char data[1024];  /* This should be large enough */
08263    size_t datalen;
08264 
08265    datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
08266    if (datalen == (size_t) -1) {
08267       return;
08268    }
08269 
08270    ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
08271 }
08272 
08273 void ast_channel_queue_connected_line_update(struct ast_channel *chan, const struct ast_party_connected_line *connected, const struct ast_set_party_connected_line *update)
08274 {
08275    unsigned char data[1024];  /* This should be large enough */
08276    size_t datalen;
08277 
08278    datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
08279    if (datalen == (size_t) -1) {
08280       return;
08281    }
08282 
08283    ast_queue_control_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
08284 }
08285 
08286 void ast_channel_set_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08287 {
08288    if (&chan->redirecting == redirecting) {
08289       /* Don't set to self */
08290       return;
08291    }
08292 
08293    ast_channel_lock(chan);
08294    ast_party_redirecting_set(&chan->redirecting, redirecting, update);
08295    ast_channel_unlock(chan);
08296 }
08297 
08298 /*!
08299  * \brief Element identifiers for redirecting indication frame data
08300  * \note Only add to the end of this enum.
08301  */
08302 enum {
08303    AST_REDIRECTING_FROM_NUMBER,
08304    AST_REDIRECTING_FROM_NAME,
08305    AST_REDIRECTING_FROM_NUMBER_PLAN,
08306    AST_REDIRECTING_FROM_ID_PRESENTATION,
08307    AST_REDIRECTING_TO_NUMBER,
08308    AST_REDIRECTING_TO_NAME,
08309    AST_REDIRECTING_TO_NUMBER_PLAN,
08310    AST_REDIRECTING_TO_ID_PRESENTATION,
08311    AST_REDIRECTING_REASON,
08312    AST_REDIRECTING_COUNT,
08313    AST_REDIRECTING_FROM_SUBADDRESS,
08314    AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
08315    AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
08316    AST_REDIRECTING_FROM_SUBADDRESS_VALID,
08317    AST_REDIRECTING_TO_SUBADDRESS,
08318    AST_REDIRECTING_TO_SUBADDRESS_TYPE,
08319    AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
08320    AST_REDIRECTING_TO_SUBADDRESS_VALID,
08321    AST_REDIRECTING_FROM_TAG,
08322    AST_REDIRECTING_TO_TAG,
08323    AST_REDIRECTING_VERSION,
08324    AST_REDIRECTING_FROM_NAME_VALID,
08325    AST_REDIRECTING_FROM_NAME_CHAR_SET,
08326    AST_REDIRECTING_FROM_NAME_PRESENTATION,
08327    AST_REDIRECTING_FROM_NUMBER_VALID,
08328    AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
08329    AST_REDIRECTING_TO_NAME_VALID,
08330    AST_REDIRECTING_TO_NAME_CHAR_SET,
08331    AST_REDIRECTING_TO_NAME_PRESENTATION,
08332    AST_REDIRECTING_TO_NUMBER_VALID,
08333    AST_REDIRECTING_TO_NUMBER_PRESENTATION,
08334 };
08335 
08336 int ast_redirecting_build_data(unsigned char *data, size_t datalen, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08337 {
08338    int32_t value;
08339    size_t pos = 0;
08340    int res;
08341 
08342    static const struct ast_party_id_ies from_ies = {
08343       .name.str = AST_REDIRECTING_FROM_NAME,
08344       .name.char_set = AST_REDIRECTING_FROM_NAME_CHAR_SET,
08345       .name.presentation = AST_REDIRECTING_FROM_NAME_PRESENTATION,
08346       .name.valid = AST_REDIRECTING_FROM_NAME_VALID,
08347 
08348       .number.str = AST_REDIRECTING_FROM_NUMBER,
08349       .number.plan = AST_REDIRECTING_FROM_NUMBER_PLAN,
08350       .number.presentation = AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
08351       .number.valid = AST_REDIRECTING_FROM_NUMBER_VALID,
08352 
08353       .subaddress.str = AST_REDIRECTING_FROM_SUBADDRESS,
08354       .subaddress.type = AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
08355       .subaddress.odd_even_indicator = AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
08356       .subaddress.valid = AST_REDIRECTING_FROM_SUBADDRESS_VALID,
08357 
08358       .tag = AST_REDIRECTING_FROM_TAG,
08359       .combined_presentation = AST_REDIRECTING_FROM_ID_PRESENTATION,
08360    };
08361    static const struct ast_party_id_ies to_ies = {
08362       .name.str = AST_REDIRECTING_TO_NAME,
08363       .name.char_set = AST_REDIRECTING_TO_NAME_CHAR_SET,
08364       .name.presentation = AST_REDIRECTING_TO_NAME_PRESENTATION,
08365       .name.valid = AST_REDIRECTING_TO_NAME_VALID,
08366 
08367       .number.str = AST_REDIRECTING_TO_NUMBER,
08368       .number.plan = AST_REDIRECTING_TO_NUMBER_PLAN,
08369       .number.presentation = AST_REDIRECTING_TO_NUMBER_PRESENTATION,
08370       .number.valid = AST_REDIRECTING_TO_NUMBER_VALID,
08371 
08372       .subaddress.str = AST_REDIRECTING_TO_SUBADDRESS,
08373       .subaddress.type = AST_REDIRECTING_TO_SUBADDRESS_TYPE,
08374       .subaddress.odd_even_indicator = AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
08375       .subaddress.valid = AST_REDIRECTING_TO_SUBADDRESS_VALID,
08376 
08377       .tag = AST_REDIRECTING_TO_TAG,
08378       .combined_presentation = AST_REDIRECTING_TO_ID_PRESENTATION,
08379    };
08380 
08381    /* Redirecting frame version */
08382    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08383       ast_log(LOG_WARNING, "No space left for redirecting frame version\n");
08384       return -1;
08385    }
08386    data[pos++] = AST_REDIRECTING_VERSION;
08387    data[pos++] = 1;
08388    data[pos++] = 2;/* Version 1 did not have a version ie */
08389 
08390    res = party_id_build_data(data + pos, datalen - pos, &redirecting->from,
08391       "redirecting-from", &from_ies, update ? &update->from : NULL);
08392    if (res < 0) {
08393       return -1;
08394    }
08395    pos += res;
08396 
08397    res = party_id_build_data(data + pos, datalen - pos, &redirecting->to,
08398       "redirecting-to", &to_ies, update ? &update->to : NULL);
08399    if (res < 0) {
08400       return -1;
08401    }
08402    pos += res;
08403 
08404    /* Redirecting reason */
08405    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08406       ast_log(LOG_WARNING, "No space left for redirecting reason\n");
08407       return -1;
08408    }
08409    data[pos++] = AST_REDIRECTING_REASON;
08410    data[pos++] = sizeof(value);
08411    value = htonl(redirecting->reason);
08412    memcpy(data + pos, &value, sizeof(value));
08413    pos += sizeof(value);
08414 
08415    /* Redirecting count */
08416    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08417       ast_log(LOG_WARNING, "No space left for redirecting count\n");
08418       return -1;
08419    }
08420    data[pos++] = AST_REDIRECTING_COUNT;
08421    data[pos++] = sizeof(value);
08422    value = htonl(redirecting->count);
08423    memcpy(data + pos, &value, sizeof(value));
08424    pos += sizeof(value);
08425 
08426    return pos;
08427 }
08428 
08429 int ast_redirecting_parse_data(const unsigned char *data, size_t datalen, struct ast_party_redirecting *redirecting)
08430 {
08431    size_t pos;
08432    unsigned char ie_len;
08433    unsigned char ie_id;
08434    int32_t value;
08435    int frame_version = 1;
08436    int from_combined_presentation = 0;
08437    int got_from_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08438    int to_combined_presentation = 0;
08439    int got_to_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08440 
08441    for (pos = 0; pos < datalen; pos += ie_len) {
08442       if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
08443          ast_log(LOG_WARNING, "Invalid redirecting update\n");
08444          return -1;
08445       }
08446       ie_id = data[pos++];
08447       ie_len = data[pos++];
08448       if (datalen < pos + ie_len) {
08449          ast_log(LOG_WARNING, "Invalid redirecting update\n");
08450          return -1;
08451       }
08452 
08453       switch (ie_id) {
08454 /* Redirecting frame version */
08455       case AST_REDIRECTING_VERSION:
08456          if (ie_len != 1) {
08457             ast_log(LOG_WARNING, "Invalid redirecting frame version (%u)\n",
08458                (unsigned) ie_len);
08459             break;
08460          }
08461          frame_version = data[pos];
08462          break;
08463 /* Redirecting-from party id name */
08464       case AST_REDIRECTING_FROM_NAME:
08465          ast_free(redirecting->from.name.str);
08466          redirecting->from.name.str = ast_malloc(ie_len + 1);
08467          if (redirecting->from.name.str) {
08468             memcpy(redirecting->from.name.str, data + pos, ie_len);
08469             redirecting->from.name.str[ie_len] = 0;
08470          }
08471          break;
08472       case AST_REDIRECTING_FROM_NAME_CHAR_SET:
08473          if (ie_len != 1) {
08474             ast_log(LOG_WARNING, "Invalid redirecting-from name char set (%u)\n",
08475                (unsigned) ie_len);
08476             break;
08477          }
08478          redirecting->from.name.char_set = data[pos];
08479          break;
08480       case AST_REDIRECTING_FROM_NAME_PRESENTATION:
08481          if (ie_len != 1) {
08482             ast_log(LOG_WARNING, "Invalid redirecting-from name presentation (%u)\n",
08483                (unsigned) ie_len);
08484             break;
08485          }
08486          redirecting->from.name.presentation = data[pos];
08487          break;
08488       case AST_REDIRECTING_FROM_NAME_VALID:
08489          if (ie_len != 1) {
08490             ast_log(LOG_WARNING, "Invalid redirecting-from name valid (%u)\n",
08491                (unsigned) ie_len);
08492             break;
08493          }
08494          redirecting->from.name.valid = data[pos];
08495          break;
08496 /* Redirecting-from party id number */
08497       case AST_REDIRECTING_FROM_NUMBER:
08498          ast_free(redirecting->from.number.str);
08499          redirecting->from.number.str = ast_malloc(ie_len + 1);
08500          if (redirecting->from.number.str) {
08501             memcpy(redirecting->from.number.str, data + pos, ie_len);
08502             redirecting->from.number.str[ie_len] = 0;
08503          }
08504          break;
08505       case AST_REDIRECTING_FROM_NUMBER_PLAN:
08506          if (ie_len != 1) {
08507             ast_log(LOG_WARNING, "Invalid redirecting-from numbering plan (%u)\n",
08508                (unsigned) ie_len);
08509             break;
08510          }
08511          redirecting->from.number.plan = data[pos];
08512          break;
08513       case AST_REDIRECTING_FROM_NUMBER_PRESENTATION:
08514          if (ie_len != 1) {
08515             ast_log(LOG_WARNING, "Invalid redirecting-from number presentation (%u)\n",
08516                (unsigned) ie_len);
08517             break;
08518          }
08519          redirecting->from.number.presentation = data[pos];
08520          break;
08521       case AST_REDIRECTING_FROM_NUMBER_VALID:
08522          if (ie_len != 1) {
08523             ast_log(LOG_WARNING, "Invalid redirecting-from number valid (%u)\n",
08524                (unsigned) ie_len);
08525             break;
08526          }
08527          redirecting->from.number.valid = data[pos];
08528          break;
08529 /* Redirecting-from party id combined presentation */
08530       case AST_REDIRECTING_FROM_ID_PRESENTATION:
08531          if (ie_len != 1) {
08532             ast_log(LOG_WARNING, "Invalid redirecting-from combined presentation (%u)\n",
08533                (unsigned) ie_len);
08534             break;
08535          }
08536          from_combined_presentation = data[pos];
08537          got_from_combined_presentation = 1;
08538          break;
08539 /* Redirecting-from party id subaddress */
08540       case AST_REDIRECTING_FROM_SUBADDRESS:
08541          ast_free(redirecting->from.subaddress.str);
08542          redirecting->from.subaddress.str = ast_malloc(ie_len + 1);
08543          if (redirecting->from.subaddress.str) {
08544             memcpy(redirecting->from.subaddress.str, data + pos, ie_len);
08545             redirecting->from.subaddress.str[ie_len] = 0;
08546          }
08547          break;
08548       case AST_REDIRECTING_FROM_SUBADDRESS_TYPE:
08549          if (ie_len != 1) {
08550             ast_log(LOG_WARNING, "Invalid redirecting-from type of subaddress (%u)\n",
08551                (unsigned) ie_len);
08552             break;
08553          }
08554          redirecting->from.subaddress.type = data[pos];
08555          break;
08556       case AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN:
08557          if (ie_len != 1) {
08558             ast_log(LOG_WARNING,
08559                "Invalid redirecting-from subaddress odd-even indicator (%u)\n",
08560                (unsigned) ie_len);
08561             break;
08562          }
08563          redirecting->from.subaddress.odd_even_indicator = data[pos];
08564          break;
08565       case AST_REDIRECTING_FROM_SUBADDRESS_VALID:
08566          if (ie_len != 1) {
08567             ast_log(LOG_WARNING, "Invalid redirecting-from subaddress valid (%u)\n",
08568                (unsigned) ie_len);
08569             break;
08570          }
08571          redirecting->from.subaddress.valid = data[pos];
08572          break;
08573 /* Redirecting-from party id tag */
08574       case AST_REDIRECTING_FROM_TAG:
08575          ast_free(redirecting->from.tag);
08576          redirecting->from.tag = ast_malloc(ie_len + 1);
08577          if (redirecting->from.tag) {
08578             memcpy(redirecting->from.tag, data + pos, ie_len);
08579             redirecting->from.tag[ie_len] = 0;
08580          }
08581          break;
08582 /* Redirecting-to party id name */
08583       case AST_REDIRECTING_TO_NAME:
08584          ast_free(redirecting->to.name.str);
08585          redirecting->to.name.str = ast_malloc(ie_len + 1);
08586          if (redirecting->to.name.str) {
08587             memcpy(redirecting->to.name.str, data + pos, ie_len);
08588             redirecting->to.name.str[ie_len] = 0;
08589          }
08590          break;
08591       case AST_REDIRECTING_TO_NAME_CHAR_SET:
08592          if (ie_len != 1) {
08593             ast_log(LOG_WARNING, "Invalid redirecting-to name char set (%u)\n",
08594                (unsigned) ie_len);
08595             break;
08596          }
08597          redirecting->to.name.char_set = data[pos];
08598          break;
08599       case AST_REDIRECTING_TO_NAME_PRESENTATION:
08600          if (ie_len != 1) {
08601             ast_log(LOG_WARNING, "Invalid redirecting-to name presentation (%u)\n",
08602                (unsigned) ie_len);
08603             break;
08604          }
08605          redirecting->to.name.presentation = data[pos];
08606          break;
08607       case AST_REDIRECTING_TO_NAME_VALID:
08608          if (ie_len != 1) {
08609             ast_log(LOG_WARNING, "Invalid redirecting-to name valid (%u)\n",
08610                (unsigned) ie_len);
08611             break;
08612          }
08613          redirecting->to.name.valid = data[pos];
08614          break;
08615 /* Redirecting-to party id number */
08616       case AST_REDIRECTING_TO_NUMBER:
08617          ast_free(redirecting->to.number.str);
08618          redirecting->to.number.str = ast_malloc(ie_len + 1);
08619          if (redirecting->to.number.str) {
08620             memcpy(redirecting->to.number.str, data + pos, ie_len);
08621             redirecting->to.number.str[ie_len] = 0;
08622          }
08623          break;
08624       case AST_REDIRECTING_TO_NUMBER_PLAN:
08625          if (ie_len != 1) {
08626             ast_log(LOG_WARNING, "Invalid redirecting-to numbering plan (%u)\n",
08627                (unsigned) ie_len);
08628             break;
08629          }
08630          redirecting->to.number.plan = data[pos];
08631          break;
08632       case AST_REDIRECTING_TO_NUMBER_PRESENTATION:
08633          if (ie_len != 1) {
08634             ast_log(LOG_WARNING, "Invalid redirecting-to number presentation (%u)\n",
08635                (unsigned) ie_len);
08636             break;
08637          }
08638          redirecting->to.number.presentation = data[pos];
08639          break;
08640       case AST_REDIRECTING_TO_NUMBER_VALID:
08641          if (ie_len != 1) {
08642             ast_log(LOG_WARNING, "Invalid redirecting-to number valid (%u)\n",
08643                (unsigned) ie_len);
08644             break;
08645          }
08646          redirecting->to.number.valid = data[pos];
08647          break;
08648 /* Redirecting-to party id combined presentation */
08649       case AST_REDIRECTING_TO_ID_PRESENTATION:
08650          if (ie_len != 1) {
08651             ast_log(LOG_WARNING, "Invalid redirecting-to combined presentation (%u)\n",
08652                (unsigned) ie_len);
08653             break;
08654          }
08655          to_combined_presentation = data[pos];
08656          got_to_combined_presentation = 1;
08657          break;
08658 /* Redirecting-to party id subaddress */
08659       case AST_REDIRECTING_TO_SUBADDRESS:
08660          ast_free(redirecting->to.subaddress.str);
08661          redirecting->to.subaddress.str = ast_malloc(ie_len + 1);
08662          if (redirecting->to.subaddress.str) {
08663             memcpy(redirecting->to.subaddress.str, data + pos, ie_len);
08664             redirecting->to.subaddress.str[ie_len] = 0;
08665          }
08666          break;
08667       case AST_REDIRECTING_TO_SUBADDRESS_TYPE:
08668          if (ie_len != 1) {
08669             ast_log(LOG_WARNING, "Invalid redirecting-to type of subaddress (%u)\n",
08670                (unsigned) ie_len);
08671             break;
08672          }
08673          redirecting->to.subaddress.type = data[pos];
08674          break;
08675       case AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN:
08676          if (ie_len != 1) {
08677             ast_log(LOG_WARNING,
08678                "Invalid redirecting-to subaddress odd-even indicator (%u)\n",
08679                (unsigned) ie_len);
08680             break;
08681          }
08682          redirecting->to.subaddress.odd_even_indicator = data[pos];
08683          break;
08684       case AST_REDIRECTING_TO_SUBADDRESS_VALID:
08685          if (ie_len != 1) {
08686             ast_log(LOG_WARNING, "Invalid redirecting-to subaddress valid (%u)\n",
08687                (unsigned) ie_len);
08688             break;
08689          }
08690          redirecting->to.subaddress.valid = data[pos];
08691          break;
08692 /* Redirecting-to party id tag */
08693       case AST_REDIRECTING_TO_TAG:
08694          ast_free(redirecting->to.tag);
08695          redirecting->to.tag = ast_malloc(ie_len + 1);
08696          if (redirecting->to.tag) {
08697             memcpy(redirecting->to.tag, data + pos, ie_len);
08698             redirecting->to.tag[ie_len] = 0;
08699          }
08700          break;
08701 /* Redirecting reason */
08702       case AST_REDIRECTING_REASON:
08703          if (ie_len != sizeof(value)) {
08704             ast_log(LOG_WARNING, "Invalid redirecting reason (%u)\n",
08705                (unsigned) ie_len);
08706             break;
08707          }
08708          memcpy(&value, data + pos, sizeof(value));
08709          redirecting->reason = ntohl(value);
08710          break;
08711 /* Redirecting count */
08712       case AST_REDIRECTING_COUNT:
08713          if (ie_len != sizeof(value)) {
08714             ast_log(LOG_WARNING, "Invalid redirecting count (%u)\n",
08715                (unsigned) ie_len);
08716             break;
08717          }
08718          memcpy(&value, data + pos, sizeof(value));
08719          redirecting->count = ntohl(value);
08720          break;
08721 /* Redirecting unknown element */
08722       default:
08723          ast_log(LOG_DEBUG, "Unknown redirecting element: %u (%u)\n",
08724             (unsigned) ie_id, (unsigned) ie_len);
08725          break;
08726       }
08727    }
08728 
08729    switch (frame_version) {
08730    case 1:
08731       /*
08732        * The other end is an earlier version that we need to adjust
08733        * for compatibility.
08734        */
08735       redirecting->from.name.valid = 1;
08736       redirecting->from.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
08737       redirecting->from.number.valid = 1;
08738       if (got_from_combined_presentation) {
08739          redirecting->from.name.presentation = from_combined_presentation;
08740          redirecting->from.number.presentation = from_combined_presentation;
08741       }
08742 
08743       redirecting->to.name.valid = 1;
08744       redirecting->to.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
08745       redirecting->to.number.valid = 1;
08746       if (got_to_combined_presentation) {
08747          redirecting->to.name.presentation = to_combined_presentation;
08748          redirecting->to.number.presentation = to_combined_presentation;
08749       }
08750       break;
08751    case 2:
08752       /* The other end is at the same level as we are. */
08753       break;
08754    default:
08755       /*
08756        * The other end is newer than we are.
08757        * We need to assume that they are compatible with us.
08758        */
08759       ast_log(LOG_DEBUG, "Redirecting frame has newer version: %u\n",
08760          (unsigned) frame_version);
08761       break;
08762    }
08763 
08764    return 0;
08765 }
08766 
08767 void ast_channel_update_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08768 {
08769    unsigned char data[1024];  /* This should be large enough */
08770    size_t datalen;
08771 
08772    datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
08773    if (datalen == (size_t) -1) {
08774       return;
08775    }
08776 
08777    ast_indicate_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
08778 }
08779 
08780 void ast_channel_queue_redirecting_update(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08781 {
08782    unsigned char data[1024];  /* This should be large enough */
08783    size_t datalen;
08784 
08785    datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
08786    if (datalen == (size_t) -1) {
08787       return;
08788    }
08789 
08790    ast_queue_control_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
08791 }
08792 
08793 int ast_channel_connected_line_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const void *connected_info, int is_caller, int is_frame)
08794 {
08795    const char *macro;
08796    const char *macro_args;
08797    int retval;
08798 
08799    ast_channel_lock(macro_chan);
08800    macro = pbx_builtin_getvar_helper(macro_chan, is_caller
08801       ? "CONNECTED_LINE_CALLER_SEND_MACRO" : "CONNECTED_LINE_CALLEE_SEND_MACRO");
08802    macro = ast_strdupa(S_OR(macro, ""));
08803    macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
08804       ? "CONNECTED_LINE_CALLER_SEND_MACRO_ARGS" : "CONNECTED_LINE_CALLEE_SEND_MACRO_ARGS");
08805    macro_args = ast_strdupa(S_OR(macro_args, ""));
08806 
08807    if (ast_strlen_zero(macro)) {
08808       ast_channel_unlock(macro_chan);
08809       return -1;
08810    }
08811 
08812    if (is_frame) {
08813       const struct ast_frame *frame = connected_info;
08814 
08815       ast_connected_line_parse_data(frame->data.ptr, frame->datalen, &macro_chan->connected);
08816    } else {
08817       const struct ast_party_connected_line *connected = connected_info;
08818 
08819       ast_party_connected_line_copy(&macro_chan->connected, connected);
08820    }
08821    ast_channel_unlock(macro_chan);
08822 
08823    if (!(retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args))) {
08824       ast_channel_lock(macro_chan);
08825       ast_channel_update_connected_line(macro_chan, &macro_chan->connected, NULL);
08826       ast_channel_unlock(macro_chan);
08827    }
08828 
08829    return retval;
08830 }
08831 
08832 int ast_channel_redirecting_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const void *redirecting_info, int is_caller, int is_frame)
08833 {
08834    const char *macro;
08835    const char *macro_args;
08836    int retval;
08837 
08838    ast_channel_lock(macro_chan);
08839    macro = pbx_builtin_getvar_helper(macro_chan, is_caller
08840       ? "REDIRECTING_CALLER_SEND_MACRO" : "REDIRECTING_CALLEE_SEND_MACRO");
08841    macro = ast_strdupa(S_OR(macro, ""));
08842    macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
08843       ? "REDIRECTING_CALLER_SEND_MACRO_ARGS" : "REDIRECTING_CALLEE_SEND_MACRO_ARGS");
08844    macro_args = ast_strdupa(S_OR(macro_args, ""));
08845 
08846    if (ast_strlen_zero(macro)) {
08847       ast_channel_unlock(macro_chan);
08848       return -1;
08849    }
08850 
08851    if (is_frame) {
08852       const struct ast_frame *frame = redirecting_info;
08853 
08854       ast_redirecting_parse_data(frame->data.ptr, frame->datalen, &macro_chan->redirecting);
08855    } else {
08856       const struct ast_party_redirecting *redirecting = redirecting_info;
08857 
08858       ast_party_redirecting_copy(&macro_chan->redirecting, redirecting);
08859    }
08860    ast_channel_unlock(macro_chan);
08861 
08862    retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args);
08863    if (!retval) {
08864       ast_channel_lock(macro_chan);
08865       ast_channel_update_redirecting(macro_chan, &macro_chan->redirecting, NULL);
08866       ast_channel_unlock(macro_chan);
08867    }
08868 
08869    return retval;
08870 }
08871 
08872 static void *channel_cc_params_copy(void *data)
08873 {
08874    const struct ast_cc_config_params *src = data;
08875    struct ast_cc_config_params *dest = ast_cc_config_params_init();
08876    if (!dest) {
08877       return NULL;
08878    }
08879    ast_cc_copy_config_params(dest, src);
08880    return dest;
08881 }
08882 
08883 static void channel_cc_params_destroy(void *data)
08884 {
08885    struct ast_cc_config_params *cc_params = data;
08886    ast_cc_config_params_destroy(cc_params);
08887 }
08888 
08889 static const struct ast_datastore_info cc_channel_datastore_info = {
08890    .type = "Call Completion",
08891    .duplicate = channel_cc_params_copy,
08892    .destroy = channel_cc_params_destroy,
08893 };
08894 
08895 int ast_channel_cc_params_init(struct ast_channel *chan,
08896       const struct ast_cc_config_params *base_params)
08897 {
08898    struct ast_cc_config_params *cc_params;
08899    struct ast_datastore *cc_datastore;
08900 
08901    if (!(cc_params = ast_cc_config_params_init())) {
08902       return -1;
08903    }
08904 
08905    if (!(cc_datastore = ast_datastore_alloc(&cc_channel_datastore_info, NULL))) {
08906       ast_cc_config_params_destroy(cc_params);
08907       return -1;
08908    }
08909 
08910    if (base_params) {
08911       ast_cc_copy_config_params(cc_params, base_params);
08912    }
08913    cc_datastore->data = cc_params;
08914    ast_channel_datastore_add(chan, cc_datastore);
08915    return 0;
08916 }
08917 
08918 struct ast_cc_config_params *ast_channel_get_cc_config_params(struct ast_channel *chan)
08919 {
08920    struct ast_datastore *cc_datastore;
08921 
08922    if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
08923       /* If we can't find the datastore, it almost definitely means that the channel type being
08924        * used has not had its driver modified to parse CC config parameters. The best action
08925        * to take here is to create the parameters on the spot with the defaults set.
08926        */
08927       if (ast_channel_cc_params_init(chan, NULL)) {
08928          return NULL;
08929       }
08930       if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
08931          /* Should be impossible */
08932          return NULL;
08933       }
08934    }
08935 
08936    ast_assert(cc_datastore->data != NULL);
08937    return cc_datastore->data;
08938 }
08939 
08940 int ast_channel_get_device_name(struct ast_channel *chan, char *device_name, size_t name_buffer_length)
08941 {
08942    int len = name_buffer_length;
08943    char *dash;
08944    if (!ast_channel_queryoption(chan, AST_OPTION_DEVICE_NAME, device_name, &len, 0)) {
08945       return 0;
08946    }
08947 
08948    /* Dang. Do it the old-fashioned way */
08949    ast_copy_string(device_name, chan->name, name_buffer_length);
08950    if ((dash = strrchr(device_name, '-'))) {
08951       *dash = '\0';
08952    }
08953 
08954    return 0;
08955 }
08956 
08957 int ast_channel_get_cc_agent_type(struct ast_channel *chan, char *agent_type, size_t size)
08958 {
08959    int len = size;
08960    char *slash;
08961 
08962    if (!ast_channel_queryoption(chan, AST_OPTION_CC_AGENT_TYPE, agent_type, &len, 0)) {
08963       return 0;
08964    }
08965 
08966    ast_copy_string(agent_type, chan->name, size);
08967    if ((slash = strchr(agent_type, '/'))) {
08968       *slash = '\0';
08969    }
08970    return 0;
08971 }
08972 
08973 /* DO NOT PUT ADDITIONAL FUNCTIONS BELOW THIS BOUNDARY
08974  *
08975  * ONLY FUNCTIONS FOR PROVIDING BACKWARDS ABI COMPATIBILITY BELONG HERE
08976  *
08977  */
08978 
08979 /* Provide binary compatibility for modules that call ast_channel_alloc() directly;
08980  * newly compiled modules will call __ast_channel_alloc() via the macros in channel.h
08981  */
08982 #undef ast_channel_alloc
08983 struct ast_channel __attribute__((format(printf, 10, 11)))
08984    *ast_channel_alloc(int needqueue, int state, const char *cid_num,
08985             const char *cid_name, const char *acctcode,
08986             const char *exten, const char *context,
08987             const char *linkedid, const int amaflag,
08988             const char *name_fmt, ...);
08989 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num,
08990                   const char *cid_name, const char *acctcode,
08991                   const char *exten, const char *context,
08992                   const char *linkedid, const int amaflag,
08993                   const char *name_fmt, ...)
08994 {
08995    va_list ap1, ap2;
08996    struct ast_channel *result;
08997 
08998 
08999    va_start(ap1, name_fmt);
09000    va_start(ap2, name_fmt);
09001    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
09002                linkedid, amaflag, __FILE__, __LINE__, __FUNCTION__, name_fmt, ap1, ap2);
09003    va_end(ap1);
09004    va_end(ap2);
09005 
09006    return result;
09007 }

Generated on Sat Mar 26 11:07:28 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9