Mon May 14 2012 03:42:35

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