Mon Jun 18 2012 03:55:30

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: 361142 $")
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    if (number_value == AST_PRES_UNAVAILABLE) {
02170       return AST_PRES_NUMBER_NOT_AVAILABLE;
02171    }
02172 
02173    return number_value | number_screening;
02174 }
02175 
02176 void ast_party_dialed_init(struct ast_party_dialed *init)
02177 {
02178    init->number.str = NULL;
02179    init->number.plan = 0;/* Unknown */
02180    ast_party_subaddress_init(&init->subaddress);
02181    init->transit_network_select = 0;
02182 }
02183 
02184 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
02185 {
02186    if (dest == src) {
02187       /* Don't copy to self */
02188       return;
02189    }
02190 
02191    ast_free(dest->number.str);
02192    dest->number.str = ast_strdup(src->number.str);
02193    dest->number.plan = src->number.plan;
02194    ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
02195    dest->transit_network_select = src->transit_network_select;
02196 }
02197 
02198 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
02199 {
02200    init->number.str = NULL;
02201    init->number.plan = guide->number.plan;
02202    ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
02203    init->transit_network_select = guide->transit_network_select;
02204 }
02205 
02206 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
02207 {
02208    if (src->number.str && src->number.str != dest->number.str) {
02209       ast_free(dest->number.str);
02210       dest->number.str = ast_strdup(src->number.str);
02211    }
02212    dest->number.plan = src->number.plan;
02213 
02214    ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
02215 
02216    dest->transit_network_select = src->transit_network_select;
02217 }
02218 
02219 void ast_party_dialed_free(struct ast_party_dialed *doomed)
02220 {
02221    ast_free(doomed->number.str);
02222    doomed->number.str = NULL;
02223    ast_party_subaddress_free(&doomed->subaddress);
02224 }
02225 
02226 void ast_party_caller_init(struct ast_party_caller *init)
02227 {
02228    ast_party_id_init(&init->id);
02229    ast_party_id_init(&init->ani);
02230    init->ani2 = 0;
02231 }
02232 
02233 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
02234 {
02235    if (dest == src) {
02236       /* Don't copy to self */
02237       return;
02238    }
02239 
02240    ast_party_id_copy(&dest->id, &src->id);
02241    ast_party_id_copy(&dest->ani, &src->ani);
02242    dest->ani2 = src->ani2;
02243 }
02244 
02245 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
02246 {
02247    ast_party_id_set_init(&init->id, &guide->id);
02248    ast_party_id_set_init(&init->ani, &guide->ani);
02249    init->ani2 = guide->ani2;
02250 }
02251 
02252 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
02253 {
02254    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
02255    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
02256    dest->ani2 = src->ani2;
02257 }
02258 
02259 void ast_party_caller_free(struct ast_party_caller *doomed)
02260 {
02261    ast_party_id_free(&doomed->id);
02262    ast_party_id_free(&doomed->ani);
02263 }
02264 
02265 void ast_party_connected_line_init(struct ast_party_connected_line *init)
02266 {
02267    ast_party_id_init(&init->id);
02268    ast_party_id_init(&init->ani);
02269    init->ani2 = 0;
02270    init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02271 }
02272 
02273 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
02274 {
02275    if (dest == src) {
02276       /* Don't copy to self */
02277       return;
02278    }
02279 
02280    ast_party_id_copy(&dest->id, &src->id);
02281    ast_party_id_copy(&dest->ani, &src->ani);
02282    dest->ani2 = src->ani2;
02283    dest->source = src->source;
02284 }
02285 
02286 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
02287 {
02288    ast_party_id_set_init(&init->id, &guide->id);
02289    ast_party_id_set_init(&init->ani, &guide->ani);
02290    init->ani2 = guide->ani2;
02291    init->source = guide->source;
02292 }
02293 
02294 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)
02295 {
02296    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
02297    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
02298    dest->ani2 = src->ani2;
02299    dest->source = src->source;
02300 }
02301 
02302 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
02303 {
02304    connected->id = caller->id;
02305    connected->ani = caller->ani;
02306    connected->ani2 = caller->ani2;
02307    connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02308 }
02309 
02310 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
02311 {
02312    ast_party_id_free(&doomed->id);
02313    ast_party_id_free(&doomed->ani);
02314 }
02315 
02316 void ast_party_redirecting_init(struct ast_party_redirecting *init)
02317 {
02318    ast_party_id_init(&init->from);
02319    ast_party_id_init(&init->to);
02320    init->count = 0;
02321    init->reason = AST_REDIRECTING_REASON_UNKNOWN;
02322 }
02323 
02324 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
02325 {
02326    if (dest == src) {
02327       /* Don't copy to self */
02328       return;
02329    }
02330 
02331    ast_party_id_copy(&dest->from, &src->from);
02332    ast_party_id_copy(&dest->to, &src->to);
02333    dest->count = src->count;
02334    dest->reason = src->reason;
02335 }
02336 
02337 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
02338 {
02339    ast_party_id_set_init(&init->from, &guide->from);
02340    ast_party_id_set_init(&init->to, &guide->to);
02341    init->count = guide->count;
02342    init->reason = guide->reason;
02343 }
02344 
02345 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
02346 {
02347    ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
02348    ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
02349    dest->reason = src->reason;
02350    dest->count = src->count;
02351 }
02352 
02353 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
02354 {
02355    ast_party_id_free(&doomed->from);
02356    ast_party_id_free(&doomed->to);
02357 }
02358 
02359 /*! \brief Free a channel structure */
02360 static void ast_channel_destructor(void *obj)
02361 {
02362    struct ast_channel *chan = obj;
02363    int fd;
02364 #ifdef HAVE_EPOLL
02365    int i;
02366 #endif
02367    struct ast_var_t *vardata;
02368    struct ast_frame *f;
02369    struct varshead *headp;
02370    struct ast_datastore *datastore;
02371    char device_name[AST_CHANNEL_NAME];
02372 
02373    if (chan->name) {
02374       /* The string fields were initialized. */
02375       ast_cel_report_event(chan, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
02376       ast_cel_check_retire_linkedid(chan);
02377    }
02378 
02379    /* Get rid of each of the data stores on the channel */
02380    ast_channel_lock(chan);
02381    while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
02382       /* Free the data store */
02383       ast_datastore_free(datastore);
02384    ast_channel_unlock(chan);
02385 
02386    /* Lock and unlock the channel just to be sure nobody has it locked still
02387       due to a reference that was stored in a datastore. (i.e. app_chanspy) */
02388    ast_channel_lock(chan);
02389    ast_channel_unlock(chan);
02390 
02391    if (chan->tech_pvt) {
02392       ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
02393       ast_free(chan->tech_pvt);
02394    }
02395 
02396    if (chan->sched)
02397       sched_context_destroy(chan->sched);
02398 
02399    if (chan->name) {
02400       char *dashptr;
02401 
02402       /* The string fields were initialized. */
02403       ast_copy_string(device_name, chan->name, sizeof(device_name));
02404       if ((dashptr = strrchr(device_name, '-'))) {
02405          *dashptr = '\0';
02406       }
02407    } else {
02408       device_name[0] = '\0';
02409    }
02410 
02411    /* Stop monitoring */
02412    if (chan->monitor)
02413       chan->monitor->stop( chan, 0 );
02414 
02415    /* If there is native format music-on-hold state, free it */
02416    if (chan->music_state)
02417       ast_moh_cleanup(chan);
02418 
02419    /* Free translators */
02420    if (chan->readtrans)
02421       ast_translator_free_path(chan->readtrans);
02422    if (chan->writetrans)
02423       ast_translator_free_path(chan->writetrans);
02424    if (chan->pbx)
02425       ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
02426 
02427    ast_party_dialed_free(&chan->dialed);
02428    ast_party_caller_free(&chan->caller);
02429    ast_party_connected_line_free(&chan->connected);
02430    ast_party_redirecting_free(&chan->redirecting);
02431 
02432    /* Close pipes if appropriate */
02433    if ((fd = chan->alertpipe[0]) > -1)
02434       close(fd);
02435    if ((fd = chan->alertpipe[1]) > -1)
02436       close(fd);
02437    if (chan->timer) {
02438       ast_timer_close(chan->timer);
02439    }
02440 #ifdef HAVE_EPOLL
02441    for (i = 0; i < AST_MAX_FDS; i++) {
02442       if (chan->epfd_data[i])
02443          free(chan->epfd_data[i]);
02444    }
02445    close(chan->epfd);
02446 #endif
02447    while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
02448       ast_frfree(f);
02449    
02450    /* loop over the variables list, freeing all data and deleting list items */
02451    /* no need to lock the list, as the channel is already locked */
02452    headp = &chan->varshead;
02453    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02454       ast_var_delete(vardata);
02455 
02456    ast_app_group_discard(chan);
02457 
02458    /* Destroy the jitterbuffer */
02459    ast_jb_destroy(chan);
02460 
02461    if (chan->cdr) {
02462       ast_cdr_discard(chan->cdr);
02463       chan->cdr = NULL;
02464    }
02465 
02466    if (chan->zone) {
02467       chan->zone = ast_tone_zone_unref(chan->zone);
02468    }
02469 
02470    ast_string_field_free_memory(chan);
02471 
02472    if (device_name[0]) {
02473       /*
02474        * We have a device name to notify of a new state.
02475        *
02476        * Queue an unknown state, because, while we know that this particular
02477        * instance is dead, we don't know the state of all other possible
02478        * instances.
02479        */
02480       ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
02481    }
02482 }
02483 
02484 /*! \brief Free a dummy channel structure */
02485 static void ast_dummy_channel_destructor(void *obj)
02486 {
02487    struct ast_channel *chan = obj;
02488    struct ast_var_t *vardata;
02489    struct varshead *headp;
02490 
02491    headp = &chan->varshead;
02492 
02493    ast_party_dialed_free(&chan->dialed);
02494    ast_party_caller_free(&chan->caller);
02495    ast_party_connected_line_free(&chan->connected);
02496    ast_party_redirecting_free(&chan->redirecting);
02497 
02498    /* loop over the variables list, freeing all data and deleting list items */
02499    /* no need to lock the list, as the channel is already locked */
02500    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02501       ast_var_delete(vardata);
02502 
02503    if (chan->cdr) {
02504       ast_cdr_discard(chan->cdr);
02505       chan->cdr = NULL;
02506    }
02507 
02508    ast_string_field_free_memory(chan);
02509 }
02510 
02511 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
02512 {
02513    return ast_datastore_alloc(info, uid);
02514 }
02515 
02516 int ast_channel_datastore_free(struct ast_datastore *datastore)
02517 {
02518    return ast_datastore_free(datastore);
02519 }
02520 
02521 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
02522 {
02523    struct ast_datastore *datastore = NULL, *datastore2;
02524 
02525    AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
02526       if (datastore->inheritance > 0) {
02527          datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
02528          if (datastore2) {
02529             datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
02530             datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
02531             AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
02532          }
02533       }
02534    }
02535    return 0;
02536 }
02537 
02538 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
02539 {
02540    int res = 0;
02541 
02542    AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
02543 
02544    return res;
02545 }
02546 
02547 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
02548 {
02549    return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
02550 }
02551 
02552 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
02553 {
02554    struct ast_datastore *datastore = NULL;
02555    
02556    if (info == NULL)
02557       return NULL;
02558 
02559    AST_LIST_TRAVERSE(&chan->datastores, datastore, entry) {
02560       if (datastore->info != info) {
02561          continue;
02562       }
02563 
02564       if (uid == NULL) {
02565          /* matched by type only */
02566          break;
02567       }
02568 
02569       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
02570          /* Matched by type AND uid */
02571          break;
02572       }
02573    }
02574 
02575    return datastore;
02576 }
02577 
02578 /*! Set the file descriptor on the channel */
02579 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
02580 {
02581 #ifdef HAVE_EPOLL
02582    struct epoll_event ev;
02583    struct ast_epoll_data *aed = NULL;
02584 
02585    if (chan->fds[which] > -1) {
02586       epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
02587       aed = chan->epfd_data[which];
02588    }
02589 
02590    /* If this new fd is valid, add it to the epoll */
02591    if (fd > -1) {
02592       if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
02593          return;
02594       
02595       chan->epfd_data[which] = aed;
02596       aed->chan = chan;
02597       aed->which = which;
02598       
02599       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02600       ev.data.ptr = aed;
02601       epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
02602    } else if (aed) {
02603       /* We don't have to keep around this epoll data structure now */
02604       free(aed);
02605       chan->epfd_data[which] = NULL;
02606    }
02607 #endif
02608    chan->fds[which] = fd;
02609    return;
02610 }
02611 
02612 /*! Add a channel to an optimized waitfor */
02613 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
02614 {
02615 #ifdef HAVE_EPOLL
02616    struct epoll_event ev;
02617    int i = 0;
02618 
02619    if (chan0->epfd == -1)
02620       return;
02621 
02622    /* Iterate through the file descriptors on chan1, adding them to chan0 */
02623    for (i = 0; i < AST_MAX_FDS; i++) {
02624       if (chan1->fds[i] == -1)
02625          continue;
02626       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02627       ev.data.ptr = chan1->epfd_data[i];
02628       epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
02629    }
02630 
02631 #endif
02632    return;
02633 }
02634 
02635 /*! Delete a channel from an optimized waitfor */
02636 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
02637 {
02638 #ifdef HAVE_EPOLL
02639    struct epoll_event ev;
02640    int i = 0;
02641 
02642    if (chan0->epfd == -1)
02643       return;
02644 
02645    for (i = 0; i < AST_MAX_FDS; i++) {
02646       if (chan1->fds[i] == -1)
02647          continue;
02648       epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
02649    }
02650 
02651 #endif
02652    return;
02653 }
02654 
02655 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
02656 {
02657    ast_channel_lock(chan);
02658 
02659    chan->_softhangup &= ~flag;
02660 
02661    if (!chan->_softhangup) {
02662       struct ast_frame *fr;
02663 
02664       /* If we have completely cleared the softhangup flag,
02665        * then we need to fully abort the hangup process.  This requires
02666        * pulling the END_OF_Q frame out of the channel frame queue if it
02667        * still happens to be there. */
02668 
02669       fr = AST_LIST_LAST(&chan->readq);
02670       if (fr && fr->frametype == AST_FRAME_CONTROL &&
02671             fr->subclass.integer == AST_CONTROL_END_OF_Q) {
02672          AST_LIST_REMOVE(&chan->readq, fr, frame_list);
02673          ast_frfree(fr);
02674       }
02675    }
02676 
02677    ast_channel_unlock(chan);
02678 }
02679 
02680 /*! \brief Softly hangup a channel, don't lock */
02681 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
02682 {
02683    ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
02684    /* Inform channel driver that we need to be hung up, if it cares */
02685    chan->_softhangup |= cause;
02686    ast_queue_frame(chan, &ast_null_frame);
02687    /* Interrupt any poll call or such */
02688    if (ast_test_flag(chan, AST_FLAG_BLOCKING))
02689       pthread_kill(chan->blocker, SIGURG);
02690    return 0;
02691 }
02692 
02693 /*! \brief Softly hangup a channel, lock */
02694 int ast_softhangup(struct ast_channel *chan, int cause)
02695 {
02696    int res;
02697 
02698    ast_channel_lock(chan);
02699    res = ast_softhangup_nolock(chan, cause);
02700    ast_channel_unlock(chan);
02701 
02702    return res;
02703 }
02704 
02705 static void free_translation(struct ast_channel *clonechan)
02706 {
02707    if (clonechan->writetrans)
02708       ast_translator_free_path(clonechan->writetrans);
02709    if (clonechan->readtrans)
02710       ast_translator_free_path(clonechan->readtrans);
02711    clonechan->writetrans = NULL;
02712    clonechan->readtrans = NULL;
02713    clonechan->rawwriteformat = clonechan->nativeformats;
02714    clonechan->rawreadformat = clonechan->nativeformats;
02715 }
02716 
02717 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
02718 {
02719    struct ast_channel *bridge;
02720 
02721    ast_channel_lock(chan);
02722    if (force || ast_strlen_zero(chan->hangupsource)) {
02723       ast_string_field_set(chan, hangupsource, source);
02724    }
02725    bridge = ast_bridged_channel(chan);
02726    ast_channel_unlock(chan);
02727 
02728    if (bridge && (force || ast_strlen_zero(bridge->hangupsource))) {
02729       ast_channel_lock(bridge);
02730       ast_string_field_set(chan, hangupsource, source);
02731       ast_channel_unlock(bridge);
02732    }
02733 }
02734 
02735 static void destroy_hooks(struct ast_channel *chan)
02736 {
02737    if (chan->audiohooks) {
02738       ast_audiohook_detach_list(chan->audiohooks);
02739       chan->audiohooks = NULL;
02740    }
02741 
02742    ast_framehook_list_destroy(chan);
02743 }
02744 
02745 /*! \brief Hangup a channel */
02746 int ast_hangup(struct ast_channel *chan)
02747 {
02748    char extra_str[64]; /* used for cel logging below */
02749    int was_zombie;
02750 
02751    ast_autoservice_stop(chan);
02752 
02753    ast_channel_lock(chan);
02754 
02755    /*
02756     * Do the masquerade if someone is setup to masquerade into us.
02757     *
02758     * NOTE: We must hold the channel lock after testing for a
02759     * pending masquerade and setting the channel as a zombie to
02760     * prevent __ast_channel_masquerade() from setting up a
02761     * masquerade with a dead channel.
02762     */
02763    while (chan->masq) {
02764       ast_channel_unlock(chan);
02765       if (ast_do_masquerade(chan)) {
02766          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
02767 
02768          /* Abort the loop or we might never leave. */
02769          ast_channel_lock(chan);
02770          break;
02771       }
02772       ast_channel_lock(chan);
02773    }
02774 
02775    if (chan->masqr) {
02776       /*
02777        * This channel is one which will be masqueraded into something.
02778        * Mark it as a zombie already so ast_do_masquerade() will know
02779        * to free it later.
02780        */
02781       ast_set_flag(chan, AST_FLAG_ZOMBIE);
02782       destroy_hooks(chan);
02783       ast_channel_unlock(chan);
02784       return 0;
02785    }
02786 
02787    if (!(was_zombie = ast_test_flag(chan, AST_FLAG_ZOMBIE))) {
02788       ast_set_flag(chan, AST_FLAG_ZOMBIE);
02789    }
02790 
02791    ast_channel_unlock(chan);
02792    ao2_unlink(channels, chan);
02793    ast_channel_lock(chan);
02794 
02795    destroy_hooks(chan);
02796 
02797    free_translation(chan);
02798    /* Close audio stream */
02799    if (chan->stream) {
02800       ast_closestream(chan->stream);
02801       chan->stream = NULL;
02802    }
02803    /* Close video stream */
02804    if (chan->vstream) {
02805       ast_closestream(chan->vstream);
02806       chan->vstream = NULL;
02807    }
02808    if (chan->sched) {
02809       sched_context_destroy(chan->sched);
02810       chan->sched = NULL;
02811    }
02812 
02813    if (chan->generatordata) { /* Clear any tone stuff remaining */
02814       if (chan->generator && chan->generator->release) {
02815          chan->generator->release(chan, chan->generatordata);
02816       }
02817    }
02818    chan->generatordata = NULL;
02819    chan->generator = NULL;
02820 
02821    snprintf(extra_str, sizeof(extra_str), "%d,%s,%s", chan->hangupcause, chan->hangupsource, S_OR(pbx_builtin_getvar_helper(chan, "DIALSTATUS"), ""));
02822    ast_cel_report_event(chan, AST_CEL_HANGUP, NULL, extra_str, NULL);
02823 
02824    if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
02825       ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
02826          "is blocked by thread %ld in procedure %s!  Expect a failure\n",
02827          (long) pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
02828       ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
02829    }
02830    if (!was_zombie) {
02831       ast_debug(1, "Hanging up channel '%s'\n", chan->name);
02832 
02833       if (chan->tech->hangup) {
02834          chan->tech->hangup(chan);
02835       }
02836    } else {
02837       ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
02838    }
02839 
02840    ast_channel_unlock(chan);
02841 
02842    ast_cc_offer(chan);
02843    ast_manager_event(chan, EVENT_FLAG_CALL, "Hangup",
02844       "Channel: %s\r\n"
02845       "Uniqueid: %s\r\n"
02846       "CallerIDNum: %s\r\n"
02847       "CallerIDName: %s\r\n"
02848       "ConnectedLineNum: %s\r\n"
02849       "ConnectedLineName: %s\r\n"
02850       "Cause: %d\r\n"
02851       "Cause-txt: %s\r\n",
02852       chan->name,
02853       chan->uniqueid,
02854       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<unknown>"),
02855       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, "<unknown>"),
02856       S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, "<unknown>"),
02857       S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, "<unknown>"),
02858       chan->hangupcause,
02859       ast_cause2str(chan->hangupcause)
02860       );
02861 
02862    if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) &&
02863       !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) &&
02864       (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
02865       ast_channel_lock(chan);
02866       ast_cdr_end(chan->cdr);
02867       ast_cdr_detach(chan->cdr);
02868       chan->cdr = NULL;
02869       ast_channel_unlock(chan);
02870    }
02871 
02872    ast_channel_unref(chan);
02873 
02874    return 0;
02875 }
02876 
02877 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
02878 {
02879    int res = 0;
02880 
02881    ast_channel_lock(chan);
02882 
02883    /* You can't answer an outbound call */
02884    if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
02885       ast_channel_unlock(chan);
02886       return 0;
02887    }
02888 
02889    /* Stop if we're a zombie or need a soft hangup */
02890    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
02891       ast_channel_unlock(chan);
02892       return -1;
02893    }
02894 
02895    ast_channel_unlock(chan);
02896 
02897    switch (chan->_state) {
02898    case AST_STATE_RINGING:
02899    case AST_STATE_RING:
02900       ast_channel_lock(chan);
02901       if (chan->tech->answer) {
02902          res = chan->tech->answer(chan);
02903       }
02904       ast_setstate(chan, AST_STATE_UP);
02905       if (cdr_answer) {
02906          ast_cdr_answer(chan->cdr);
02907       }
02908       ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
02909       ast_channel_unlock(chan);
02910       break;
02911    case AST_STATE_UP:
02912       ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
02913       /* Calling ast_cdr_answer when it it has previously been called
02914        * is essentially a no-op, so it is safe.
02915        */
02916       if (cdr_answer) {
02917          ast_cdr_answer(chan->cdr);
02918       }
02919       break;
02920    default:
02921       break;
02922    }
02923 
02924    ast_indicate(chan, -1);
02925 
02926    return res;
02927 }
02928 
02929 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
02930 {
02931    int res = 0;
02932    enum ast_channel_state old_state;
02933 
02934    old_state = chan->_state;
02935    if ((res = ast_raw_answer(chan, cdr_answer))) {
02936       return res;
02937    }
02938 
02939    switch (old_state) {
02940    case AST_STATE_RINGING:
02941    case AST_STATE_RING:
02942       /* wait for media to start flowing, but don't wait any longer
02943        * than 'delay' or 500 milliseconds, whichever is longer
02944        */
02945       do {
02946          AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
02947          struct ast_frame *cur, *new;
02948          int ms = MAX(delay, 500);
02949          unsigned int done = 0;
02950 
02951          AST_LIST_HEAD_INIT_NOLOCK(&frames);
02952 
02953          for (;;) {
02954             ms = ast_waitfor(chan, ms);
02955             if (ms < 0) {
02956                ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
02957                res = -1;
02958                break;
02959             }
02960             if (ms == 0) {
02961                ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
02962                break;
02963             }
02964             cur = ast_read(chan);
02965             if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
02966                     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
02967                if (cur) {
02968                   ast_frfree(cur);
02969                }
02970                res = -1;
02971                ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
02972                break;
02973             }
02974 
02975             if ((new = ast_frisolate(cur)) != cur) {
02976                ast_frfree(cur);
02977             }
02978 
02979             AST_LIST_INSERT_HEAD(&frames, new, frame_list);
02980 
02981             /* if a specific delay period was requested, continue
02982              * until that delay has passed. don't stop just because
02983              * incoming media has arrived.
02984              */
02985             if (delay) {
02986                continue;
02987             }
02988 
02989             switch (new->frametype) {
02990                /* all of these frametypes qualify as 'media' */
02991             case AST_FRAME_VOICE:
02992             case AST_FRAME_VIDEO:
02993             case AST_FRAME_TEXT:
02994             case AST_FRAME_DTMF_BEGIN:
02995             case AST_FRAME_DTMF_END:
02996             case AST_FRAME_IMAGE:
02997             case AST_FRAME_HTML:
02998             case AST_FRAME_MODEM:
02999                done = 1;
03000                break;
03001             case AST_FRAME_CONTROL:
03002             case AST_FRAME_IAX:
03003             case AST_FRAME_NULL:
03004             case AST_FRAME_CNG:
03005                break;
03006             }
03007 
03008             if (done) {
03009                break;
03010             }
03011          }
03012 
03013          if (res == 0) {
03014             ast_channel_lock(chan);
03015             while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
03016                ast_queue_frame_head(chan, cur);
03017                ast_frfree(cur);
03018             }
03019             ast_channel_unlock(chan);
03020          }
03021       } while (0);
03022       break;
03023    default:
03024       break;
03025    }
03026 
03027    return res;
03028 }
03029 
03030 int ast_answer(struct ast_channel *chan)
03031 {
03032    return __ast_answer(chan, 0, 1);
03033 }
03034 
03035 void ast_deactivate_generator(struct ast_channel *chan)
03036 {
03037    ast_channel_lock(chan);
03038    if (chan->generatordata) {
03039       if (chan->generator && chan->generator->release)
03040          chan->generator->release(chan, chan->generatordata);
03041       chan->generatordata = NULL;
03042       chan->generator = NULL;
03043       ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
03044       ast_clear_flag(chan, AST_FLAG_WRITE_INT);
03045       ast_settimeout(chan, 0, NULL, NULL);
03046    }
03047    ast_channel_unlock(chan);
03048 }
03049 
03050 static int generator_force(const void *data)
03051 {
03052    /* Called if generator doesn't have data */
03053    void *tmp;
03054    int res;
03055    int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
03056    struct ast_channel *chan = (struct ast_channel *)data;
03057 
03058    ast_channel_lock(chan);
03059    tmp = chan->generatordata;
03060    chan->generatordata = NULL;
03061    if (chan->generator)
03062       generate = chan->generator->generate;
03063    ast_channel_unlock(chan);
03064 
03065    if (!tmp || !generate)
03066       return 0;
03067 
03068    res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
03069 
03070    chan->generatordata = tmp;
03071 
03072    if (res) {
03073       ast_debug(1, "Auto-deactivating generator\n");
03074       ast_deactivate_generator(chan);
03075    }
03076 
03077    return 0;
03078 }
03079 
03080 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
03081 {
03082    int res = 0;
03083 
03084    ast_channel_lock(chan);
03085    if (chan->generatordata) {
03086       if (chan->generator && chan->generator->release)
03087          chan->generator->release(chan, chan->generatordata);
03088       chan->generatordata = NULL;
03089    }
03090    if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
03091       res = -1;
03092    }
03093    if (!res) {
03094       ast_settimeout(chan, 50, generator_force, chan);
03095       chan->generator = gen;
03096    }
03097    ast_channel_unlock(chan);
03098 
03099    ast_prod(chan);
03100 
03101    return res;
03102 }
03103 
03104 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
03105 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
03106 {
03107    int winner = -1;
03108    ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
03109    return winner;
03110 }
03111 
03112 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
03113 #ifdef HAVE_EPOLL
03114 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
03115                int *exception, int *outfd, int *ms)
03116 #else
03117 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
03118                int *exception, int *outfd, int *ms)
03119 #endif
03120 {
03121    struct timeval start = { 0 , 0 };
03122    struct pollfd *pfds = NULL;
03123    int res;
03124    long rms;
03125    int x, y, max;
03126    int sz;
03127    struct timeval now = { 0, 0 };
03128    struct timeval whentohangup = { 0, 0 }, diff;
03129    struct ast_channel *winner = NULL;
03130    struct fdmap {
03131       int chan;
03132       int fdno;
03133    } *fdmap = NULL;
03134 
03135    if ((sz = n * AST_MAX_FDS + nfds)) {
03136       pfds = alloca(sizeof(*pfds) * sz);
03137       fdmap = alloca(sizeof(*fdmap) * sz);
03138    }
03139 
03140    if (outfd)
03141       *outfd = -99999;
03142    if (exception)
03143       *exception = 0;
03144    
03145    /* Perform any pending masquerades */
03146    for (x = 0; x < n; x++) {
03147       if (c[x]->masq && ast_do_masquerade(c[x])) {
03148          ast_log(LOG_WARNING, "Masquerade failed\n");
03149          *ms = -1;
03150          return NULL;
03151       }
03152 
03153       ast_channel_lock(c[x]);
03154       if (!ast_tvzero(c[x]->whentohangup)) {
03155          if (ast_tvzero(whentohangup))
03156             now = ast_tvnow();
03157          diff = ast_tvsub(c[x]->whentohangup, now);
03158          if (diff.tv_sec < 0 || ast_tvzero(diff)) {
03159             /* Should already be hungup */
03160             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03161             ast_channel_unlock(c[x]);
03162             return c[x];
03163          }
03164          if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
03165             whentohangup = diff;
03166       }
03167       ast_channel_unlock(c[x]);
03168    }
03169    /* Wait full interval */
03170    rms = *ms;
03171    /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
03172    if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
03173       rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
03174       if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
03175          rms =  *ms;
03176       }
03177    } else if (!ast_tvzero(whentohangup) && rms < 0) {
03178       /* Tiny corner case... call would need to last >24 days */
03179       rms = INT_MAX;
03180    }
03181    /*
03182     * Build the pollfd array, putting the channels' fds first,
03183     * followed by individual fds. Order is important because
03184     * individual fd's must have priority over channel fds.
03185     */
03186    max = 0;
03187    for (x = 0; x < n; x++) {
03188       for (y = 0; y < AST_MAX_FDS; y++) {
03189          fdmap[max].fdno = y;  /* fd y is linked to this pfds */
03190          fdmap[max].chan = x;  /* channel x is linked to this pfds */
03191          max += ast_add_fd(&pfds[max], c[x]->fds[y]);
03192       }
03193       CHECK_BLOCKING(c[x]);
03194    }
03195    /* Add the individual fds */
03196    for (x = 0; x < nfds; x++) {
03197       fdmap[max].chan = -1;
03198       max += ast_add_fd(&pfds[max], fds[x]);
03199    }
03200 
03201    if (*ms > 0)
03202       start = ast_tvnow();
03203    
03204    if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
03205       do {
03206          int kbrms = rms;
03207          if (kbrms > 600000)
03208             kbrms = 600000;
03209          res = ast_poll(pfds, max, kbrms);
03210          if (!res)
03211             rms -= kbrms;
03212       } while (!res && (rms > 0));
03213    } else {
03214       res = ast_poll(pfds, max, rms);
03215    }
03216    for (x = 0; x < n; x++)
03217       ast_clear_flag(c[x], AST_FLAG_BLOCKING);
03218    if (res < 0) { /* Simulate a timeout if we were interrupted */
03219       if (errno != EINTR)
03220          *ms = -1;
03221       return NULL;
03222    }
03223    if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
03224       now = ast_tvnow();
03225       for (x = 0; x < n; x++) {
03226          if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
03227             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03228             if (winner == NULL)
03229                winner = c[x];
03230          }
03231       }
03232    }
03233    if (res == 0) { /* no fd ready, reset timeout and done */
03234       *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
03235       return winner;
03236    }
03237    /*
03238     * Then check if any channel or fd has a pending event.
03239     * Remember to check channels first and fds last, as they
03240     * must have priority on setting 'winner'
03241     */
03242    for (x = 0; x < max; x++) {
03243       res = pfds[x].revents;
03244       if (res == 0)
03245          continue;
03246       if (fdmap[x].chan >= 0) {  /* this is a channel */
03247          winner = c[fdmap[x].chan]; /* override previous winners */
03248          if (res & POLLPRI)
03249             ast_set_flag(winner, AST_FLAG_EXCEPTION);
03250          else
03251             ast_clear_flag(winner, AST_FLAG_EXCEPTION);
03252          winner->fdno = fdmap[x].fdno;
03253       } else {       /* this is an fd */
03254          if (outfd)
03255             *outfd = pfds[x].fd;
03256          if (exception)
03257             *exception = (res & POLLPRI) ? -1 : 0;
03258          winner = NULL;
03259       }
03260    }
03261    if (*ms > 0) {
03262       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03263       if (*ms < 0)
03264          *ms = 0;
03265    }
03266    return winner;
03267 }
03268 
03269 #ifdef HAVE_EPOLL
03270 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
03271 {
03272    struct timeval start = { 0 , 0 };
03273    int res = 0;
03274    struct epoll_event ev[1];
03275    long diff, rms = *ms;
03276    struct ast_channel *winner = NULL;
03277    struct ast_epoll_data *aed = NULL;
03278 
03279 
03280    /* See if this channel needs to be masqueraded */
03281    if (chan->masq && ast_do_masquerade(chan)) {
03282       ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
03283       *ms = -1;
03284       return NULL;
03285    }
03286 
03287    ast_channel_lock(chan);
03288    /* Figure out their timeout */
03289    if (!ast_tvzero(chan->whentohangup)) {
03290       if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
03291          /* They should already be hungup! */
03292          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03293          ast_channel_unlock(chan);
03294          return NULL;
03295       }
03296       /* If this value is smaller then the current one... make it priority */
03297       if (rms > diff)
03298          rms = diff;
03299    }
03300 
03301    ast_channel_unlock(chan);
03302 
03303    /* Time to make this channel block... */
03304    CHECK_BLOCKING(chan);
03305 
03306    if (*ms > 0)
03307       start = ast_tvnow();
03308 
03309    /* We don't have to add any file descriptors... they are already added, we just have to wait! */
03310    res = epoll_wait(chan->epfd, ev, 1, rms);
03311 
03312    /* Stop blocking */
03313    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03314 
03315    /* Simulate a timeout if we were interrupted */
03316    if (res < 0) {
03317       if (errno != EINTR)
03318          *ms = -1;
03319       return NULL;
03320    }
03321 
03322    /* If this channel has a timeout see if it expired */
03323    if (!ast_tvzero(chan->whentohangup)) {
03324       if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
03325          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03326          winner = chan;
03327       }
03328    }
03329 
03330    /* No fd ready, reset timeout and be done for now */
03331    if (!res) {
03332       *ms = 0;
03333       return winner;
03334    }
03335 
03336    /* See what events are pending */
03337    aed = ev[0].data.ptr;
03338    chan->fdno = aed->which;
03339    if (ev[0].events & EPOLLPRI)
03340       ast_set_flag(chan, AST_FLAG_EXCEPTION);
03341    else
03342       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03343 
03344    if (*ms > 0) {
03345       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03346       if (*ms < 0)
03347          *ms = 0;
03348    }
03349 
03350    return chan;
03351 }
03352 
03353 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
03354 {
03355    struct timeval start = { 0 , 0 };
03356    int res = 0, i;
03357    struct epoll_event ev[25] = { { 0, } };
03358    struct timeval now = { 0, 0 };
03359    long whentohangup = 0, diff = 0, rms = *ms;
03360    struct ast_channel *winner = NULL;
03361 
03362    for (i = 0; i < n; i++) {
03363       if (c[i]->masq && ast_do_masquerade(c[i])) {
03364          ast_log(LOG_WARNING, "Masquerade failed\n");
03365          *ms = -1;
03366          return NULL;
03367       }
03368 
03369       ast_channel_lock(c[i]);
03370       if (!ast_tvzero(c[i]->whentohangup)) {
03371          if (whentohangup == 0)
03372             now = ast_tvnow();
03373          if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
03374             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03375             ast_channel_unlock(c[i]);
03376             return c[i];
03377          }
03378          if (!whentohangup || whentohangup > diff)
03379             whentohangup = diff;
03380       }
03381       ast_channel_unlock(c[i]);
03382       CHECK_BLOCKING(c[i]);
03383    }
03384 
03385    rms = *ms;
03386    if (whentohangup) {
03387       rms = whentohangup;
03388       if (*ms >= 0 && *ms < rms)
03389          rms = *ms;
03390    }
03391 
03392    if (*ms > 0)
03393       start = ast_tvnow();
03394 
03395    res = epoll_wait(c[0]->epfd, ev, 25, rms);
03396 
03397    for (i = 0; i < n; i++)
03398       ast_clear_flag(c[i], AST_FLAG_BLOCKING);
03399 
03400    if (res < 0) {
03401       if (errno != EINTR)
03402          *ms = -1;
03403       return NULL;
03404    }
03405 
03406    if (whentohangup) {
03407       now = ast_tvnow();
03408       for (i = 0; i < n; i++) {
03409          if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
03410             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
03411             if (!winner)
03412                winner = c[i];
03413          }
03414       }
03415    }
03416 
03417    if (!res) {
03418       *ms = 0;
03419       return winner;
03420    }
03421 
03422    for (i = 0; i < res; i++) {
03423       struct ast_epoll_data *aed = ev[i].data.ptr;
03424 
03425       if (!ev[i].events || !aed)
03426          continue;
03427 
03428       winner = aed->chan;
03429       if (ev[i].events & EPOLLPRI)
03430          ast_set_flag(winner, AST_FLAG_EXCEPTION);
03431       else
03432          ast_clear_flag(winner, AST_FLAG_EXCEPTION);
03433       winner->fdno = aed->which;
03434    }
03435 
03436    if (*ms > 0) {
03437       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03438       if (*ms < 0)
03439          *ms = 0;
03440    }
03441 
03442    return winner;
03443 }
03444 
03445 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
03446                int *exception, int *outfd, int *ms)
03447 {
03448    /* Clear all provided values in one place. */
03449    if (outfd)
03450       *outfd = -99999;
03451    if (exception)
03452       *exception = 0;
03453 
03454    /* If no epoll file descriptor is available resort to classic nandfds */
03455    if (!n || nfds || c[0]->epfd == -1)
03456       return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
03457    else if (!nfds && n == 1)
03458       return ast_waitfor_nandfds_simple(c[0], ms);
03459    else
03460       return ast_waitfor_nandfds_complex(c, n, ms);
03461 }
03462 #endif
03463 
03464 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
03465 {
03466    return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
03467 }
03468 
03469 int ast_waitfor(struct ast_channel *c, int ms)
03470 {
03471    int oldms = ms;   /* -1 if no timeout */
03472 
03473    ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
03474    if ((ms < 0) && (oldms < 0))
03475       ms = 0;
03476    return ms;
03477 }
03478 
03479 /* XXX never to be called with ms = -1 */
03480 int ast_waitfordigit(struct ast_channel *c, int ms)
03481 {
03482    return ast_waitfordigit_full(c, ms, -1, -1);
03483 }
03484 
03485 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
03486 {
03487    int res;
03488    unsigned int real_rate = rate, max_rate;
03489 
03490    ast_channel_lock(c);
03491 
03492    if (c->timingfd == -1) {
03493       ast_channel_unlock(c);
03494       return -1;
03495    }
03496 
03497    if (!func) {
03498       rate = 0;
03499       data = NULL;
03500    }
03501 
03502    if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
03503       real_rate = max_rate;
03504    }
03505 
03506    ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
03507 
03508    res = ast_timer_set_rate(c->timer, real_rate);
03509 
03510    c->timingfunc = func;
03511    c->timingdata = data;
03512 
03513    if (func == NULL && rate == 0 && c->fdno == AST_TIMING_FD) {
03514       /* Clearing the timing func and setting the rate to 0
03515        * means that we don't want to be reading from the timingfd
03516        * any more. Setting c->fdno to -1 means we won't have any
03517        * errant reads from the timingfd, meaning we won't potentially
03518        * miss any important frames.
03519        */
03520       c->fdno = -1;
03521    }
03522 
03523    ast_channel_unlock(c);
03524 
03525    return res;
03526 }
03527 
03528 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
03529 {
03530    /* Stop if we're a zombie or need a soft hangup */
03531    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
03532       return -1;
03533 
03534    /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
03535    ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
03536 
03537    /* Wait for a digit, no more than ms milliseconds total. */
03538    
03539    while (ms) {
03540       struct ast_channel *rchan;
03541       int outfd=-1;
03542 
03543       errno = 0;
03544       rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
03545       
03546       if (!rchan && outfd < 0 && ms) {
03547          if (errno == 0 || errno == EINTR)
03548             continue;
03549          ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
03550          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03551          return -1;
03552       } else if (outfd > -1) {
03553          /* The FD we were watching has something waiting */
03554          ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
03555          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03556          return 1;
03557       } else if (rchan) {
03558          int res;
03559          struct ast_frame *f = ast_read(c);
03560          if (!f)
03561             return -1;
03562 
03563          switch (f->frametype) {
03564          case AST_FRAME_DTMF_BEGIN:
03565             break;
03566          case AST_FRAME_DTMF_END:
03567             res = f->subclass.integer;
03568             ast_frfree(f);
03569             ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03570             return res;
03571          case AST_FRAME_CONTROL:
03572             switch (f->subclass.integer) {
03573             case AST_CONTROL_HANGUP:
03574                ast_frfree(f);
03575                ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03576                return -1;
03577             case AST_CONTROL_RINGING:
03578             case AST_CONTROL_ANSWER:
03579             case AST_CONTROL_SRCUPDATE:
03580             case AST_CONTROL_SRCCHANGE:
03581             case AST_CONTROL_CONNECTED_LINE:
03582             case AST_CONTROL_REDIRECTING:
03583             case AST_CONTROL_UPDATE_RTP_PEER:
03584             case AST_CONTROL_HOLD:
03585             case AST_CONTROL_UNHOLD:
03586             case -1:
03587                /* Unimportant */
03588                break;
03589             default:
03590                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
03591                break;
03592             }
03593             break;
03594          case AST_FRAME_VOICE:
03595             /* Write audio if appropriate */
03596             if (audiofd > -1) {
03597                if (write(audiofd, f->data.ptr, f->datalen) < 0) {
03598                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
03599                }
03600             }
03601          default:
03602             /* Ignore */
03603             break;
03604          }
03605          ast_frfree(f);
03606       }
03607    }
03608 
03609    ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
03610 
03611    return 0; /* Time is up */
03612 }
03613 
03614 static void send_dtmf_event(struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
03615 {
03616    ast_manager_event(chan, EVENT_FLAG_DTMF,
03617          "DTMF",
03618          "Channel: %s\r\n"
03619          "Uniqueid: %s\r\n"
03620          "Digit: %c\r\n"
03621          "Direction: %s\r\n"
03622          "Begin: %s\r\n"
03623          "End: %s\r\n",
03624          chan->name, chan->uniqueid, digit, direction, begin, end);
03625 }
03626 
03627 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
03628 {
03629    if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
03630       void *tmp = chan->generatordata;
03631       int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
03632       int res;
03633       int samples;
03634 
03635       if (chan->timingfunc) {
03636          ast_debug(1, "Generator got voice, switching to phase locked mode\n");
03637          ast_settimeout(chan, 0, NULL, NULL);
03638       }
03639 
03640       chan->generatordata = NULL;     /* reset, to let writes go through */
03641 
03642       if (f->subclass.codec != chan->writeformat) {
03643          float factor;
03644          factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass.codec));
03645          samples = (int) ( ((float) f->samples) * factor );
03646       } else {
03647          samples = f->samples;
03648       }
03649       
03650       /* This unlock is here based on two assumptions that hold true at this point in the
03651        * code. 1) this function is only called from within __ast_read() and 2) all generators
03652        * call ast_write() in their generate callback.
03653        *
03654        * The reason this is added is so that when ast_write is called, the lock that occurs 
03655        * there will not recursively lock the channel. Doing this will cause intended deadlock 
03656        * avoidance not to work in deeper functions
03657        */
03658       ast_channel_unlock(chan);
03659       res = generate(chan, tmp, f->datalen, samples);
03660       ast_channel_lock(chan);
03661       chan->generatordata = tmp;
03662       if (res) {
03663          ast_debug(1, "Auto-deactivating generator\n");
03664          ast_deactivate_generator(chan);
03665       }
03666 
03667    } else if (f->frametype == AST_FRAME_CNG) {
03668       if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
03669          ast_debug(1, "Generator got CNG, switching to timed mode\n");
03670          ast_settimeout(chan, 50, generator_force, chan);
03671       }
03672    }
03673 }
03674 
03675 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
03676 {
03677    struct ast_frame *fr = &chan->dtmff;
03678 
03679    fr->frametype = AST_FRAME_DTMF_END;
03680    fr->subclass.integer = f->subclass.integer;
03681    fr->len = f->len;
03682 
03683    /* The only time this function will be called is for a frame that just came
03684     * out of the channel driver.  So, we want to stick it on the tail of the
03685     * readq. */
03686 
03687    ast_queue_frame(chan, fr);
03688 }
03689 
03690 /*!
03691  * \brief Determine whether or not we should ignore DTMF in the readq
03692  */
03693 static inline int should_skip_dtmf(struct ast_channel *chan)
03694 {
03695    if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
03696       /* We're in the middle of emulating a digit, or DTMF has been
03697        * explicitly deferred.  Skip this digit, then. */
03698       return 1;
03699    }
03700          
03701    if (!ast_tvzero(chan->dtmf_tv) && 
03702          ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
03703       /* We're not in the middle of a digit, but it hasn't been long enough
03704        * since the last digit, so we'll have to skip DTMF for now. */
03705       return 1;
03706    }
03707 
03708    return 0;
03709 }
03710 
03711 /*!
03712  * \brief calculates the number of samples to jump forward with in a monitor stream.
03713  
03714  * \note When using ast_seekstream() with the read and write streams of a monitor,
03715  * the number of samples to seek forward must be of the same sample rate as the stream
03716  * or else the jump will not be calculated correctly.
03717  *
03718  * \retval number of samples to seek forward after rate conversion.
03719  */
03720 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
03721 {
03722    int diff = sample_rate - seek_rate;
03723 
03724    if (diff > 0) {
03725       samples = samples / (float) (sample_rate / seek_rate);
03726    } else if (diff < 0) {
03727       samples = samples * (float) (seek_rate / sample_rate);
03728    }
03729 
03730    return samples;
03731 }
03732 
03733 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
03734 {
03735    struct ast_frame *f = NULL;   /* the return value */
03736    int blah;
03737    int prestate;
03738    int cause = 0;
03739 
03740    /* this function is very long so make sure there is only one return
03741     * point at the end (there are only two exceptions to this).
03742     */
03743 
03744    if (chan->masq) {
03745       if (ast_do_masquerade(chan))
03746          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
03747       else
03748          f =  &ast_null_frame;
03749       return f;
03750    }
03751 
03752    /* if here, no masq has happened, lock the channel and proceed */
03753    ast_channel_lock(chan);
03754 
03755    /* Stop if we're a zombie or need a soft hangup */
03756    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03757       if (chan->generator)
03758          ast_deactivate_generator(chan);
03759 
03760       /*
03761        * It is possible for chan->_softhangup to be set and there
03762        * still be control frames that need to be read.  Instead of
03763        * just going to 'done' in the case of ast_check_hangup(), we
03764        * need to queue the end-of-Q frame so that it can mark the end
03765        * of the read queue.  If there are frames to be read,
03766        * ast_queue_control() will be called repeatedly, but will only
03767        * queue the first end-of-Q frame.
03768        */
03769       if (chan->_softhangup) {
03770          ast_queue_control(chan, AST_CONTROL_END_OF_Q);
03771       } else {
03772          goto done;
03773       }
03774    } else {
03775 #ifdef AST_DEVMODE
03776       /*
03777        * The ast_waitfor() code records which of the channel's file
03778        * descriptors reported that data is available.  In theory,
03779        * ast_read() should only be called after ast_waitfor() reports
03780        * that a channel has data available for reading.  However,
03781        * there still may be some edge cases throughout the code where
03782        * ast_read() is called improperly.  This can potentially cause
03783        * problems, so if this is a developer build, make a lot of
03784        * noise if this happens so that it can be addressed.
03785        *
03786        * One of the potential problems is blocking on a dead channel.
03787        */
03788       if (chan->fdno == -1) {
03789          ast_log(LOG_ERROR,
03790             "ast_read() on chan '%s' called with no recorded file descriptor.\n",
03791             chan->name);
03792       }
03793 #endif
03794    }
03795 
03796    prestate = chan->_state;
03797    if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
03798       enum ast_timer_event res;
03799 
03800       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03801 
03802       res = ast_timer_get_event(chan->timer);
03803 
03804       switch (res) {
03805       case AST_TIMING_EVENT_EXPIRED:
03806          ast_timer_ack(chan->timer, 1);
03807 
03808          if (chan->timingfunc) {
03809             /* save a copy of func/data before unlocking the channel */
03810             int (*func)(const void *) = chan->timingfunc;
03811             void *data = chan->timingdata;
03812             chan->fdno = -1;
03813             ast_channel_unlock(chan);
03814             func(data);
03815          } else {
03816             ast_timer_set_rate(chan->timer, 0);
03817             chan->fdno = -1;
03818             ast_channel_unlock(chan);
03819          }
03820 
03821          /* cannot 'goto done' because the channel is already unlocked */
03822          return &ast_null_frame;
03823 
03824       case AST_TIMING_EVENT_CONTINUOUS:
03825          if (AST_LIST_EMPTY(&chan->readq) || 
03826             !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
03827             ast_timer_disable_continuous(chan->timer);
03828          }
03829          break;
03830       }
03831 
03832    } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
03833       /* if the AST_GENERATOR_FD is set, call the generator with args
03834        * set to -1 so it can do whatever it needs to.
03835        */
03836       void *tmp = chan->generatordata;
03837       chan->generatordata = NULL;     /* reset to let ast_write get through */
03838       chan->generator->generate(chan, tmp, -1, -1);
03839       chan->generatordata = tmp;
03840       f = &ast_null_frame;
03841       chan->fdno = -1;
03842       goto done;
03843    }
03844 
03845    /* Read and ignore anything on the alertpipe, but read only
03846       one sizeof(blah) per frame that we send from it */
03847    if (chan->alertpipe[0] > -1) {
03848       int flags = fcntl(chan->alertpipe[0], F_GETFL);
03849       /* For some odd reason, the alertpipe occasionally loses nonblocking status,
03850        * which immediately causes a deadlock scenario.  Detect and prevent this. */
03851       if ((flags & O_NONBLOCK) == 0) {
03852          ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
03853          if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
03854             ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
03855             f = &ast_null_frame;
03856             goto done;
03857          }
03858       }
03859       if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
03860          if (errno != EINTR && errno != EAGAIN)
03861             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
03862       }
03863    }
03864 
03865 
03866    /* Check for pending read queue */
03867    if (!AST_LIST_EMPTY(&chan->readq)) {
03868       int skip_dtmf = should_skip_dtmf(chan);
03869 
03870       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
03871          /* We have to be picky about which frame we pull off of the readq because
03872           * there are cases where we want to leave DTMF frames on the queue until
03873           * some later time. */
03874 
03875          if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
03876             continue;
03877          }
03878 
03879          AST_LIST_REMOVE_CURRENT(frame_list);
03880          break;
03881       }
03882       AST_LIST_TRAVERSE_SAFE_END;
03883       
03884       if (!f) {
03885          /* There were no acceptable frames on the readq. */
03886          f = &ast_null_frame;
03887          if (chan->alertpipe[0] > -1) {
03888             int poke = 0;
03889             /* Restore the state of the alertpipe since we aren't ready for any
03890              * of the frames in the readq. */
03891             if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
03892                ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
03893             }
03894          }
03895       }
03896 
03897       /* Interpret hangup and end-of-Q frames to return NULL */
03898       /* XXX why not the same for frames from the channel ? */
03899       if (f->frametype == AST_FRAME_CONTROL) {
03900          switch (f->subclass.integer) {
03901          case AST_CONTROL_HANGUP:
03902             chan->_softhangup |= AST_SOFTHANGUP_DEV;
03903             cause = f->data.uint32;
03904             /* Fall through */
03905          case AST_CONTROL_END_OF_Q:
03906             ast_frfree(f);
03907             f = NULL;
03908             break;
03909          default:
03910             break;
03911          }
03912       }
03913    } else {
03914       chan->blocker = pthread_self();
03915       if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
03916          if (chan->tech->exception)
03917             f = chan->tech->exception(chan);
03918          else {
03919             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
03920             f = &ast_null_frame;
03921          }
03922          /* Clear the exception flag */
03923          ast_clear_flag(chan, AST_FLAG_EXCEPTION);
03924       } else if (chan->tech && chan->tech->read)
03925          f = chan->tech->read(chan);
03926       else
03927          ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
03928    }
03929 
03930    /*
03931     * Reset the recorded file descriptor that triggered this read so that we can
03932     * easily detect when ast_read() is called without properly using ast_waitfor().
03933     */
03934    chan->fdno = -1;
03935 
03936    /* Perform the framehook read event here. After the frame enters the framehook list
03937     * there is no telling what will happen, <insert mad scientist laugh here>!!! */
03938    f = ast_framehook_list_read_event(chan->framehooks, f);
03939 
03940    if (f) {
03941       struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
03942       struct ast_control_read_action_payload *read_action_payload;
03943       struct ast_party_connected_line connected;
03944 
03945       /* if the channel driver returned more than one frame, stuff the excess
03946          into the readq for the next ast_read call
03947       */
03948       if (AST_LIST_NEXT(f, frame_list)) {
03949          ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
03950          ast_frfree(AST_LIST_NEXT(f, frame_list));
03951          AST_LIST_NEXT(f, frame_list) = NULL;
03952       }
03953 
03954       switch (f->frametype) {
03955       case AST_FRAME_CONTROL:
03956          if (f->subclass.integer == AST_CONTROL_ANSWER) {
03957             if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
03958                ast_debug(1, "Ignoring answer on an inbound call!\n");
03959                ast_frfree(f);
03960                f = &ast_null_frame;
03961             } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
03962                ast_debug(1, "Dropping duplicate answer!\n");
03963                ast_frfree(f);
03964                f = &ast_null_frame;
03965             } else {
03966                /* Answer the CDR */
03967                ast_setstate(chan, AST_STATE_UP);
03968                /* removed a call to ast_cdr_answer(chan->cdr) from here. */
03969                ast_cel_report_event(chan, AST_CEL_ANSWER, NULL, NULL, NULL);
03970             }
03971          } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
03972             read_action_payload = f->data.ptr;
03973             switch (read_action_payload->action) {
03974             case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
03975                ast_party_connected_line_init(&connected);
03976                ast_party_connected_line_copy(&connected, &chan->connected);
03977                if (ast_connected_line_parse_data(read_action_payload->payload,
03978                   read_action_payload->payload_size, &connected)) {
03979                   ast_party_connected_line_free(&connected);
03980                   break;
03981                }
03982                ast_channel_unlock(chan);
03983                if (ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
03984                   ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
03985                      read_action_payload->payload,
03986                      read_action_payload->payload_size);
03987                }
03988                ast_party_connected_line_free(&connected);
03989                ast_channel_lock(chan);
03990                break;
03991             }
03992             ast_frfree(f);
03993             f = &ast_null_frame;
03994          }
03995          break;
03996       case AST_FRAME_DTMF_END:
03997          send_dtmf_event(chan, "Received", f->subclass.integer, "No", "Yes");
03998          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, chan->name, f->len);
03999          /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
04000          if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
04001             queue_dtmf_readq(chan, f);
04002             ast_frfree(f);
04003             f = &ast_null_frame;
04004          } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
04005             if (!ast_tvzero(chan->dtmf_tv) && 
04006                 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
04007                /* If it hasn't been long enough, defer this digit */
04008                queue_dtmf_readq(chan, f);
04009                ast_frfree(f);
04010                f = &ast_null_frame;
04011             } else {
04012                /* There was no begin, turn this into a begin and send the end later */
04013                f->frametype = AST_FRAME_DTMF_BEGIN;
04014                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
04015                chan->emulate_dtmf_digit = f->subclass.integer;
04016                chan->dtmf_tv = ast_tvnow();
04017                if (f->len) {
04018                   if (f->len > AST_MIN_DTMF_DURATION)
04019                      chan->emulate_dtmf_duration = f->len;
04020                   else 
04021                      chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
04022                } else
04023                   chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
04024                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);
04025             }
04026             if (chan->audiohooks) {
04027                struct ast_frame *old_frame = f;
04028                /*!
04029                 * \todo XXX It is possible to write a digit to the audiohook twice
04030                 * if the digit was originally read while the channel was in autoservice. */
04031                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04032                if (old_frame != f)
04033                   ast_frfree(old_frame);
04034             }
04035          } else {
04036             struct timeval now = ast_tvnow();
04037             if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
04038                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, chan->name);
04039                ast_clear_flag(chan, AST_FLAG_IN_DTMF);
04040                if (!f->len)
04041                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
04042 
04043                /* detect tones that were received on
04044                 * the wire with durations shorter than
04045                 * AST_MIN_DTMF_DURATION and set f->len
04046                 * to the actual duration of the DTMF
04047                 * frames on the wire.  This will cause
04048                 * dtmf emulation to be triggered later
04049                 * on.
04050                 */
04051                if (ast_tvdiff_ms(now, chan->dtmf_tv) < AST_MIN_DTMF_DURATION) {
04052                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
04053                   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);
04054                }
04055             } else if (!f->len) {
04056                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, chan->name);
04057                f->len = AST_MIN_DTMF_DURATION;
04058             }
04059             if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
04060                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);
04061                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
04062                chan->emulate_dtmf_digit = f->subclass.integer;
04063                chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
04064                ast_frfree(f);
04065                f = &ast_null_frame;
04066             } else {
04067                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, chan->name);
04068                if (f->len < AST_MIN_DTMF_DURATION) {
04069                   f->len = AST_MIN_DTMF_DURATION;
04070                }
04071                chan->dtmf_tv = now;
04072             }
04073             if (chan->audiohooks) {
04074                struct ast_frame *old_frame = f;
04075                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04076                if (old_frame != f)
04077                   ast_frfree(old_frame);
04078             }
04079          }
04080          break;
04081       case AST_FRAME_DTMF_BEGIN:
04082          send_dtmf_event(chan, "Received", f->subclass.integer, "Yes", "No");
04083          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, chan->name);
04084          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
04085              (!ast_tvzero(chan->dtmf_tv) && 
04086                ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
04087             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, chan->name);
04088             ast_frfree(f);
04089             f = &ast_null_frame;
04090          } else {
04091             ast_set_flag(chan, AST_FLAG_IN_DTMF);
04092             chan->dtmf_tv = ast_tvnow();
04093             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, chan->name);
04094          }
04095          break;
04096       case AST_FRAME_NULL:
04097          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
04098           * is reached , because we want to make sure we pass at least one
04099           * voice frame through before starting the next digit, to ensure a gap
04100           * between DTMF digits. */
04101          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
04102             struct timeval now = ast_tvnow();
04103             if (!chan->emulate_dtmf_duration) {
04104                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
04105                chan->emulate_dtmf_digit = 0;
04106             } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
04107                chan->emulate_dtmf_duration = 0;
04108                ast_frfree(f);
04109                f = &chan->dtmff;
04110                f->frametype = AST_FRAME_DTMF_END;
04111                f->subclass.integer = chan->emulate_dtmf_digit;
04112                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
04113                chan->dtmf_tv = now;
04114                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
04115                chan->emulate_dtmf_digit = 0;
04116                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
04117                if (chan->audiohooks) {
04118                   struct ast_frame *old_frame = f;
04119                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04120                   if (old_frame != f) {
04121                      ast_frfree(old_frame);
04122                   }
04123                }
04124             }
04125          }
04126          break;
04127       case AST_FRAME_VOICE:
04128          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
04129           * is reached , because we want to make sure we pass at least one
04130           * voice frame through before starting the next digit, to ensure a gap
04131           * between DTMF digits. */
04132          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
04133             ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
04134             chan->emulate_dtmf_digit = 0;
04135          }
04136 
04137          if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
04138             if (dropaudio)
04139                ast_read_generator_actions(chan, f);
04140             ast_frfree(f);
04141             f = &ast_null_frame;
04142          }
04143 
04144          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
04145             struct timeval now = ast_tvnow();
04146             if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
04147                chan->emulate_dtmf_duration = 0;
04148                ast_frfree(f);
04149                f = &chan->dtmff;
04150                f->frametype = AST_FRAME_DTMF_END;
04151                f->subclass.integer = chan->emulate_dtmf_digit;
04152                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
04153                chan->dtmf_tv = now;
04154                if (chan->audiohooks) {
04155                   struct ast_frame *old_frame = f;
04156                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04157                   if (old_frame != f)
04158                      ast_frfree(old_frame);
04159                }
04160                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, chan->name);
04161             } else {
04162                /* Drop voice frames while we're still in the middle of the digit */
04163                ast_frfree(f);
04164                f = &ast_null_frame;
04165             }
04166          } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass.codec & chan->nativeformats)) {
04167             /* This frame is not one of the current native formats -- drop it on the floor */
04168             char to[200];
04169             ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
04170                chan->name, ast_getformatname(f->subclass.codec), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
04171             ast_frfree(f);
04172             f = &ast_null_frame;
04173          } else if ((f->frametype == AST_FRAME_VOICE)) {
04174             /* Send frame to audiohooks if present */
04175             if (chan->audiohooks) {
04176                struct ast_frame *old_frame = f;
04177                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
04178                if (old_frame != f)
04179                   ast_frfree(old_frame);
04180             }
04181             if (chan->monitor && chan->monitor->read_stream ) {
04182                /* XXX what does this do ? */
04183 #ifndef MONITOR_CONSTANT_DELAY
04184                int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
04185                if (jump >= 0) {
04186                   jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04187                   if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
04188                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
04189                   chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
04190                } else
04191                   chan->insmpl+= f->samples;
04192 #else
04193                int jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
04194                if (jump - MONITOR_DELAY >= 0) {
04195                   if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
04196                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
04197                   chan->insmpl += chan->outsmpl - chan->insmpl;
04198                } else
04199                   chan->insmpl += f->samples;
04200 #endif
04201                if (chan->monitor->state == AST_MONITOR_RUNNING) {
04202                   if (ast_writestream(chan->monitor->read_stream, f) < 0)
04203                      ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
04204                }
04205             }
04206 
04207             if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL) {
04208                f = &ast_null_frame;
04209             }
04210 
04211             /* it is possible for the translation process on chan->readtrans to have
04212                produced multiple frames from the single input frame we passed it; if
04213                this happens, queue the additional frames *before* the frames we may
04214                have queued earlier. if the readq was empty, put them at the head of
04215                the queue, and if it was not, put them just after the frame that was
04216                at the end of the queue.
04217             */
04218             if (AST_LIST_NEXT(f, frame_list)) {
04219                if (!readq_tail) {
04220                   ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
04221                } else {
04222                   __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
04223                }
04224                ast_frfree(AST_LIST_NEXT(f, frame_list));
04225                AST_LIST_NEXT(f, frame_list) = NULL;
04226             }
04227 
04228             /* Run generator sitting on the line if timing device not available
04229             * and synchronous generation of outgoing frames is necessary       */
04230             ast_read_generator_actions(chan, f);
04231          }
04232          break;
04233       default:
04234          /* Just pass it on! */
04235          break;
04236       }
04237    } else {
04238       /* Make sure we always return NULL in the future */
04239       if (!chan->_softhangup) {
04240          chan->_softhangup |= AST_SOFTHANGUP_DEV;
04241       }
04242       if (cause)
04243          chan->hangupcause = cause;
04244       if (chan->generator)
04245          ast_deactivate_generator(chan);
04246       /* We no longer End the CDR here */
04247    }
04248 
04249    /* High bit prints debugging */
04250    if (chan->fin & DEBUGCHAN_FLAG)
04251       ast_frame_dump(chan->name, f, "<<");
04252    chan->fin = FRAMECOUNT_INC(chan->fin);
04253 
04254 done:
04255    if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
04256       chan->generator->digit(chan, f->subclass.integer);
04257 
04258    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
04259       /* The list gets recreated if audiohooks are added again later */
04260       ast_audiohook_detach_list(chan->audiohooks);
04261       chan->audiohooks = NULL;
04262    }
04263    ast_channel_unlock(chan);
04264    return f;
04265 }
04266 
04267 int ast_internal_timing_enabled(struct ast_channel *chan)
04268 {
04269    return (ast_opt_internal_timing && chan->timingfd > -1);
04270 }
04271 
04272 struct ast_frame *ast_read(struct ast_channel *chan)
04273 {
04274    return __ast_read(chan, 0);
04275 }
04276 
04277 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
04278 {
04279    return __ast_read(chan, 1);
04280 }
04281 
04282 int ast_indicate(struct ast_channel *chan, int condition)
04283 {
04284    return ast_indicate_data(chan, condition, NULL, 0);
04285 }
04286 
04287 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
04288 {
04289    /* Don't include a default case here so that we get compiler warnings
04290     * when a new type is added. */
04291 
04292    switch (condition) {
04293    case AST_CONTROL_PROGRESS:
04294    case AST_CONTROL_PROCEEDING:
04295    case AST_CONTROL_VIDUPDATE:
04296    case AST_CONTROL_SRCUPDATE:
04297    case AST_CONTROL_SRCCHANGE:
04298    case AST_CONTROL_RADIO_KEY:
04299    case AST_CONTROL_RADIO_UNKEY:
04300    case AST_CONTROL_OPTION:
04301    case AST_CONTROL_WINK:
04302    case AST_CONTROL_FLASH:
04303    case AST_CONTROL_OFFHOOK:
04304    case AST_CONTROL_TAKEOFFHOOK:
04305    case AST_CONTROL_ANSWER:
04306    case AST_CONTROL_HANGUP:
04307    case AST_CONTROL_CONNECTED_LINE:
04308    case AST_CONTROL_REDIRECTING:
04309    case AST_CONTROL_TRANSFER:
04310    case AST_CONTROL_T38_PARAMETERS:
04311    case _XXX_AST_CONTROL_T38:
04312    case AST_CONTROL_CC:
04313    case AST_CONTROL_READ_ACTION:
04314    case AST_CONTROL_AOC:
04315    case AST_CONTROL_END_OF_Q:
04316    case AST_CONTROL_UPDATE_RTP_PEER:
04317       break;
04318 
04319    case AST_CONTROL_INCOMPLETE:
04320    case AST_CONTROL_CONGESTION:
04321    case AST_CONTROL_BUSY:
04322    case AST_CONTROL_RINGING:
04323    case AST_CONTROL_RING:
04324    case AST_CONTROL_HOLD:
04325       /* You can hear these */
04326       return 1;
04327 
04328    case AST_CONTROL_UNHOLD:
04329       /* This is a special case.  You stop hearing this. */
04330       break;
04331    }
04332 
04333    return 0;
04334 }
04335 
04336 int ast_indicate_data(struct ast_channel *chan, int _condition,
04337       const void *data, size_t datalen)
04338 {
04339    /* By using an enum, we'll get compiler warnings for values not handled 
04340     * in switch statements. */
04341    enum ast_control_frame_type condition = _condition;
04342    struct ast_tone_zone_sound *ts = NULL;
04343    int res;
04344    /* this frame is used by framehooks. if it is set, we must free it at the end of this function */
04345    struct ast_frame *awesome_frame = NULL;
04346 
04347    ast_channel_lock(chan);
04348 
04349    /* Don't bother if the channel is about to go away, anyway. */
04350    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
04351       res = -1;
04352       goto indicate_cleanup;
04353    }
04354 
04355    if (!ast_framehook_list_is_empty(chan->framehooks)) {
04356       /* Do framehooks now, do it, go, go now */
04357       struct ast_frame frame = {
04358          .frametype = AST_FRAME_CONTROL,
04359          .subclass.integer = condition,
04360          .data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
04361          .datalen = datalen
04362       };
04363 
04364       /* we have now committed to freeing this frame */
04365       awesome_frame = ast_frdup(&frame);
04366 
04367       /* who knows what we will get back! the anticipation is killing me. */
04368       if (!(awesome_frame = ast_framehook_list_write_event(chan->framehooks, awesome_frame))
04369          || awesome_frame->frametype != AST_FRAME_CONTROL) {
04370 
04371          res = 0;
04372          goto indicate_cleanup;
04373       }
04374 
04375       condition = awesome_frame->subclass.integer;
04376       data = awesome_frame->data.ptr;
04377       datalen = awesome_frame->datalen;
04378    }
04379 
04380    switch (condition) {
04381    case AST_CONTROL_CONNECTED_LINE:
04382       {
04383          struct ast_party_connected_line connected;
04384 
04385          ast_party_connected_line_set_init(&connected, &chan->connected);
04386          res = ast_connected_line_parse_data(data, datalen, &connected);
04387          if (!res) {
04388             ast_channel_set_connected_line(chan, &connected, NULL);
04389          }
04390          ast_party_connected_line_free(&connected);
04391       }
04392       break;
04393 
04394    case AST_CONTROL_REDIRECTING:
04395       {
04396          struct ast_party_redirecting redirecting;
04397 
04398          ast_party_redirecting_set_init(&redirecting, &chan->redirecting);
04399          res = ast_redirecting_parse_data(data, datalen, &redirecting);
04400          if (!res) {
04401             ast_channel_set_redirecting(chan, &redirecting, NULL);
04402          }
04403          ast_party_redirecting_free(&redirecting);
04404       }
04405       break;
04406    
04407    default:
04408       break;
04409    }
04410 
04411    if (is_visible_indication(condition)) {
04412       /* A new visible indication is requested. */
04413       chan->visible_indication = condition;
04414    } else if (condition == AST_CONTROL_UNHOLD || _condition < 0) {
04415       /* Visible indication is cleared/stopped. */
04416       chan->visible_indication = 0;
04417    }
04418 
04419    if (chan->tech->indicate) {
04420       /* See if the channel driver can handle this condition. */
04421       res = chan->tech->indicate(chan, condition, data, datalen);
04422    } else {
04423       res = -1;
04424    }
04425 
04426    if (!res) {
04427       /* The channel driver successfully handled this indication */
04428       res = 0;
04429       goto indicate_cleanup;
04430    }
04431 
04432    /* The channel driver does not support this indication, let's fake
04433     * it by doing our own tone generation if applicable. */
04434 
04435    /*!\note If we compare the enumeration type, which does not have any
04436     * negative constants, the compiler may optimize this code away.
04437     * Therefore, we must perform an integer comparison here. */
04438    if (_condition < 0) {
04439       /* Stop any tones that are playing */
04440       ast_playtones_stop(chan);
04441       res = 0;
04442       goto indicate_cleanup;
04443    }
04444 
04445    /* Handle conditions that we have tones for. */
04446    switch (condition) {
04447    case _XXX_AST_CONTROL_T38:
04448       /* deprecated T.38 control frame */
04449       res = -1;
04450       goto indicate_cleanup;
04451    case AST_CONTROL_T38_PARAMETERS:
04452       /* there is no way to provide 'default' behavior for these
04453        * control frames, so we need to return failure, but there
04454        * is also no value in the log message below being emitted
04455        * since failure to handle these frames is not an 'error'
04456        * so just return right now. in addition, we want to return
04457        * whatever value the channel driver returned, in case it
04458        * has some meaning.*/
04459       goto indicate_cleanup;
04460    case AST_CONTROL_RINGING:
04461       ts = ast_get_indication_tone(chan->zone, "ring");
04462       /* It is common practice for channel drivers to return -1 if trying
04463        * to indicate ringing on a channel which is up. The idea is to let the
04464        * core generate the ringing inband. However, we don't want the
04465        * warning message about not being able to handle the specific indication
04466        * to print nor do we want ast_indicate_data to return an "error" for this
04467        * condition
04468        */
04469       if (chan->_state == AST_STATE_UP) {
04470          res = 0;
04471       }
04472       break;
04473    case AST_CONTROL_BUSY:
04474       ts = ast_get_indication_tone(chan->zone, "busy");
04475       break;
04476    case AST_CONTROL_INCOMPLETE:
04477    case AST_CONTROL_CONGESTION:
04478       ts = ast_get_indication_tone(chan->zone, "congestion");
04479       break;
04480    case AST_CONTROL_PROGRESS:
04481    case AST_CONTROL_PROCEEDING:
04482    case AST_CONTROL_VIDUPDATE:
04483    case AST_CONTROL_SRCUPDATE:
04484    case AST_CONTROL_SRCCHANGE:
04485    case AST_CONTROL_RADIO_KEY:
04486    case AST_CONTROL_RADIO_UNKEY:
04487    case AST_CONTROL_OPTION:
04488    case AST_CONTROL_WINK:
04489    case AST_CONTROL_FLASH:
04490    case AST_CONTROL_OFFHOOK:
04491    case AST_CONTROL_TAKEOFFHOOK:
04492    case AST_CONTROL_ANSWER:
04493    case AST_CONTROL_HANGUP:
04494    case AST_CONTROL_RING:
04495    case AST_CONTROL_HOLD:
04496    case AST_CONTROL_UNHOLD:
04497    case AST_CONTROL_TRANSFER:
04498    case AST_CONTROL_CONNECTED_LINE:
04499    case AST_CONTROL_REDIRECTING:
04500    case AST_CONTROL_CC:
04501    case AST_CONTROL_READ_ACTION:
04502    case AST_CONTROL_AOC:
04503    case AST_CONTROL_END_OF_Q:
04504    case AST_CONTROL_UPDATE_RTP_PEER:
04505       /* Nothing left to do for these. */
04506       res = 0;
04507       break;
04508    }
04509 
04510    if (ts) {
04511       /* We have a tone to play, yay. */
04512       ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
04513       res = ast_playtones_start(chan, 0, ts->data, 1);
04514       ts = ast_tone_zone_sound_unref(ts);
04515    }
04516 
04517    if (res) {
04518       /* not handled */
04519       ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
04520    }
04521 
04522 indicate_cleanup:
04523    ast_channel_unlock(chan);
04524    if (awesome_frame) {
04525       ast_frfree(awesome_frame);
04526    }
04527 
04528    return res;
04529 }
04530 
04531 int ast_recvchar(struct ast_channel *chan, int timeout)
04532 {
04533    int c;
04534    char *buf = ast_recvtext(chan, timeout);
04535    if (buf == NULL)
04536       return -1;  /* error or timeout */
04537    c = *(unsigned char *)buf;
04538    ast_free(buf);
04539    return c;
04540 }
04541 
04542 char *ast_recvtext(struct ast_channel *chan, int timeout)
04543 {
04544    int res, done = 0;
04545    char *buf = NULL;
04546    
04547    while (!done) {
04548       struct ast_frame *f;
04549       if (ast_check_hangup(chan))
04550          break;
04551       res = ast_waitfor(chan, timeout);
04552       if (res <= 0) /* timeout or error */
04553          break;
04554       timeout = res; /* update timeout */
04555       f = ast_read(chan);
04556       if (f == NULL)
04557          break; /* no frame */
04558       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP)
04559          done = 1;   /* force a break */
04560       else if (f->frametype == AST_FRAME_TEXT) {      /* what we want */
04561          buf = ast_strndup((char *) f->data.ptr, f->datalen);  /* dup and break */
04562          done = 1;
04563       }
04564       ast_frfree(f);
04565    }
04566    return buf;
04567 }
04568 
04569 int ast_sendtext(struct ast_channel *chan, const char *text)
04570 {
04571    int res = 0;
04572 
04573    ast_channel_lock(chan);
04574    /* Stop if we're a zombie or need a soft hangup */
04575    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
04576       ast_channel_unlock(chan);
04577       return -1;
04578    }
04579    CHECK_BLOCKING(chan);
04580    if (chan->tech->send_text)
04581       res = chan->tech->send_text(chan, text);
04582    ast_clear_flag(chan, AST_FLAG_BLOCKING);
04583    ast_channel_unlock(chan);
04584    return res;
04585 }
04586 
04587 int ast_senddigit_begin(struct ast_channel *chan, char digit)
04588 {
04589    /* Device does not support DTMF tones, lets fake
04590     * it by doing our own generation. */
04591    static const char * const dtmf_tones[] = {
04592       "941+1336", /* 0 */
04593       "697+1209", /* 1 */
04594       "697+1336", /* 2 */
04595       "697+1477", /* 3 */
04596       "770+1209", /* 4 */
04597       "770+1336", /* 5 */
04598       "770+1477", /* 6 */
04599       "852+1209", /* 7 */
04600       "852+1336", /* 8 */
04601       "852+1477", /* 9 */
04602       "697+1633", /* A */
04603       "770+1633", /* B */
04604       "852+1633", /* C */
04605       "941+1633", /* D */
04606       "941+1209", /* * */
04607       "941+1477"  /* # */
04608    };
04609 
04610    if (!chan->tech->send_digit_begin)
04611       return 0;
04612 
04613    if (!chan->tech->send_digit_begin(chan, digit))
04614       return 0;
04615 
04616    if (digit >= '0' && digit <='9')
04617       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
04618    else if (digit >= 'A' && digit <= 'D')
04619       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
04620    else if (digit == '*')
04621       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
04622    else if (digit == '#')
04623       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
04624    else {
04625       /* not handled */
04626       ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
04627    }
04628 
04629    return 0;
04630 }
04631 
04632 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
04633 {
04634    int res = -1;
04635 
04636    if (chan->tech->send_digit_end)
04637       res = chan->tech->send_digit_end(chan, digit, duration);
04638 
04639    if (res && chan->generator)
04640       ast_playtones_stop(chan);
04641    
04642    return 0;
04643 }
04644 
04645 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
04646 {
04647    if (chan->tech->send_digit_begin) {
04648       ast_senddigit_begin(chan, digit);
04649       ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04650    }
04651    
04652    return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04653 }
04654 
04655 int ast_prod(struct ast_channel *chan)
04656 {
04657    struct ast_frame a = { AST_FRAME_VOICE };
04658    char nothing[128];
04659 
04660    /* Send an empty audio frame to get things moving */
04661    if (chan->_state != AST_STATE_UP) {
04662       ast_debug(1, "Prodding channel '%s'\n", chan->name);
04663       a.subclass.codec = chan->rawwriteformat;
04664       a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
04665       a.src = "ast_prod"; /* this better match check in ast_write */
04666       if (ast_write(chan, &a))
04667          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
04668    }
04669    return 0;
04670 }
04671 
04672 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
04673 {
04674    int res;
04675    if (!chan->tech->write_video)
04676       return 0;
04677    res = ast_write(chan, fr);
04678    if (!res)
04679       res = 1;
04680    return res;
04681 }
04682 
04683 struct plc_ds {
04684    /* A buffer in which to store SLIN PLC
04685     * samples generated by the generic PLC
04686     * functionality in plc.c
04687     */
04688    int16_t *samples_buf;
04689    /* The current number of samples in the
04690     * samples_buf
04691     */
04692    size_t num_samples;
04693    plc_state_t plc_state;
04694 };
04695 
04696 static void plc_ds_destroy(void *data)
04697 {
04698    struct plc_ds *plc = data;
04699    ast_free(plc->samples_buf);
04700    ast_free(plc);
04701 }
04702 
04703 static struct ast_datastore_info plc_ds_info = {
04704    .type = "plc",
04705    .destroy = plc_ds_destroy,
04706 };
04707 
04708 static void adjust_frame_for_plc(struct ast_channel *chan, struct ast_frame *frame, struct ast_datastore *datastore)
04709 {
04710    int num_new_samples = frame->samples;
04711    struct plc_ds *plc = datastore->data;
04712 
04713    /* As a general note, let me explain the somewhat odd calculations used when taking
04714     * the frame offset into account here. According to documentation in frame.h, the frame's
04715     * offset field indicates the number of bytes that the audio is offset. The plc->samples_buf
04716     * is not an array of bytes, but rather an array of 16-bit integers since it holds SLIN
04717     * samples. So I had two choices to make here with the offset.
04718     * 
04719     * 1. Make the offset AST_FRIENDLY_OFFSET bytes. The main downside for this is that
04720     *    I can't just add AST_FRIENDLY_OFFSET to the plc->samples_buf and have the pointer
04721     *    arithmetic come out right. I would have to do some odd casting or division for this to
04722     *    work as I wanted.
04723     * 2. Make the offset AST_FRIENDLY_OFFSET * 2 bytes. This allows the pointer arithmetic
04724     *    to work out better with the plc->samples_buf. The downside here is that the buffer's
04725     *    allocation contains an extra 64 bytes of unused space.
04726     * 
04727     * I decided to go with option 2. This is why in the calloc statement and the statement that
04728     * sets the frame's offset, AST_FRIENDLY_OFFSET is multiplied by 2.
04729     */
04730 
04731    /* If this audio frame has no samples to fill in, ignore it */
04732    if (!num_new_samples) {
04733       return;
04734    }
04735 
04736    /* First, we need to be sure that our buffer is large enough to accomodate
04737     * the samples we need to fill in. This will likely only occur on the first
04738     * frame we write.
04739     */
04740    if (plc->num_samples < num_new_samples) {
04741       ast_free(plc->samples_buf);
04742       plc->samples_buf = ast_calloc(1, (num_new_samples * sizeof(*plc->samples_buf)) + (AST_FRIENDLY_OFFSET * 2));
04743       if (!plc->samples_buf) {
04744          ast_channel_datastore_remove(chan, datastore);
04745          ast_datastore_free(datastore);
04746          return;
04747       }
04748       plc->num_samples = num_new_samples;
04749    }
04750 
04751    if (frame->datalen == 0) {
04752       plc_fillin(&plc->plc_state, plc->samples_buf + AST_FRIENDLY_OFFSET, frame->samples);
04753       frame->data.ptr = plc->samples_buf + AST_FRIENDLY_OFFSET;
04754       frame->datalen = num_new_samples * 2;
04755       frame->offset = AST_FRIENDLY_OFFSET * 2;
04756    } else {
04757       plc_rx(&plc->plc_state, frame->data.ptr, frame->samples);
04758    }
04759 }
04760 
04761 static void apply_plc(struct ast_channel *chan, struct ast_frame *frame)
04762 {
04763    struct ast_datastore *datastore;
04764    struct plc_ds *plc;
04765 
04766    datastore = ast_channel_datastore_find(chan, &plc_ds_info, NULL);
04767    if (datastore) {
04768       plc = datastore->data;
04769       adjust_frame_for_plc(chan, frame, datastore);
04770       return;
04771    }
04772 
04773    datastore = ast_datastore_alloc(&plc_ds_info, NULL);
04774    if (!datastore) {
04775       return;
04776    }
04777    plc = ast_calloc(1, sizeof(*plc));
04778    if (!plc) {
04779       ast_datastore_free(datastore);
04780       return;
04781    }
04782    datastore->data = plc;
04783    ast_channel_datastore_add(chan, datastore);
04784    adjust_frame_for_plc(chan, frame, datastore);
04785 }
04786 
04787 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
04788 {
04789    int res = -1;
04790    struct ast_frame *f = NULL;
04791    int count = 0;
04792 
04793    /*Deadlock avoidance*/
04794    while(ast_channel_trylock(chan)) {
04795       /*cannot goto done since the channel is not locked*/
04796       if(count++ > 10) {
04797          ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
04798          return 0;
04799       }
04800       usleep(1);
04801    }
04802    /* Stop if we're a zombie or need a soft hangup */
04803    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
04804       goto done;
04805 
04806    /* Handle any pending masquerades */
04807    if (chan->masq) {
04808       ast_channel_unlock(chan);
04809       if (ast_do_masquerade(chan)) {
04810          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
04811          return res; /* no need to goto done: chan is already unlocked for masq */
04812       }
04813       ast_channel_lock(chan);
04814    }
04815    if (chan->masqr) {
04816       res = 0; /* XXX explain, why 0 ? */
04817       goto done;
04818    }
04819 
04820    /* Perform the framehook write event here. After the frame enters the framehook list
04821     * there is no telling what will happen, how awesome is that!!! */
04822    if (!(fr = ast_framehook_list_write_event(chan->framehooks, fr))) {
04823       res = 0;
04824       goto done;
04825    }
04826 
04827    if (chan->generatordata && (!fr->src || strcasecmp(fr->src, "ast_prod"))) {
04828       if (ast_test_flag(chan, AST_FLAG_WRITE_INT)) {
04829             ast_deactivate_generator(chan);
04830       } else {
04831          if (fr->frametype == AST_FRAME_DTMF_END) {
04832             /* There is a generator running while we're in the middle of a digit.
04833              * It's probably inband DTMF, so go ahead and pass it so it can
04834              * stop the generator */
04835             ast_clear_flag(chan, AST_FLAG_BLOCKING);
04836             ast_channel_unlock(chan);
04837             res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
04838             ast_channel_lock(chan);
04839             CHECK_BLOCKING(chan);
04840          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_UNHOLD) {
04841             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
04842             res = (chan->tech->indicate == NULL) ? 0 :
04843                chan->tech->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
04844          }
04845          res = 0; /* XXX explain, why 0 ? */
04846          goto done;
04847       }
04848    }
04849    /* High bit prints debugging */
04850    if (chan->fout & DEBUGCHAN_FLAG)
04851       ast_frame_dump(chan->name, fr, ">>");
04852    CHECK_BLOCKING(chan);
04853    switch (fr->frametype) {
04854    case AST_FRAME_CONTROL:
04855       res = (chan->tech->indicate == NULL) ? 0 :
04856          chan->tech->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
04857       break;
04858    case AST_FRAME_DTMF_BEGIN:
04859       if (chan->audiohooks) {
04860          struct ast_frame *old_frame = fr;
04861          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
04862          if (old_frame != fr)
04863             f = fr;
04864       }
04865       send_dtmf_event(chan, "Sent", fr->subclass.integer, "Yes", "No");
04866       ast_clear_flag(chan, AST_FLAG_BLOCKING);
04867       ast_channel_unlock(chan);
04868       res = ast_senddigit_begin(chan, fr->subclass.integer);
04869       ast_channel_lock(chan);
04870       CHECK_BLOCKING(chan);
04871       break;
04872    case AST_FRAME_DTMF_END:
04873       if (chan->audiohooks) {
04874          struct ast_frame *new_frame = fr;
04875 
04876          new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
04877          if (new_frame != fr) {
04878             ast_frfree(new_frame);
04879          }
04880       }
04881       send_dtmf_event(chan, "Sent", fr->subclass.integer, "No", "Yes");
04882       ast_clear_flag(chan, AST_FLAG_BLOCKING);
04883       ast_channel_unlock(chan);
04884       res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
04885       ast_channel_lock(chan);
04886       CHECK_BLOCKING(chan);
04887       break;
04888    case AST_FRAME_TEXT:
04889       if (fr->subclass.integer == AST_FORMAT_T140) {
04890          res = (chan->tech->write_text == NULL) ? 0 :
04891             chan->tech->write_text(chan, fr);
04892       } else {
04893          res = (chan->tech->send_text == NULL) ? 0 :
04894             chan->tech->send_text(chan, (char *) fr->data.ptr);
04895       }
04896       break;
04897    case AST_FRAME_HTML:
04898       res = (chan->tech->send_html == NULL) ? 0 :
04899          chan->tech->send_html(chan, fr->subclass.integer, (char *) fr->data.ptr, fr->datalen);
04900       break;
04901    case AST_FRAME_VIDEO:
04902       /* XXX Handle translation of video codecs one day XXX */
04903       res = (chan->tech->write_video == NULL) ? 0 :
04904          chan->tech->write_video(chan, fr);
04905       break;
04906    case AST_FRAME_MODEM:
04907       res = (chan->tech->write == NULL) ? 0 :
04908          chan->tech->write(chan, fr);
04909       break;
04910    case AST_FRAME_VOICE:
04911       if (chan->tech->write == NULL)
04912          break;   /*! \todo XXX should return 0 maybe ? */
04913 
04914       if (ast_opt_generic_plc && fr->subclass.codec == AST_FORMAT_SLINEAR) {
04915          apply_plc(chan, fr);
04916       }
04917 
04918       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
04919       if (fr->subclass.codec == chan->rawwriteformat) {
04920          f = fr;
04921       } else {
04922          if ((!(fr->subclass.codec & chan->nativeformats)) && (chan->writeformat != fr->subclass.codec)) {
04923             char nf[512];
04924 
04925             /*
04926              * XXX Something is not right.  We are not compatible with this
04927              * frame.  Bad things can happen.  Problems range from no audio,
04928              * one-way audio, to unexplained line hangups.  As a last resort
04929              * try to adjust the format.  Ideally, we do not want to do this
04930              * because it indicates a deeper problem.  For now, we log these
04931              * events to reduce user impact and help identify the problem
04932              * areas.
04933              */
04934             ast_log(LOG_WARNING, "Codec mismatch on channel %s setting write format to %s from %s native formats %s\n",
04935                chan->name, ast_getformatname(fr->subclass.codec), ast_getformatname(chan->writeformat),
04936                ast_getformatname_multiple(nf, sizeof(nf), chan->nativeformats & AST_FORMAT_AUDIO_MASK));
04937             ast_set_write_format(chan, fr->subclass.codec);
04938          }
04939 
04940          f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
04941       }
04942 
04943       if (!f) {
04944          res = 0;
04945          break;
04946       }
04947 
04948       if (chan->audiohooks) {
04949          struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
04950          int freeoldlist = 0;
04951 
04952          if (f != fr) {
04953             freeoldlist = 1;
04954          }
04955 
04956          /* Since ast_audiohook_write may return a new frame, and the cur frame is
04957           * an item in a list of frames, create a new list adding each cur frame back to it
04958           * regardless if the cur frame changes or not. */
04959          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
04960             new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, cur);
04961 
04962             /* if this frame is different than cur, preserve the end of the list,
04963              * free the old frames, and set cur to be the new frame */
04964             if (new_frame != cur) {
04965 
04966                /* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
04967                 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
04968                 * times it may override the previous frame we got from it unless we dup it */
04969                if ((dup = ast_frisolate(new_frame))) {
04970                   AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
04971                   if (freeoldlist) {
04972                      AST_LIST_NEXT(cur, frame_list) = NULL;
04973                      ast_frfree(cur);
04974                   }
04975                   if (new_frame != dup) {
04976                      ast_frfree(new_frame);
04977                   }
04978                   cur = dup;
04979                }
04980             }
04981 
04982             /* now, regardless if cur is new or not, add it to the new list,
04983              * if the new list has not started, cur will become the first item. */
04984             if (prev) {
04985                AST_LIST_NEXT(prev, frame_list) = cur;
04986             } else {
04987                f = cur; /* set f to be the beginning of our new list */
04988             }
04989             prev = cur;
04990          }
04991       }
04992       
04993       /* If Monitor is running on this channel, then we have to write frames out there too */
04994       /* the translator on chan->writetrans may have returned multiple frames
04995          from the single frame we passed in; if so, feed each one of them to the
04996          monitor */
04997       if (chan->monitor && chan->monitor->write_stream) {
04998          struct ast_frame *cur;
04999 
05000          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
05001          /* XXX must explain this code */
05002 #ifndef MONITOR_CONSTANT_DELAY
05003             int jump = chan->insmpl - chan->outsmpl - 4 * cur->samples;
05004             if (jump >= 0) {
05005                jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
05006                if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
05007                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
05008                chan->outsmpl += (chan->insmpl - chan->outsmpl) + cur->samples;
05009             } else {
05010                chan->outsmpl += cur->samples;
05011             }
05012 #else
05013             int jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass.codec), ast_format_rate(chan->monitor->read_stream->fmt->format));
05014             if (jump - MONITOR_DELAY >= 0) {
05015                if (ast_seekstream(chan->monitor->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1)
05016                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
05017                chan->outsmpl += chan->insmpl - chan->outsmpl;
05018             } else {
05019                chan->outsmpl += cur->samples;
05020             }
05021 #endif
05022             if (chan->monitor->state == AST_MONITOR_RUNNING) {
05023                if (ast_writestream(chan->monitor->write_stream, cur) < 0)
05024                   ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
05025             }
05026          }
05027       }
05028 
05029       /* the translator on chan->writetrans may have returned multiple frames
05030          from the single frame we passed in; if so, feed each one of them to the
05031          channel, freeing each one after it has been written */
05032       if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
05033          struct ast_frame *cur, *next;
05034          unsigned int skip = 0;
05035 
05036          for (cur = f, next = AST_LIST_NEXT(cur, frame_list);
05037               cur;
05038               cur = next, next = cur ? AST_LIST_NEXT(cur, frame_list) : NULL) {
05039             if (!skip) {
05040                if ((res = chan->tech->write(chan, cur)) < 0) {
05041                   chan->_softhangup |= AST_SOFTHANGUP_DEV;
05042                   skip = 1;
05043                } else if (next) {
05044                   /* don't do this for the last frame in the list,
05045                      as the code outside the loop will do it once
05046                   */
05047                   chan->fout = FRAMECOUNT_INC(chan->fout);
05048                }
05049             }
05050             ast_frfree(cur);
05051          }
05052 
05053          /* reset f so the code below doesn't attempt to free it */
05054          f = NULL;
05055       } else {
05056          res = chan->tech->write(chan, f);
05057       }
05058       break;
05059    case AST_FRAME_NULL:
05060    case AST_FRAME_IAX:
05061       /* Ignore these */
05062       res = 0;
05063       break;
05064    default:
05065       /* At this point, fr is the incoming frame and f is NULL.  Channels do
05066        * not expect to get NULL as a frame pointer and will segfault.  Hence,
05067        * we output the original frame passed in. */
05068       res = chan->tech->write(chan, fr);
05069       break;
05070    }
05071 
05072    if (f && f != fr)
05073       ast_frfree(f);
05074    ast_clear_flag(chan, AST_FLAG_BLOCKING);
05075 
05076    /* Consider a write failure to force a soft hangup */
05077    if (res < 0) {
05078       chan->_softhangup |= AST_SOFTHANGUP_DEV;
05079    } else {
05080       chan->fout = FRAMECOUNT_INC(chan->fout);
05081    }
05082 done:
05083    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
05084       /* The list gets recreated if audiohooks are added again later */
05085       ast_audiohook_detach_list(chan->audiohooks);
05086       chan->audiohooks = NULL;
05087    }
05088    ast_channel_unlock(chan);
05089    return res;
05090 }
05091 
05092 static int set_format(struct ast_channel *chan, format_t fmt, format_t *rawformat, format_t *format,
05093             struct ast_trans_pvt **trans, const int direction)
05094 {
05095    format_t native, native_fmt = ast_best_codec(fmt);
05096    int res;
05097    char from[200], to[200];
05098    
05099    /* Make sure we only consider audio */
05100    fmt &= AST_FORMAT_AUDIO_MASK;
05101    
05102    native = chan->nativeformats;
05103 
05104    if (!fmt || !native) /* No audio requested */
05105       return 0;   /* Let's try a call without any sounds (video, text) */
05106 
05107    /* See if the underlying channel driver is capable of performing transcoding for us */
05108    if (!ast_channel_setoption(chan, direction ? AST_OPTION_FORMAT_WRITE : AST_OPTION_FORMAT_READ, &native_fmt, sizeof(int*), 0)) {
05109       ast_debug(1, "Channel driver natively set channel %s to %s format %s\n", chan->name,
05110            direction ? "write" : "read", ast_getformatname(native_fmt));
05111       chan->nativeformats = *rawformat = *format = native_fmt;
05112       if (*trans) {
05113          ast_translator_free_path(*trans);
05114       }
05115       *trans = NULL;
05116       return 0;
05117    }
05118 
05119    /* Find a translation path from the native format to one of the desired formats */
05120    if (!direction)
05121       /* reading */
05122       res = ast_translator_best_choice(&fmt, &native);
05123    else
05124       /* writing */
05125       res = ast_translator_best_choice(&native, &fmt);
05126 
05127    if (res < 0) {
05128       ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
05129          ast_getformatname_multiple(from, sizeof(from), native),
05130          ast_getformatname_multiple(to, sizeof(to), fmt));
05131       return -1;
05132    }
05133    
05134    /* Now we have a good choice for both. */
05135    ast_channel_lock(chan);
05136 
05137    if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
05138       /* the channel is already in these formats, so nothing to do */
05139       ast_channel_unlock(chan);
05140       return 0;
05141    }
05142 
05143    *rawformat = native;
05144    /* User perspective is fmt */
05145    *format = fmt;
05146    /* Free any read translation we have right now */
05147    if (*trans) {
05148       ast_translator_free_path(*trans);
05149       *trans = NULL;
05150    }
05151    /* Build a translation path from the raw format to the desired format */
05152    if (*format == *rawformat) {
05153       /*
05154        * If we were able to swap the native format to the format that
05155        * has been requested, then there is no need to try to build
05156        * a translation path.
05157        */
05158       res = 0;
05159    } else {
05160       if (!direction) {
05161          /* reading */
05162          *trans = ast_translator_build_path(*format, *rawformat);
05163       } else {
05164          /* writing */
05165          *trans = ast_translator_build_path(*rawformat, *format);
05166       }
05167       res = *trans ? 0 : -1;
05168    }
05169    ast_channel_unlock(chan);
05170    ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
05171       direction ? "write" : "read", ast_getformatname(fmt));
05172    return res;
05173 }
05174 
05175 int ast_set_read_format(struct ast_channel *chan, format_t fmt)
05176 {
05177    return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
05178            &chan->readtrans, 0);
05179 }
05180 
05181 int ast_set_write_format(struct ast_channel *chan, format_t fmt)
05182 {
05183    return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
05184            &chan->writetrans, 1);
05185 }
05186 
05187 const char *ast_channel_reason2str(int reason)
05188 {
05189    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
05190    {
05191    case 0:
05192       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
05193    case AST_CONTROL_HANGUP:
05194       return "Hangup";
05195    case AST_CONTROL_RING:
05196       return "Local Ring";
05197    case AST_CONTROL_RINGING:
05198       return "Remote end Ringing";
05199    case AST_CONTROL_ANSWER:
05200       return "Remote end has Answered";
05201    case AST_CONTROL_BUSY:
05202       return "Remote end is Busy";
05203    case AST_CONTROL_CONGESTION:
05204       return "Congestion (circuits busy)";
05205    default:
05206       return "Unknown Reason!!";
05207    }
05208 }
05209 
05210 static void handle_cause(int cause, int *outstate)
05211 {
05212    if (outstate) {
05213       /* compute error and return */
05214       if (cause == AST_CAUSE_BUSY)
05215          *outstate = AST_CONTROL_BUSY;
05216       else if (cause == AST_CAUSE_CONGESTION)
05217          *outstate = AST_CONTROL_CONGESTION;
05218       else
05219          *outstate = 0;
05220    }
05221 }
05222 
05223 /*!
05224  * \internal
05225  * \brief Helper function to inherit info from parent channel.
05226  *
05227  * \param new_chan Channel inheriting information.
05228  * \param parent Channel new_chan inherits information.
05229  * \param orig Channel being replaced by the call forward channel.
05230  *
05231  * \return Nothing
05232  */
05233 static void call_forward_inherit(struct ast_channel *new_chan, struct ast_channel *parent, struct ast_channel *orig)
05234 {
05235    if (!ast_test_flag(parent, AST_FLAG_ZOMBIE) && !ast_check_hangup(parent)) {
05236       struct ast_party_redirecting redirecting;
05237 
05238       /*
05239        * The parent is not a ZOMBIE or hungup so update it with the
05240        * original channel's redirecting information.
05241        */
05242       ast_party_redirecting_init(&redirecting);
05243       ast_channel_lock(orig);
05244       ast_party_redirecting_copy(&redirecting, &orig->redirecting);
05245       ast_channel_unlock(orig);
05246       if (ast_channel_redirecting_macro(orig, parent, &redirecting, 1, 0)) {
05247          ast_channel_update_redirecting(parent, &redirecting, NULL);
05248       }
05249       ast_party_redirecting_free(&redirecting);
05250    }
05251 
05252    /* Safely inherit variables and datastores from the parent channel. */
05253    ast_channel_lock_both(parent, new_chan);
05254    ast_channel_inherit_variables(parent, new_chan);
05255    ast_channel_datastore_inherit(parent, new_chan);
05256    ast_channel_unlock(new_chan);
05257    ast_channel_unlock(parent);
05258 }
05259 
05260 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)
05261 {
05262    char tmpchan[256];
05263    struct ast_channel *new_chan = NULL;
05264    char *data, *type;
05265    int cause = 0;
05266    int res;
05267 
05268    /* gather data and request the new forward channel */
05269    ast_copy_string(tmpchan, orig->call_forward, sizeof(tmpchan));
05270    if ((data = strchr(tmpchan, '/'))) {
05271       *data++ = '\0';
05272       type = tmpchan;
05273    } else {
05274       const char *forward_context;
05275       ast_channel_lock(orig);
05276       forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
05277       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", orig->call_forward, S_OR(forward_context, orig->context));
05278       ast_channel_unlock(orig);
05279       data = tmpchan;
05280       type = "Local";
05281    }
05282    if (!(new_chan = ast_request(type, format, orig, data, &cause))) {
05283       ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
05284       handle_cause(cause, outstate);
05285       ast_hangup(orig);
05286       return NULL;
05287    }
05288 
05289    /* Copy/inherit important information into new channel */
05290    if (oh) {
05291       if (oh->vars) {
05292          ast_set_variables(new_chan, oh->vars);
05293       }
05294       if (oh->parent_channel) {
05295          call_forward_inherit(new_chan, oh->parent_channel, orig);
05296       }
05297       if (oh->account) {
05298          ast_channel_lock(new_chan);
05299          ast_cdr_setaccount(new_chan, oh->account);
05300          ast_channel_unlock(new_chan);
05301       }
05302    } else if (caller) { /* no outgoing helper so use caller if avaliable */
05303       call_forward_inherit(new_chan, caller, orig);
05304    }
05305 
05306    ast_channel_lock_both(orig, new_chan);
05307    ast_copy_flags(new_chan->cdr, orig->cdr, AST_CDR_FLAG_ORIGINATED);
05308    ast_string_field_set(new_chan, accountcode, orig->accountcode);
05309    ast_party_connected_line_copy(&new_chan->connected, &orig->connected);
05310    ast_party_redirecting_copy(&new_chan->redirecting, &orig->redirecting);
05311    ast_channel_unlock(new_chan);
05312    ast_channel_unlock(orig);
05313 
05314    /* call new channel */
05315    res = ast_call(new_chan, data, 0);
05316    if (timeout) {
05317       *timeout = res;
05318    }
05319    if (res) {
05320       ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
05321       ast_hangup(orig);
05322       ast_hangup(new_chan);
05323       return NULL;
05324    }
05325    ast_hangup(orig);
05326 
05327    return new_chan;
05328 }
05329 
05330 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)
05331 {
05332    int dummy_outstate;
05333    int cause = 0;
05334    struct ast_channel *chan;
05335    int res = 0;
05336    int last_subclass = 0;
05337    struct ast_party_connected_line connected;
05338    
05339    if (outstate)
05340       *outstate = 0;
05341    else
05342       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
05343 
05344    chan = ast_request(type, format, requestor, data, &cause);
05345    if (!chan) {
05346       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
05347       handle_cause(cause, outstate);
05348       return NULL;
05349    }
05350 
05351    if (oh) {
05352       if (oh->vars) {
05353          ast_set_variables(chan, oh->vars);
05354       }
05355       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
05356          /*
05357           * Use the oh values instead of the function parameters for the
05358           * outgoing CallerID.
05359           */
05360          cid_num = oh->cid_num;
05361          cid_name = oh->cid_name;
05362       }
05363       if (oh->parent_channel) {
05364          /* Safely inherit variables and datastores from the parent channel. */
05365          ast_channel_lock_both(oh->parent_channel, chan);
05366          ast_channel_inherit_variables(oh->parent_channel, chan);
05367          ast_channel_datastore_inherit(oh->parent_channel, chan);
05368          ast_channel_unlock(oh->parent_channel);
05369          ast_channel_unlock(chan);
05370       }
05371       if (oh->account) {
05372          ast_channel_lock(chan);
05373          ast_cdr_setaccount(chan, oh->account);
05374          ast_channel_unlock(chan);
05375       }
05376    }
05377 
05378    /*
05379     * I seems strange to set the CallerID on an outgoing call leg
05380     * to whom we are calling, but this function's callers are doing
05381     * various Originate methods.  This call leg goes to the local
05382     * user.  Once the local user answers, the dialplan needs to be
05383     * able to access the CallerID from the CALLERID function as if
05384     * the local user had placed this call.
05385     */
05386    ast_set_callerid(chan, cid_num, cid_name, cid_num);
05387 
05388    ast_set_flag(chan->cdr, AST_CDR_FLAG_ORIGINATED);
05389    ast_party_connected_line_set_init(&connected, &chan->connected);
05390    if (cid_num) {
05391       connected.id.number.valid = 1;
05392       connected.id.number.str = (char *) cid_num;
05393       connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05394    }
05395    if (cid_name) {
05396       connected.id.name.valid = 1;
05397       connected.id.name.str = (char *) cid_name;
05398       connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05399    }
05400    ast_channel_set_connected_line(chan, &connected, NULL);
05401 
05402    if (ast_call(chan, data, 0)) {   /* ast_call failed... */
05403       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
05404    } else {
05405       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
05406       while (timeout && chan->_state != AST_STATE_UP) {
05407          struct ast_frame *f;
05408          res = ast_waitfor(chan, timeout);
05409          if (res == 0) { /* timeout, treat it like ringing */
05410             *outstate = AST_CONTROL_RINGING;
05411             break;
05412          }
05413          if (res < 0) /* error or done */
05414             break;
05415          if (timeout > -1)
05416             timeout = res;
05417          if (!ast_strlen_zero(chan->call_forward)) {
05418             if (!(chan = ast_call_forward(NULL, chan, NULL, format, oh, outstate))) {
05419                return NULL;
05420             }
05421             continue;
05422          }
05423 
05424          f = ast_read(chan);
05425          if (!f) {
05426             *outstate = AST_CONTROL_HANGUP;
05427             res = 0;
05428             break;
05429          }
05430          if (f->frametype == AST_FRAME_CONTROL) {
05431             switch (f->subclass.integer) {
05432             case AST_CONTROL_RINGING:  /* record but keep going */
05433                *outstate = f->subclass.integer;
05434                break;
05435 
05436             case AST_CONTROL_BUSY:
05437                ast_cdr_busy(chan->cdr);
05438                *outstate = f->subclass.integer;
05439                timeout = 0;
05440                break;
05441 
05442             case AST_CONTROL_INCOMPLETE:
05443                ast_cdr_failed(chan->cdr);
05444                *outstate = AST_CONTROL_CONGESTION;
05445                timeout = 0;
05446                break;
05447 
05448             case AST_CONTROL_CONGESTION:
05449                ast_cdr_failed(chan->cdr);
05450                *outstate = f->subclass.integer;
05451                timeout = 0;
05452                break;
05453 
05454             case AST_CONTROL_ANSWER:
05455                ast_cdr_answer(chan->cdr);
05456                *outstate = f->subclass.integer;
05457                timeout = 0;      /* trick to force exit from the while() */
05458                break;
05459 
05460             /* Ignore these */
05461             case AST_CONTROL_PROGRESS:
05462             case AST_CONTROL_PROCEEDING:
05463             case AST_CONTROL_HOLD:
05464             case AST_CONTROL_UNHOLD:
05465             case AST_CONTROL_VIDUPDATE:
05466             case AST_CONTROL_SRCUPDATE:
05467             case AST_CONTROL_SRCCHANGE:
05468             case AST_CONTROL_CONNECTED_LINE:
05469             case AST_CONTROL_REDIRECTING:
05470             case AST_CONTROL_CC:
05471             case -1:       /* Ignore -- just stopping indications */
05472                break;
05473 
05474             default:
05475                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass.integer);
05476             }
05477             last_subclass = f->subclass.integer;
05478          }
05479          ast_frfree(f);
05480       }
05481    }
05482 
05483    /* Final fixups */
05484    if (oh) {
05485       if (!ast_strlen_zero(oh->context))
05486          ast_copy_string(chan->context, oh->context, sizeof(chan->context));
05487       if (!ast_strlen_zero(oh->exten))
05488          ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
05489       if (oh->priority) 
05490          chan->priority = oh->priority;
05491    }
05492    if (chan->_state == AST_STATE_UP)
05493       *outstate = AST_CONTROL_ANSWER;
05494 
05495    if (res <= 0) {
05496       ast_channel_lock(chan);
05497       if (AST_CONTROL_RINGING == last_subclass) {
05498          chan->hangupcause = AST_CAUSE_NO_ANSWER;
05499       }
05500       if (!chan->cdr && (chan->cdr = ast_cdr_alloc())) {
05501          ast_cdr_init(chan->cdr, chan);
05502       }
05503       if (chan->cdr) {
05504          char tmp[256];
05505 
05506          snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
05507          ast_cdr_setapp(chan->cdr, "Dial", tmp);
05508          ast_cdr_update(chan);
05509          ast_cdr_start(chan->cdr);
05510          ast_cdr_end(chan->cdr);
05511          /* If the cause wasn't handled properly */
05512          if (ast_cdr_disposition(chan->cdr, chan->hangupcause)) {
05513             ast_cdr_failed(chan->cdr);
05514          }
05515       }
05516       ast_channel_unlock(chan);
05517       ast_hangup(chan);
05518       chan = NULL;
05519    }
05520    return chan;
05521 }
05522 
05523 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)
05524 {
05525    return __ast_request_and_dial(type, format, requestor, data, timeout, outstate, cidnum, cidname, NULL);
05526 }
05527 
05528 static int set_security_requirements(const struct ast_channel *requestor, struct ast_channel *out)
05529 {
05530    int ops[2][2] = {
05531       {AST_OPTION_SECURE_SIGNALING, 0},
05532       {AST_OPTION_SECURE_MEDIA, 0},
05533    };
05534    int i;
05535    struct ast_channel *r = (struct ast_channel *) requestor; /* UGLY */
05536    struct ast_datastore *ds;
05537 
05538    if (!requestor || !out) {
05539       return 0;
05540    }
05541 
05542    ast_channel_lock(r);
05543    if ((ds = ast_channel_datastore_find(r, &secure_call_info, NULL))) {
05544       struct ast_secure_call_store *encrypt = ds->data;
05545       ops[0][1] = encrypt->signaling;
05546       ops[1][1] = encrypt->media;
05547    } else {
05548       ast_channel_unlock(r);
05549       return 0;
05550    }
05551    ast_channel_unlock(r);
05552 
05553    for (i = 0; i < 2; i++) {
05554       if (ops[i][1]) {
05555          if (ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0)) {
05556             /* We require a security feature, but the channel won't provide it */
05557             return -1;
05558          }
05559       } else {
05560          /* We don't care if we can't clear the option on a channel that doesn't support it */
05561          ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0);
05562       }
05563    }
05564 
05565    return 0;
05566 }
05567 
05568 struct ast_channel *ast_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
05569 {
05570    struct chanlist *chan;
05571    struct ast_channel *c;
05572    format_t capabilities;
05573    format_t fmt;
05574    int res;
05575    int foo;
05576    format_t videoformat = format & AST_FORMAT_VIDEO_MASK;
05577    format_t textformat = format & AST_FORMAT_TEXT_MASK;
05578 
05579    if (!cause)
05580       cause = &foo;
05581    *cause = AST_CAUSE_NOTDEFINED;
05582 
05583    if (AST_RWLIST_RDLOCK(&backends)) {
05584       ast_log(LOG_WARNING, "Unable to lock technology backend list\n");
05585       return NULL;
05586    }
05587 
05588    AST_RWLIST_TRAVERSE(&backends, chan, list) {
05589       if (strcasecmp(type, chan->tech->type))
05590          continue;
05591 
05592       capabilities = chan->tech->capabilities;
05593       fmt = format & AST_FORMAT_AUDIO_MASK;
05594       if (fmt) {
05595          /* We have audio - is it possible to connect the various calls to each other? 
05596             (Avoid this check for calls without audio, like text+video calls)
05597          */
05598          res = ast_translator_best_choice(&fmt, &capabilities);
05599          if (res < 0) {
05600             char tmp1[256], tmp2[256];
05601             ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %s) to %s\n", type,
05602                ast_getformatname_multiple(tmp1, sizeof(tmp1), chan->tech->capabilities),
05603                ast_getformatname_multiple(tmp2, sizeof(tmp2), format));
05604             *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05605             AST_RWLIST_UNLOCK(&backends);
05606             return NULL;
05607          }
05608       }
05609       AST_RWLIST_UNLOCK(&backends);
05610       if (!chan->tech->requester)
05611          return NULL;
05612 
05613       if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, requestor, data, cause)))
05614          return NULL;
05615 
05616       if (set_security_requirements(requestor, c)) {
05617          ast_log(LOG_WARNING, "Setting security requirements failed\n");
05618          c = ast_channel_release(c);
05619          *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05620          return NULL;
05621       }
05622 
05623       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
05624       return c;
05625    }
05626 
05627    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
05628    *cause = AST_CAUSE_NOSUCHDRIVER;
05629    AST_RWLIST_UNLOCK(&backends);
05630 
05631    return NULL;
05632 }
05633 
05634 int ast_call(struct ast_channel *chan, char *addr, int timeout)
05635 {
05636    /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
05637       If the remote end does not answer within the timeout, then do NOT hang up, but
05638       return anyway.  */
05639    int res = -1;
05640    /* Stop if we're a zombie or need a soft hangup */
05641    ast_channel_lock(chan);
05642    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
05643       if (chan->cdr) {
05644          ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
05645       }
05646       if (chan->tech->call)
05647          res = chan->tech->call(chan, addr, timeout);
05648       ast_set_flag(chan, AST_FLAG_OUTGOING);
05649    }
05650    ast_channel_unlock(chan);
05651    return res;
05652 }
05653 
05654 /*!
05655   \brief Transfer a call to dest, if the channel supports transfer
05656 
05657   Called by:
05658    \arg app_transfer
05659    \arg the manager interface
05660 */
05661 int ast_transfer(struct ast_channel *chan, char *dest)
05662 {
05663    int res = -1;
05664 
05665    /* Stop if we're a zombie or need a soft hangup */
05666    ast_channel_lock(chan);
05667    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
05668       if (chan->tech->transfer) {
05669          res = chan->tech->transfer(chan, dest);
05670          if (!res)
05671             res = 1;
05672       } else
05673          res = 0;
05674    }
05675    ast_channel_unlock(chan);
05676 
05677    if (res <= 0) {
05678       return res;
05679    }
05680 
05681    for (;;) {
05682       struct ast_frame *fr;
05683 
05684       res = ast_waitfor(chan, -1);
05685 
05686       if (res < 0 || !(fr = ast_read(chan))) {
05687          res = -1;
05688          break;
05689       }
05690 
05691       if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_TRANSFER) {
05692          enum ast_control_transfer *message = fr->data.ptr;
05693 
05694          if (*message == AST_TRANSFER_SUCCESS) {
05695             res = 1;
05696          } else {
05697             res = -1;
05698          }
05699 
05700          ast_frfree(fr);
05701          break;
05702       }
05703 
05704       ast_frfree(fr);
05705    }
05706 
05707    return res;
05708 }
05709 
05710 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
05711 {
05712    return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
05713 }
05714 
05715 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
05716 {
05717    int pos = 0;   /* index in the buffer where we accumulate digits */
05718    int to = ftimeout;
05719 
05720    struct ast_silence_generator *silgen = NULL;
05721 
05722    /* Stop if we're a zombie or need a soft hangup */
05723    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
05724       return -1;
05725    if (!len)
05726       return -1;
05727    for (;;) {
05728       int d;
05729       if (c->stream) {
05730          d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
05731          ast_stopstream(c);
05732          if (!silgen && ast_opt_transmit_silence)
05733             silgen = ast_channel_start_silence_generator(c);
05734          usleep(1000);
05735          if (!d)
05736             d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
05737       } else {
05738          if (!silgen && ast_opt_transmit_silence)
05739             silgen = ast_channel_start_silence_generator(c);
05740          d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
05741       }
05742       if (d < 0) {
05743          ast_channel_stop_silence_generator(c, silgen);
05744          return AST_GETDATA_FAILED;
05745       }
05746       if (d == 0) {
05747          s[pos] = '\0';
05748          ast_channel_stop_silence_generator(c, silgen);
05749          return AST_GETDATA_TIMEOUT;
05750       }
05751       if (d == 1) {
05752          s[pos] = '\0';
05753          ast_channel_stop_silence_generator(c, silgen);
05754          return AST_GETDATA_INTERRUPTED;
05755       }
05756       if (strchr(enders, d) && (pos == 0)) {
05757          s[pos] = '\0';
05758          ast_channel_stop_silence_generator(c, silgen);
05759          return AST_GETDATA_EMPTY_END_TERMINATED;
05760       }
05761       if (!strchr(enders, d)) {
05762          s[pos++] = d;
05763       }
05764       if (strchr(enders, d) || (pos >= len)) {
05765          s[pos] = '\0';
05766          ast_channel_stop_silence_generator(c, silgen);
05767          return AST_GETDATA_COMPLETE;
05768       }
05769       to = timeout;
05770    }
05771    /* Never reached */
05772    return 0;
05773 }
05774 
05775 int ast_channel_supports_html(struct ast_channel *chan)
05776 {
05777    return (chan->tech->send_html) ? 1 : 0;
05778 }
05779 
05780 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
05781 {
05782    if (chan->tech->send_html)
05783       return chan->tech->send_html(chan, subclass, data, datalen);
05784    return -1;
05785 }
05786 
05787 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
05788 {
05789    return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
05790 }
05791 
05792 /*! \brief Set up translation from one channel to another */
05793 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
05794 {
05795    format_t src, dst;
05796    int use_slin;
05797 
05798    /* See if the channel driver can natively make these two channels compatible */
05799    if (from->tech->bridge && from->tech->bridge == to->tech->bridge &&
05800        !ast_channel_setoption(from, AST_OPTION_MAKE_COMPATIBLE, to, sizeof(struct ast_channel *), 0)) {
05801       return 0;
05802    }
05803 
05804    if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
05805       /* Already compatible!  Moving on ... */
05806       return 0;
05807    }
05808 
05809    /* Set up translation from the 'from' channel to the 'to' channel */
05810    src = from->nativeformats;
05811    dst = to->nativeformats;
05812 
05813    /* If there's no audio in this call, don't bother with trying to find a translation path */
05814    if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
05815       return 0;
05816 
05817    if (ast_translator_best_choice(&dst, &src) < 0) {
05818       ast_log(LOG_WARNING, "No path to translate from %s to %s\n", from->name, to->name);
05819       return -1;
05820    }
05821 
05822    /* if the best path is not 'pass through', then
05823     * transcoding is needed; if desired, force transcode path
05824     * to use SLINEAR between channels, but only if there is
05825     * no direct conversion available. If generic PLC is
05826     * desired, then transcoding via SLINEAR is a requirement
05827     */
05828    use_slin = (src == AST_FORMAT_SLINEAR || dst == AST_FORMAT_SLINEAR);
05829    if ((src != dst) && (ast_opt_generic_plc || ast_opt_transcode_via_slin) &&
05830        (ast_translate_path_steps(dst, src) != 1 || use_slin))
05831       dst = AST_FORMAT_SLINEAR;
05832    if (ast_set_read_format(from, dst) < 0) {
05833       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %s\n", from->name, ast_getformatname(dst));
05834       return -1;
05835    }
05836    if (ast_set_write_format(to, dst) < 0) {
05837       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %s\n", to->name, ast_getformatname(dst));
05838       return -1;
05839    }
05840    return 0;
05841 }
05842 
05843 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
05844 {
05845    /* Some callers do not check return code, and we must try to set all call legs correctly */
05846    int rc = 0;
05847 
05848    /* Set up translation from the chan to the peer */
05849    rc = ast_channel_make_compatible_helper(chan, peer);
05850 
05851    if (rc < 0)
05852       return rc;
05853 
05854    /* Set up translation from the peer to the chan */
05855    rc = ast_channel_make_compatible_helper(peer, chan);
05856 
05857    return rc;
05858 }
05859 
05860 static int __ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clonechan, struct ast_datastore *xfer_ds)
05861 {
05862    int res = -1;
05863    struct ast_channel *final_orig, *final_clone, *base;
05864 
05865    for (;;) {
05866       final_orig = original;
05867       final_clone = clonechan;
05868 
05869       ast_channel_lock_both(original, clonechan);
05870 
05871       if (ast_test_flag(original, AST_FLAG_ZOMBIE)
05872          || ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
05873          /* Zombies! Run! */
05874          ast_log(LOG_WARNING,
05875             "Can't setup masquerade. One or both channels is dead. (%s <-- %s)\n",
05876             original->name, clonechan->name);
05877          ast_channel_unlock(clonechan);
05878          ast_channel_unlock(original);
05879          return -1;
05880       }
05881 
05882       /*
05883        * Each of these channels may be sitting behind a channel proxy
05884        * (i.e. chan_agent) and if so, we don't really want to
05885        * masquerade it, but its proxy
05886        */
05887       if (original->_bridge
05888          && (original->_bridge != ast_bridged_channel(original))
05889          && (original->_bridge->_bridge != original)) {
05890          final_orig = original->_bridge;
05891       }
05892       if (clonechan->_bridge
05893          && (clonechan->_bridge != ast_bridged_channel(clonechan))
05894          && (clonechan->_bridge->_bridge != clonechan)) {
05895          final_clone = clonechan->_bridge;
05896       }
05897       if (final_clone->tech->get_base_channel
05898          && (base = final_clone->tech->get_base_channel(final_clone))) {
05899          final_clone = base;
05900       }
05901 
05902       if ((final_orig != original) || (final_clone != clonechan)) {
05903          /*
05904           * Lots and lots of deadlock avoidance.  The main one we're
05905           * competing with is ast_write(), which locks channels
05906           * recursively, when working with a proxy channel.
05907           */
05908          if (ast_channel_trylock(final_orig)) {
05909             ast_channel_unlock(clonechan);
05910             ast_channel_unlock(original);
05911 
05912             /* Try again */
05913             continue;
05914          }
05915          if (ast_channel_trylock(final_clone)) {
05916             ast_channel_unlock(final_orig);
05917             ast_channel_unlock(clonechan);
05918             ast_channel_unlock(original);
05919 
05920             /* Try again */
05921             continue;
05922          }
05923          ast_channel_unlock(clonechan);
05924          ast_channel_unlock(original);
05925          original = final_orig;
05926          clonechan = final_clone;
05927 
05928          if (ast_test_flag(original, AST_FLAG_ZOMBIE)
05929             || ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
05930             /* Zombies! Run! */
05931             ast_log(LOG_WARNING,
05932                "Can't setup masquerade. One or both channels is dead. (%s <-- %s)\n",
05933                original->name, clonechan->name);
05934             ast_channel_unlock(clonechan);
05935             ast_channel_unlock(original);
05936             return -1;
05937          }
05938       }
05939       break;
05940    }
05941 
05942    if (original == clonechan) {
05943       ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
05944       ast_channel_unlock(clonechan);
05945       ast_channel_unlock(original);
05946       return -1;
05947    }
05948 
05949    ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
05950       clonechan->name, original->name);
05951 
05952    if (!original->masqr && !original->masq && !clonechan->masq && !clonechan->masqr) {
05953       original->masq = clonechan;
05954       clonechan->masqr = original;
05955       if (xfer_ds) {
05956          ast_channel_datastore_add(original, xfer_ds);
05957       }
05958       ast_queue_frame(original, &ast_null_frame);
05959       ast_queue_frame(clonechan, &ast_null_frame);
05960       ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan->name, original->name);
05961       res = 0;
05962    } else if (original->masq) {
05963       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05964          original->masq->name, original->name);
05965    } else if (original->masqr) {
05966       /* not yet as a previously planned masq hasn't yet happened */
05967       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05968          original->name, original->masqr->name);
05969    } else if (clonechan->masq) {
05970       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05971          clonechan->masq->name, clonechan->name);
05972    } else { /* (clonechan->masqr) */
05973       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
05974       clonechan->name, clonechan->masqr->name);
05975    }
05976 
05977    ast_channel_unlock(clonechan);
05978    ast_channel_unlock(original);
05979 
05980    return res;
05981 }
05982 
05983 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
05984 {
05985    return __ast_channel_masquerade(original, clone, NULL);
05986 }
05987 
05988 /*!
05989  * \internal
05990  * \brief Copy the source connected line information to the destination for a transfer.
05991  * \since 1.8
05992  *
05993  * \param dest Destination connected line
05994  * \param src Source connected line
05995  *
05996  * \return Nothing
05997  */
05998 static void party_connected_line_copy_transfer(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
05999 {
06000    struct ast_party_connected_line connected;
06001 
06002    connected = *((struct ast_party_connected_line *) src);
06003    connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
06004 
06005    /* Make sure empty strings will be erased. */
06006    if (!connected.id.name.str) {
06007       connected.id.name.str = "";
06008    }
06009    if (!connected.id.number.str) {
06010       connected.id.number.str = "";
06011    }
06012    if (!connected.id.subaddress.str) {
06013       connected.id.subaddress.str = "";
06014    }
06015    if (!connected.id.tag) {
06016       connected.id.tag = "";
06017    }
06018 
06019    ast_party_connected_line_copy(dest, &connected);
06020 }
06021 
06022 /*! Transfer masquerade connected line exchange data. */
06023 struct xfer_masquerade_ds {
06024    /*! New ID for the target of the transfer (Masquerade original channel) */
06025    struct ast_party_connected_line target_id;
06026    /*! New ID for the transferee of the transfer (Masquerade clone channel) */
06027    struct ast_party_connected_line transferee_id;
06028    /*! TRUE if the target call is held. (Masquerade original channel) */
06029    int target_held;
06030    /*! TRUE if the transferee call is held. (Masquerade clone channel) */
06031    int transferee_held;
06032 };
06033 
06034 /*!
06035  * \internal
06036  * \brief Destroy the transfer connected line exchange datastore information.
06037  * \since 1.8
06038  *
06039  * \param data The datastore payload to destroy.
06040  *
06041  * \return Nothing
06042  */
06043 static void xfer_ds_destroy(void *data)
06044 {
06045    struct xfer_masquerade_ds *ds = data;
06046 
06047    ast_party_connected_line_free(&ds->target_id);
06048    ast_party_connected_line_free(&ds->transferee_id);
06049    ast_free(ds);
06050 }
06051 
06052 static const struct ast_datastore_info xfer_ds_info = {
06053    .type = "xfer_colp",
06054    .destroy = xfer_ds_destroy,
06055 };
06056 
06057 int ast_channel_transfer_masquerade(
06058    struct ast_channel *target_chan,
06059    const struct ast_party_connected_line *target_id,
06060    int target_held,
06061    struct ast_channel *transferee_chan,
06062    const struct ast_party_connected_line *transferee_id,
06063    int transferee_held)
06064 {
06065    struct ast_datastore *xfer_ds;
06066    struct xfer_masquerade_ds *xfer_colp;
06067    int res;
06068 
06069    xfer_ds = ast_datastore_alloc(&xfer_ds_info, NULL);
06070    if (!xfer_ds) {
06071       return -1;
06072    }
06073 
06074    xfer_colp = ast_calloc(1, sizeof(*xfer_colp));
06075    if (!xfer_colp) {
06076       ast_datastore_free(xfer_ds);
06077       return -1;
06078    }
06079    party_connected_line_copy_transfer(&xfer_colp->target_id, target_id);
06080    xfer_colp->target_held = target_held;
06081    party_connected_line_copy_transfer(&xfer_colp->transferee_id, transferee_id);
06082    xfer_colp->transferee_held = transferee_held;
06083    xfer_ds->data = xfer_colp;
06084 
06085    res = __ast_channel_masquerade(target_chan, transferee_chan, xfer_ds);
06086    if (res) {
06087       ast_datastore_free(xfer_ds);
06088    }
06089    return res;
06090 }
06091 
06092 /*! \brief this function simply changes the name of the channel and issues a manager_event
06093  *         with out unlinking and linking the channel from the ao2_container.  This should
06094  *         only be used when the channel has already been unlinked from the ao2_container.
06095  */
06096 static void __ast_change_name_nolink(struct ast_channel *chan, const char *newname)
06097 {
06098    ast_manager_event(chan, EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
06099    ast_string_field_set(chan, name, newname);
06100 }
06101 
06102 void ast_change_name(struct ast_channel *chan, const char *newname)
06103 {
06104    /* We must re-link, as the hash value will change here. */
06105    ao2_unlink(channels, chan);
06106    ast_channel_lock(chan);
06107    __ast_change_name_nolink(chan, newname);
06108    ast_channel_unlock(chan);
06109    ao2_link(channels, chan);
06110 }
06111 
06112 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
06113 {
06114    struct ast_var_t *current, *newvar;
06115    const char *varname;
06116 
06117    AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
06118       int vartype = 0;
06119 
06120       varname = ast_var_full_name(current);
06121       if (!varname)
06122          continue;
06123 
06124       if (varname[0] == '_') {
06125          vartype = 1;
06126          if (varname[1] == '_')
06127             vartype = 2;
06128       }
06129 
06130       switch (vartype) {
06131       case 1:
06132          newvar = ast_var_assign(&varname[1], ast_var_value(current));
06133          if (newvar) {
06134             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
06135             ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
06136          }
06137          break;
06138       case 2:
06139          newvar = ast_var_assign(varname, ast_var_value(current));
06140          if (newvar) {
06141             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
06142             ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
06143          }
06144          break;
06145       default:
06146          ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
06147          break;
06148       }
06149    }
06150 }
06151 
06152 /*!
06153   \brief Clone channel variables from 'clone' channel into 'original' channel
06154 
06155   All variables except those related to app_groupcount are cloned.
06156   Variables are actually _removed_ from 'clone' channel, presumably
06157   because it will subsequently be destroyed.
06158 
06159   \note Assumes locks will be in place on both channels when called.
06160 */
06161 static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
06162 {
06163    struct ast_var_t *current, *newvar;
06164    /* Append variables from clone channel into original channel */
06165    /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
06166    if (AST_LIST_FIRST(&clonechan->varshead))
06167       AST_LIST_APPEND_LIST(&original->varshead, &clonechan->varshead, entries);
06168 
06169    /* then, dup the varshead list into the clone */
06170    
06171    AST_LIST_TRAVERSE(&original->varshead, current, entries) {
06172       newvar = ast_var_assign(current->name, current->value);
06173       if (newvar)
06174          AST_LIST_INSERT_TAIL(&clonechan->varshead, newvar, entries);
06175    }
06176 }
06177 
06178 
06179 
06180 /* return the oldest of two linkedids.  linkedid is derived from
06181    uniqueid which is formed like this: [systemname-]ctime.seq
06182 
06183    The systemname, and the dash are optional, followed by the epoch
06184    time followed by an integer sequence.  Note that this is not a
06185    decimal number, since 1.2 is less than 1.11 in uniqueid land.
06186 
06187    To compare two uniqueids, we parse out the integer values of the
06188    time and the sequence numbers and compare them, with time trumping
06189    sequence.
06190 */
06191 static const char *oldest_linkedid(const char *a, const char *b)
06192 {
06193    const char *satime, *saseq;
06194    const char *sbtime, *sbseq;
06195    const char *dash;
06196 
06197    unsigned int atime, aseq, btime, bseq;
06198 
06199    if (ast_strlen_zero(a))
06200       return b;
06201 
06202    if (ast_strlen_zero(b))
06203       return a;
06204 
06205    satime = a;
06206    sbtime = b;
06207 
06208    /* jump over the system name */
06209    if ((dash = strrchr(satime, '-'))) {
06210       satime = dash+1;
06211    }
06212    if ((dash = strrchr(sbtime, '-'))) {
06213       sbtime = dash+1;
06214    }
06215 
06216    /* the sequence comes after the '.' */
06217    saseq = strchr(satime, '.');
06218    sbseq = strchr(sbtime, '.');
06219    if (!saseq || !sbseq)
06220       return NULL;
06221    saseq++;
06222    sbseq++;
06223 
06224    /* convert it all to integers */
06225    atime = atoi(satime); /* note that atoi is ignoring the '.' after the time string */
06226    btime = atoi(sbtime); /* note that atoi is ignoring the '.' after the time string */
06227    aseq = atoi(saseq);
06228    bseq = atoi(sbseq);
06229 
06230    /* and finally compare */
06231    if (atime == btime) {
06232       return (aseq < bseq) ? a : b;
06233    }
06234    else {
06235       return (atime < btime) ? a : b;
06236    }
06237 }
06238 
06239 /*! Set the channel's linkedid to the given string, and also check to
06240  *  see if the channel's old linkedid is now being retired */
06241 static void ast_channel_change_linkedid(struct ast_channel *chan, const char *linkedid)
06242 {
06243    /* if the linkedid for this channel is being changed from something, check... */
06244    if (!ast_strlen_zero(chan->linkedid) && 0 != strcmp(chan->linkedid, linkedid)) {
06245       ast_cel_check_retire_linkedid(chan);
06246    }
06247 
06248    ast_string_field_set(chan, linkedid, linkedid);
06249 }
06250 
06251 
06252 /*!
06253   \brief Propagate the oldest linkedid between associated channels
06254 
06255 */
06256 void ast_channel_set_linkgroup(struct ast_channel *chan, struct ast_channel *peer)
06257 {
06258    const char* linkedid=NULL;
06259    struct ast_channel *bridged;
06260 
06261    linkedid = oldest_linkedid(chan->linkedid, peer->linkedid);
06262    linkedid = oldest_linkedid(linkedid, chan->uniqueid);
06263    linkedid = oldest_linkedid(linkedid, peer->uniqueid);
06264    if (chan->_bridge) {
06265       bridged = ast_bridged_channel(chan);
06266       if (bridged != peer) {
06267          linkedid = oldest_linkedid(linkedid, bridged->linkedid);
06268          linkedid = oldest_linkedid(linkedid, bridged->uniqueid);
06269       }
06270    }
06271    if (peer->_bridge) {
06272       bridged = ast_bridged_channel(peer);
06273       if (bridged != chan) {
06274          linkedid = oldest_linkedid(linkedid, bridged->linkedid);
06275          linkedid = oldest_linkedid(linkedid, bridged->uniqueid);
06276       }
06277    }
06278 
06279    /* just in case setting a stringfield to itself causes problems */
06280    linkedid = ast_strdupa(linkedid);
06281 
06282    ast_channel_change_linkedid(chan, linkedid);
06283    ast_channel_change_linkedid(peer, linkedid);
06284    if (chan->_bridge) {
06285       bridged = ast_bridged_channel(chan);
06286       if (bridged != peer) {
06287          ast_channel_change_linkedid(bridged, linkedid);
06288       }
06289    }
06290    if (peer->_bridge) {
06291       bridged = ast_bridged_channel(peer);
06292       if (bridged != chan) {
06293          ast_channel_change_linkedid(bridged, linkedid);
06294       }
06295    }
06296 }
06297 
06298 /* copy accountcode and peeraccount across during a link */
06299 static void ast_set_owners_and_peers(struct ast_channel *chan1,
06300                             struct ast_channel *chan2)
06301 {
06302    if (!ast_strlen_zero(chan1->accountcode) && ast_strlen_zero(chan2->peeraccount)) {
06303       ast_log(LOG_DEBUG, "setting peeraccount to %s for %s from data on channel %s\n",
06304             chan1->accountcode, chan2->name, chan1->name);
06305       ast_string_field_set(chan2, peeraccount, chan1->accountcode);
06306    }
06307    if (!ast_strlen_zero(chan2->accountcode) && ast_strlen_zero(chan1->peeraccount)) {
06308       ast_log(LOG_DEBUG, "setting peeraccount to %s for %s from data on channel %s\n",
06309             chan2->accountcode, chan1->name, chan2->name);
06310       ast_string_field_set(chan1, peeraccount, chan2->accountcode);
06311    }
06312    if (!ast_strlen_zero(chan1->peeraccount) && ast_strlen_zero(chan2->accountcode)) {
06313       ast_log(LOG_DEBUG, "setting accountcode to %s for %s from data on channel %s\n",
06314             chan1->peeraccount, chan2->name, chan1->name);
06315       ast_string_field_set(chan2, accountcode, chan1->peeraccount);
06316    }
06317    if (!ast_strlen_zero(chan2->peeraccount) && ast_strlen_zero(chan1->accountcode)) {
06318       ast_log(LOG_DEBUG, "setting accountcode to %s for %s from data on channel %s\n",
06319             chan2->peeraccount, chan1->name, chan2->name);
06320       ast_string_field_set(chan1, accountcode, chan2->peeraccount);
06321    }
06322    if (0 != strcmp(chan1->accountcode, chan2->peeraccount)) {
06323       ast_log(LOG_DEBUG, "changing peeraccount from %s to %s on %s to match channel %s\n",
06324             chan2->peeraccount, chan1->peeraccount, chan2->name, chan1->name);
06325       ast_string_field_set(chan2, peeraccount, chan1->accountcode);
06326    }
06327    if (0 != strcmp(chan2->accountcode, chan1->peeraccount)) {
06328       ast_log(LOG_DEBUG, "changing peeraccount from %s to %s on %s to match channel %s\n",
06329             chan1->peeraccount, chan2->peeraccount, chan1->name, chan2->name);
06330       ast_string_field_set(chan1, peeraccount, chan2->accountcode);
06331    }
06332 }
06333 
06334 /*!
06335  * \pre chan is locked
06336  */
06337 static void report_new_callerid(struct ast_channel *chan)
06338 {
06339    int pres;
06340 
06341    pres = ast_party_id_presentation(&chan->caller.id);
06342    ast_manager_event(chan, EVENT_FLAG_CALL, "NewCallerid",
06343       "Channel: %s\r\n"
06344       "CallerIDNum: %s\r\n"
06345       "CallerIDName: %s\r\n"
06346       "Uniqueid: %s\r\n"
06347       "CID-CallingPres: %d (%s)\r\n",
06348       chan->name,
06349       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
06350       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, ""),
06351       chan->uniqueid,
06352       pres,
06353       ast_describe_caller_presentation(pres)
06354       );
06355 }
06356 
06357 /*!
06358  * \internal
06359  * \brief Transfer COLP between target and transferee channels.
06360  * \since 1.8
06361  *
06362  * \param transferee Transferee channel to exchange connected line information.
06363  * \param colp Connected line information to exchange.
06364  *
06365  * \return Nothing
06366  */
06367 static void masquerade_colp_transfer(struct ast_channel *transferee, struct xfer_masquerade_ds *colp)
06368 {
06369    struct ast_control_read_action_payload *frame_payload;
06370    int payload_size;
06371    int frame_size;
06372    unsigned char connected_line_data[1024];
06373 
06374    /* Release any hold on the target. */
06375    if (colp->target_held) {
06376       ast_queue_control(transferee, AST_CONTROL_UNHOLD);
06377    }
06378 
06379    /*
06380     * Since transferee may not actually be bridged to another channel,
06381     * there is no way for us to queue a frame so that its connected
06382     * line status will be updated.  Instead, we use the somewhat
06383     * hackish approach of using a special control frame type that
06384     * instructs ast_read() to perform a specific action.  In this
06385     * case, the frame we queue tells ast_read() to call the
06386     * connected line interception macro configured for transferee.
06387     */
06388    payload_size = ast_connected_line_build_data(connected_line_data,
06389       sizeof(connected_line_data), &colp->target_id, NULL);
06390    if (payload_size != -1) {
06391       frame_size = payload_size + sizeof(*frame_payload);
06392       frame_payload = alloca(frame_size);
06393       frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
06394       frame_payload->payload_size = payload_size;
06395       memcpy(frame_payload->payload, connected_line_data, payload_size);
06396       ast_queue_control_data(transferee, AST_CONTROL_READ_ACTION, frame_payload,
06397          frame_size);
06398    }
06399    /*
06400     * In addition to queueing the read action frame so that the
06401     * connected line info on transferee will be updated, we also are
06402     * going to queue a plain old connected line update on transferee to
06403     * update the target.
06404     */
06405    ast_channel_queue_connected_line_update(transferee, &colp->transferee_id, NULL);
06406 }
06407 
06408 /*!
06409  * \brief Masquerade a channel
06410  *
06411  * \note Assumes _NO_ channels and _NO_ channel pvt's are locked.  If a channel is locked while calling
06412  *       this function, it invalidates our channel container locking order.  All channels
06413  *       must be unlocked before it is permissible to lock the channels' ao2 container.
06414  */
06415 int ast_do_masquerade(struct ast_channel *original)
06416 {
06417    format_t x;
06418    int i;
06419    int res=0;
06420    int origstate;
06421    int visible_indication;
06422    struct ast_frame *current;
06423    const struct ast_channel_tech *t;
06424    void *t_pvt;
06425    union {
06426       struct ast_party_dialed dialed;
06427       struct ast_party_caller caller;
06428       struct ast_party_connected_line connected;
06429       struct ast_party_redirecting redirecting;
06430    } exchange;
06431    struct ast_channel *clonechan, *chans[2];
06432    struct ast_channel *bridged;
06433    struct ast_cdr *cdr;
06434    struct ast_datastore *xfer_ds;
06435    struct xfer_masquerade_ds *xfer_colp;
06436    format_t rformat = original->readformat;
06437    format_t wformat = original->writeformat;
06438    char newn[AST_CHANNEL_NAME];
06439    char orig[AST_CHANNEL_NAME];
06440    char masqn[AST_CHANNEL_NAME];
06441    char zombn[AST_CHANNEL_NAME];
06442 
06443    /* XXX This operation is a bit odd.  We're essentially putting the guts of
06444     * the clone channel into the original channel.  Start by killing off the
06445     * original channel's backend.  While the features are nice, which is the
06446     * reason we're keeping it, it's still awesomely weird. XXX */
06447 
06448    /* The reasoning for the channels ao2_container lock here is complex.
06449     * 
06450     * In order to check for a race condition, the original channel must
06451     * be locked.  If it is determined that the masquerade should proceed
06452     * the original channel can absolutely not be unlocked until the end
06453     * of the function.  Since after determining the masquerade should
06454     * continue requires the channels to be unlinked from the ao2_container,
06455     * the container lock must be held first to achieve proper locking order.
06456     */
06457    ao2_lock(channels);
06458 
06459    /* lock the original channel to determine if the masquerade is required or not */
06460    ast_channel_lock(original);
06461 
06462    /*
06463     * This checks to see if the masquerade has already happened or
06464     * not.  There is a race condition that exists for this
06465     * function.  Since all pvt and channel locks must be let go
06466     * before calling do_masquerade, it is possible that it could be
06467     * called multiple times for the same channel.  This check
06468     * verifies whether or not the masquerade has already been
06469     * completed by another thread.
06470     */
06471    while ((clonechan = original->masq) && ast_channel_trylock(clonechan)) {
06472       /*
06473        * A masq is needed but we could not get the clonechan lock
06474        * immediately.  Since this function already holds the global
06475        * container lock, unlocking original for deadlock avoidance
06476        * will not result in any sort of masquerade race condition.  If
06477        * masq is called by a different thread while this happens, it
06478        * will be stuck waiting until we unlock the container.
06479        */
06480       CHANNEL_DEADLOCK_AVOIDANCE(original);
06481    }
06482 
06483    /*
06484     * A final masq check must be done after deadlock avoidance for
06485     * clonechan above or we could get a double masq.  This is
06486     * posible with ast_hangup at least.
06487     */
06488    if (!clonechan) {
06489       /* masq already completed by another thread, or never needed to be done to begin with */
06490       ast_channel_unlock(original);
06491       ao2_unlock(channels);
06492       return 0;
06493    }
06494 
06495    /* Get any transfer masquerade connected line exchange data. */
06496    xfer_ds = ast_channel_datastore_find(original, &xfer_ds_info, NULL);
06497    if (xfer_ds) {
06498       ast_channel_datastore_remove(original, xfer_ds);
06499       xfer_colp = xfer_ds->data;
06500    } else {
06501       xfer_colp = NULL;
06502    }
06503 
06504    /*
06505     * Release any hold on the transferee channel before proceeding
06506     * with the masquerade.
06507     */
06508    if (xfer_colp && xfer_colp->transferee_held) {
06509       ast_indicate(clonechan, AST_CONTROL_UNHOLD);
06510    }
06511 
06512    /* clear the masquerade channels */
06513    original->masq = NULL;
06514    clonechan->masqr = NULL;
06515 
06516    /* unlink from channels container as name (which is the hash value) will change */
06517    ao2_unlink(channels, original);
06518    ao2_unlink(channels, clonechan);
06519 
06520    ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
06521       clonechan->name, clonechan->_state, original->name, original->_state);
06522 
06523    /*
06524     * Stop any visible indiction on the original channel so we can
06525     * transfer it to the clonechan taking the original's place.
06526     */
06527    visible_indication = original->visible_indication;
06528    ast_indicate(original, -1);
06529 
06530    chans[0] = clonechan;
06531    chans[1] = original;
06532    ast_manager_event_multichan(EVENT_FLAG_CALL, "Masquerade", 2, chans,
06533       "Clone: %s\r\n"
06534       "CloneState: %s\r\n"
06535       "Original: %s\r\n"
06536       "OriginalState: %s\r\n",
06537       clonechan->name, ast_state2str(clonechan->_state), original->name, ast_state2str(original->_state));
06538 
06539    /* Having remembered the original read/write formats, we turn off any translation on either
06540       one */
06541    free_translation(clonechan);
06542    free_translation(original);
06543 
06544    /* Save the original name */
06545    ast_copy_string(orig, original->name, sizeof(orig));
06546    /* Save the new name */
06547    ast_copy_string(newn, clonechan->name, sizeof(newn));
06548    /* Create the masq name */
06549    snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
06550 
06551    /* Mangle the name of the clone channel */
06552    __ast_change_name_nolink(clonechan, masqn);
06553 
06554    /* Copy the name from the clone channel */
06555    __ast_change_name_nolink(original, newn);
06556 
06557    /* share linked id's */
06558    ast_channel_set_linkgroup(original, clonechan);
06559 
06560    /* Swap the technologies */
06561    t = original->tech;
06562    original->tech = clonechan->tech;
06563    clonechan->tech = t;
06564 
06565    /* Swap the cdrs */
06566    cdr = original->cdr;
06567    original->cdr = clonechan->cdr;
06568    clonechan->cdr = cdr;
06569 
06570    t_pvt = original->tech_pvt;
06571    original->tech_pvt = clonechan->tech_pvt;
06572    clonechan->tech_pvt = t_pvt;
06573 
06574    /* Swap the alertpipes */
06575    for (i = 0; i < 2; i++) {
06576       x = original->alertpipe[i];
06577       original->alertpipe[i] = clonechan->alertpipe[i];
06578       clonechan->alertpipe[i] = x;
06579    }
06580 
06581    /* 
06582     * Swap the readq's.  The end result should be this:
06583     *
06584     *  1) All frames should be on the new (original) channel.
06585     *  2) Any frames that were already on the new channel before this
06586     *     masquerade need to be at the end of the readq, after all of the
06587     *     frames on the old (clone) channel.
06588     *  3) The alertpipe needs to get poked for every frame that was already
06589     *     on the new channel, since we are now using the alert pipe from the
06590     *     old (clone) channel.
06591     */
06592    {
06593       AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
06594       AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
06595 
06596       AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
06597       AST_LIST_APPEND_LIST(&original->readq, &clonechan->readq, frame_list);
06598 
06599       while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
06600          AST_LIST_INSERT_TAIL(&original->readq, current, frame_list);
06601          if (original->alertpipe[1] > -1) {
06602             int poke = 0;
06603 
06604             if (write(original->alertpipe[1], &poke, sizeof(poke)) < 0) {
06605                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
06606             }
06607          }
06608       }
06609    }
06610 
06611    /* Swap the raw formats */
06612    x = original->rawreadformat;
06613    original->rawreadformat = clonechan->rawreadformat;
06614    clonechan->rawreadformat = x;
06615    x = original->rawwriteformat;
06616    original->rawwriteformat = clonechan->rawwriteformat;
06617    clonechan->rawwriteformat = x;
06618 
06619    clonechan->_softhangup = AST_SOFTHANGUP_DEV;
06620 
06621    /* And of course, so does our current state.  Note we need not
06622       call ast_setstate since the event manager doesn't really consider
06623       these separate.  We do this early so that the clone has the proper
06624       state of the original channel. */
06625    origstate = original->_state;
06626    original->_state = clonechan->_state;
06627    clonechan->_state = origstate;
06628 
06629    if (clonechan->tech->fixup && clonechan->tech->fixup(original, clonechan)) {
06630       ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clonechan->name);
06631    }
06632 
06633    /* Start by disconnecting the original's physical side */
06634    if (clonechan->tech->hangup && clonechan->tech->hangup(clonechan)) {
06635       ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
06636       res = -1;
06637       goto done;
06638    }
06639 
06640    /*
06641     * We just hung up the physical side of the channel.  Set the
06642     * new zombie to use the kill channel driver for safety.
06643     */
06644    clonechan->tech = &ast_kill_tech;
06645 
06646    /* Mangle the name of the clone channel */
06647    snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig); /* quick, hide the brains! */
06648    __ast_change_name_nolink(clonechan, zombn);
06649 
06650    /* Update the type. */
06651    t_pvt = original->monitor;
06652    original->monitor = clonechan->monitor;
06653    clonechan->monitor = t_pvt;
06654 
06655    /* Keep the same language.  */
06656    ast_string_field_set(original, language, clonechan->language);
06657    /* Copy the FD's other than the generator fd */
06658    for (x = 0; x < AST_MAX_FDS; x++) {
06659       if (x != AST_GENERATOR_FD)
06660          ast_channel_set_fd(original, x, clonechan->fds[x]);
06661    }
06662 
06663    ast_app_group_update(clonechan, original);
06664 
06665    /* Move data stores over */
06666    if (AST_LIST_FIRST(&clonechan->datastores)) {
06667       struct ast_datastore *ds;
06668       /* We use a safe traversal here because some fixup routines actually
06669        * remove the datastore from the list and free them.
06670        */
06671       AST_LIST_TRAVERSE_SAFE_BEGIN(&clonechan->datastores, ds, entry) {
06672          if (ds->info->chan_fixup)
06673             ds->info->chan_fixup(ds->data, clonechan, original);
06674       }
06675       AST_LIST_TRAVERSE_SAFE_END;
06676       AST_LIST_APPEND_LIST(&original->datastores, &clonechan->datastores, entry);
06677    }
06678 
06679    ast_autochan_new_channel(clonechan, original);
06680 
06681    clone_variables(original, clonechan);
06682    /* Presense of ADSI capable CPE follows clone */
06683    original->adsicpe = clonechan->adsicpe;
06684    /* Bridge remains the same */
06685    /* CDR fields remain the same */
06686    /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
06687    /* Application and data remain the same */
06688    /* Clone exception  becomes real one, as with fdno */
06689    ast_set_flag(original, ast_test_flag(clonechan, AST_FLAG_EXCEPTION | AST_FLAG_OUTGOING));
06690    original->fdno = clonechan->fdno;
06691    /* Schedule context remains the same */
06692    /* Stream stuff stays the same */
06693    /* Keep the original state.  The fixup code will need to work with it most likely */
06694 
06695    /*
06696     * Just swap the whole structures, nevermind the allocations,
06697     * they'll work themselves out.
06698     */
06699    exchange.dialed = original->dialed;
06700    original->dialed = clonechan->dialed;
06701    clonechan->dialed = exchange.dialed;
06702 
06703    exchange.caller = original->caller;
06704    original->caller = clonechan->caller;
06705    clonechan->caller = exchange.caller;
06706 
06707    exchange.connected = original->connected;
06708    original->connected = clonechan->connected;
06709    clonechan->connected = exchange.connected;
06710 
06711    exchange.redirecting = original->redirecting;
06712    original->redirecting = clonechan->redirecting;
06713    clonechan->redirecting = exchange.redirecting;
06714 
06715    report_new_callerid(original);
06716 
06717    /* Restore original timing file descriptor */
06718    ast_channel_set_fd(original, AST_TIMING_FD, original->timingfd);
06719 
06720    /* Our native formats are different now */
06721    original->nativeformats = clonechan->nativeformats;
06722 
06723    /* Context, extension, priority, app data, jump table,  remain the same */
06724    /* pvt switches.  pbx stays the same, as does next */
06725 
06726    /* Set the write format */
06727    ast_set_write_format(original, wformat);
06728 
06729    /* Set the read format */
06730    ast_set_read_format(original, rformat);
06731 
06732    /* Copy the music class */
06733    ast_string_field_set(original, musicclass, clonechan->musicclass);
06734 
06735    /* copy over accuntcode and set peeraccount across the bridge */
06736    ast_string_field_set(original, accountcode, S_OR(clonechan->accountcode, ""));
06737    if (original->_bridge) {
06738       /* XXX - should we try to lock original->_bridge here? */
06739       ast_string_field_set(original->_bridge, peeraccount, S_OR(clonechan->accountcode, ""));
06740       ast_cel_report_event(original, AST_CEL_BRIDGE_UPDATE, NULL, NULL, NULL);
06741    }
06742 
06743    ast_debug(1, "Putting channel %s in %s/%s formats\n", original->name,
06744       ast_getformatname(wformat), ast_getformatname(rformat));
06745 
06746    /* Okay.  Last thing is to let the channel driver know about all this mess, so he
06747       can fix up everything as best as possible */
06748    if (original->tech->fixup) {
06749       if (original->tech->fixup(clonechan, original)) {
06750          ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
06751             original->tech->type, original->name);
06752          res = -1;
06753          goto done;
06754       }
06755    } else
06756       ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
06757          original->tech->type, original->name);
06758 
06759    /* 
06760     * If an indication is currently playing, maintain it on the channel 
06761     * that is taking the place of original 
06762     *
06763     * This is needed because the masquerade is swapping out in the internals
06764     * of this channel, and the new channel private data needs to be made
06765     * aware of the current visible indication (RINGING, CONGESTION, etc.)
06766     */
06767    if (visible_indication) {
06768       ast_indicate(original, visible_indication);
06769    }
06770 
06771    /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
06772       a zombie so nothing tries to touch it.  If it's already been marked as a
06773       zombie, then free it now (since it already is considered invalid). */
06774    if (ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
06775       ast_debug(1, "Destroying channel clone '%s'\n", clonechan->name);
06776       ast_channel_unlock(clonechan);
06777       ast_manager_event(clonechan, EVENT_FLAG_CALL, "Hangup",
06778          "Channel: %s\r\n"
06779          "Uniqueid: %s\r\n"
06780          "Cause: %d\r\n"
06781          "Cause-txt: %s\r\n",
06782          clonechan->name,
06783          clonechan->uniqueid,
06784          clonechan->hangupcause,
06785          ast_cause2str(clonechan->hangupcause)
06786          );
06787       clonechan = ast_channel_release(clonechan);
06788    } else {
06789       ast_debug(1, "Released clone lock on '%s'\n", clonechan->name);
06790       ast_set_flag(clonechan, AST_FLAG_ZOMBIE);
06791       ast_queue_frame(clonechan, &ast_null_frame);
06792    }
06793 
06794    /* Signal any blocker */
06795    if (ast_test_flag(original, AST_FLAG_BLOCKING))
06796       pthread_kill(original->blocker, SIGURG);
06797    ast_debug(1, "Done Masquerading %s (%d)\n", original->name, original->_state);
06798 
06799    if ((bridged = ast_bridged_channel(original))) {
06800       ast_channel_lock(bridged);
06801       ast_indicate(bridged, AST_CONTROL_SRCCHANGE);
06802       ast_channel_unlock(bridged);
06803    }
06804    ast_indicate(original, AST_CONTROL_SRCCHANGE);
06805 
06806    if (xfer_colp) {
06807       /*
06808        * After the masquerade, the original channel pointer actually
06809        * points to the new transferee channel and the bridged channel
06810        * is still the intended transfer target party.
06811        */
06812       masquerade_colp_transfer(original, xfer_colp);
06813    }
06814 
06815 done:
06816    if (xfer_ds) {
06817       ast_datastore_free(xfer_ds);
06818    }
06819    /* it is possible for the clone channel to disappear during this */
06820    if (clonechan) {
06821       ast_channel_unlock(original);
06822       ast_channel_unlock(clonechan);
06823       ao2_link(channels, clonechan);
06824       ao2_link(channels, original);
06825    } else {
06826       ast_channel_unlock(original);
06827       ao2_link(channels, original);
06828    }
06829 
06830    ao2_unlock(channels);
06831 
06832    return res;
06833 }
06834 
06835 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
06836 {
06837    ast_channel_lock(chan);
06838 
06839    if (cid_num) {
06840       chan->caller.id.number.valid = 1;
06841       ast_free(chan->caller.id.number.str);
06842       chan->caller.id.number.str = ast_strdup(cid_num);
06843    }
06844    if (cid_name) {
06845       chan->caller.id.name.valid = 1;
06846       ast_free(chan->caller.id.name.str);
06847       chan->caller.id.name.str = ast_strdup(cid_name);
06848    }
06849    if (cid_ani) {
06850       chan->caller.ani.number.valid = 1;
06851       ast_free(chan->caller.ani.number.str);
06852       chan->caller.ani.number.str = ast_strdup(cid_ani);
06853    }
06854    if (chan->cdr) {
06855       ast_cdr_setcid(chan->cdr, chan);
06856    }
06857 
06858    report_new_callerid(chan);
06859 
06860    ast_channel_unlock(chan);
06861 }
06862 
06863 void ast_channel_set_caller(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
06864 {
06865    if (&chan->caller == caller) {
06866       /* Don't set to self */
06867       return;
06868    }
06869 
06870    ast_channel_lock(chan);
06871    ast_party_caller_set(&chan->caller, caller, update);
06872    ast_channel_unlock(chan);
06873 }
06874 
06875 void ast_channel_set_caller_event(struct ast_channel *chan, const struct ast_party_caller *caller, const struct ast_set_party_caller *update)
06876 {
06877    const char *pre_set_number;
06878    const char *pre_set_name;
06879 
06880    if (&chan->caller == caller) {
06881       /* Don't set to self */
06882       return;
06883    }
06884 
06885    ast_channel_lock(chan);
06886    pre_set_number =
06887       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL);
06888    pre_set_name = S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL);
06889    ast_party_caller_set(&chan->caller, caller, update);
06890    if (S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)
06891          != pre_set_number
06892       || S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, NULL)
06893          != pre_set_name) {
06894       /* The caller id name or number changed. */
06895       report_new_callerid(chan);
06896    }
06897    if (chan->cdr) {
06898       ast_cdr_setcid(chan->cdr, chan);
06899    }
06900    ast_channel_unlock(chan);
06901 }
06902 
06903 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
06904 {
06905    int oldstate = chan->_state;
06906    char name[AST_CHANNEL_NAME], *dashptr;
06907 
06908    if (oldstate == state)
06909       return 0;
06910 
06911    ast_copy_string(name, chan->name, sizeof(name));
06912    if ((dashptr = strrchr(name, '-'))) {
06913       *dashptr = '\0';
06914    }
06915 
06916    chan->_state = state;
06917 
06918    /* We have to pass AST_DEVICE_UNKNOWN here because it is entirely possible that the channel driver
06919     * for this channel is using the callback method for device state. If we pass in an actual state here
06920     * we override what they are saying the state is and things go amuck. */
06921    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
06922 
06923    /* setstate used to conditionally report Newchannel; this is no more */
06924    ast_manager_event(chan, EVENT_FLAG_CALL, "Newstate",
06925       "Channel: %s\r\n"
06926       "ChannelState: %d\r\n"
06927       "ChannelStateDesc: %s\r\n"
06928       "CallerIDNum: %s\r\n"
06929       "CallerIDName: %s\r\n"
06930       "ConnectedLineNum: %s\r\n"
06931       "ConnectedLineName: %s\r\n"
06932       "Uniqueid: %s\r\n",
06933       chan->name, chan->_state, ast_state2str(chan->_state),
06934       S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, ""),
06935       S_COR(chan->caller.id.name.valid, chan->caller.id.name.str, ""),
06936       S_COR(chan->connected.id.number.valid, chan->connected.id.number.str, ""),
06937       S_COR(chan->connected.id.name.valid, chan->connected.id.name.str, ""),
06938       chan->uniqueid);
06939 
06940    return 0;
06941 }
06942 
06943 /*! \brief Find bridged channel */
06944 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
06945 {
06946    struct ast_channel *bridged;
06947    bridged = chan->_bridge;
06948    if (bridged && bridged->tech->bridged_channel)
06949       bridged = bridged->tech->bridged_channel(chan, bridged);
06950    return bridged;
06951 }
06952 
06953 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
06954 {
06955    int min = 0, sec = 0, check;
06956 
06957    check = ast_autoservice_start(peer);
06958    if (check)
06959       return;
06960 
06961    if (remain > 0) {
06962       if (remain / 60 > 1) {
06963          min = remain / 60;
06964          sec = remain % 60;
06965       } else {
06966          sec = remain;
06967       }
06968    }
06969    
06970    if (!strcmp(sound,"timeleft")) { /* Queue support */
06971       ast_stream_and_wait(chan, "vm-youhave", "");
06972       if (min) {
06973          ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
06974          ast_stream_and_wait(chan, "queue-minutes", "");
06975       }
06976       if (sec) {
06977          ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
06978          ast_stream_and_wait(chan, "queue-seconds", "");
06979       }
06980    } else {
06981       ast_stream_and_wait(chan, sound, "");
06982    }
06983 
06984    ast_autoservice_stop(peer);
06985 }
06986 
06987 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
06988                    struct ast_bridge_config *config, struct ast_frame **fo,
06989                    struct ast_channel **rc)
06990 {
06991    /* Copy voice back and forth between the two channels. */
06992    struct ast_channel *cs[3];
06993    struct ast_frame *f;
06994    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
06995    format_t o0nativeformats;
06996    format_t o1nativeformats;
06997    int watch_c0_dtmf;
06998    int watch_c1_dtmf;
06999    void *pvt0, *pvt1;
07000    /* Indicates whether a frame was queued into a jitterbuffer */
07001    int frame_put_in_jb = 0;
07002    int jb_in_use;
07003    int to;
07004    
07005    cs[0] = c0;
07006    cs[1] = c1;
07007    pvt0 = c0->tech_pvt;
07008    pvt1 = c1->tech_pvt;
07009    o0nativeformats = c0->nativeformats;
07010    o1nativeformats = c1->nativeformats;
07011    watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
07012    watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
07013 
07014    /* Check the need of a jitterbuffer for each channel */
07015    jb_in_use = ast_jb_do_usecheck(c0, c1);
07016    if (jb_in_use)
07017       ast_jb_empty_and_reset(c0, c1);
07018 
07019    ast_poll_channel_add(c0, c1);
07020 
07021    if (config->feature_timer > 0 && ast_tvzero(config->nexteventts)) {
07022       /* nexteventts is not set when the bridge is not scheduled to
07023        * break, so calculate when the bridge should possibly break
07024        * if a partial feature match timed out */
07025       config->nexteventts = ast_tvadd(ast_tvnow(), ast_samp2tv(config->feature_timer, 1000));
07026    }
07027 
07028    for (;;) {
07029       struct ast_channel *who, *other;
07030 
07031       if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
07032           (o0nativeformats != c0->nativeformats) ||
07033           (o1nativeformats != c1->nativeformats)) {
07034          /* Check for Masquerade, codec changes, etc */
07035          res = AST_BRIDGE_RETRY;
07036          break;
07037       }
07038       if (config->nexteventts.tv_sec) {
07039          to = ast_tvdiff_ms(config->nexteventts, ast_tvnow());
07040          if (to <= 0) {
07041             if (config->timelimit && !config->feature_timer && !ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
07042                res = AST_BRIDGE_RETRY;
07043                /* generic bridge ending to play warning */
07044                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
07045             } else if (config->feature_timer) {
07046                /* feature timer expired - make sure we do not play warning */
07047                ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
07048                res = AST_BRIDGE_RETRY;
07049             } else {
07050                res = AST_BRIDGE_COMPLETE;
07051             }
07052             break;
07053          }
07054       } else {
07055          /* If a feature has been started and the bridge is configured to 
07056           * to not break, leave the channel bridge when the feature timer
07057           * time has elapsed so the DTMF will be sent to the other side. 
07058           */
07059          if (!ast_tvzero(config->nexteventts)) {
07060             int diff = ast_tvdiff_ms(config->nexteventts, ast_tvnow());
07061             if (diff <= 0) {
07062                res = AST_BRIDGE_RETRY;
07063                break;
07064             }
07065          }
07066          to = -1;
07067       }
07068       /* Calculate the appropriate max sleep interval - in general, this is the time,
07069          left to the closest jb delivery moment */
07070       if (jb_in_use)
07071          to = ast_jb_get_when_to_wakeup(c0, c1, to);
07072       who = ast_waitfor_n(cs, 2, &to);
07073       if (!who) {
07074          /* No frame received within the specified timeout - check if we have to deliver now */
07075          if (jb_in_use)
07076             ast_jb_get_and_deliver(c0, c1);
07077          if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
07078             if (c0->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
07079                ast_channel_clear_softhangup(c0, AST_SOFTHANGUP_UNBRIDGE);
07080             }
07081             if (c1->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
07082                ast_channel_clear_softhangup(c1, AST_SOFTHANGUP_UNBRIDGE);
07083             }
07084             c0->_bridge = c1;
07085             c1->_bridge = c0;
07086          }
07087          continue;
07088       }
07089       f = ast_read(who);
07090       if (!f) {
07091          *fo = NULL;
07092          *rc = who;
07093          ast_debug(1, "Didn't get a frame from channel: %s\n",who->name);
07094          break;
07095       }
07096 
07097       other = (who == c0) ? c1 : c0; /* the 'other' channel */
07098       /* Try add the frame info the who's bridged channel jitterbuff */
07099       if (jb_in_use)
07100          frame_put_in_jb = !ast_jb_put(other, f);
07101 
07102       if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
07103          int bridge_exit = 0;
07104 
07105          switch (f->subclass.integer) {
07106          case AST_CONTROL_AOC:
07107             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
07108             break;
07109          case AST_CONTROL_REDIRECTING:
07110             if (ast_channel_redirecting_macro(who, other, f, other == c0, 1)) {
07111                ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
07112             }
07113             break;
07114          case AST_CONTROL_CONNECTED_LINE:
07115             if (ast_channel_connected_line_macro(who, other, f, other == c0, 1)) {
07116                ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
07117             }
07118             break;
07119          case AST_CONTROL_HOLD:
07120          case AST_CONTROL_UNHOLD:
07121          case AST_CONTROL_VIDUPDATE:
07122          case AST_CONTROL_SRCUPDATE:
07123          case AST_CONTROL_SRCCHANGE:
07124          case AST_CONTROL_T38_PARAMETERS:
07125             ast_indicate_data(other, f->subclass.integer, f->data.ptr, f->datalen);
07126             if (jb_in_use) {
07127                ast_jb_empty_and_reset(c0, c1);
07128             }
07129             break;
07130          default:
07131             *fo = f;
07132             *rc = who;
07133             bridge_exit = 1;
07134             ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass.integer, who->name);
07135             break;
07136          }
07137          if (bridge_exit)
07138             break;
07139       }
07140       if ((f->frametype == AST_FRAME_VOICE) ||
07141           (f->frametype == AST_FRAME_DTMF_BEGIN) ||
07142           (f->frametype == AST_FRAME_DTMF) ||
07143           (f->frametype == AST_FRAME_VIDEO) ||
07144           (f->frametype == AST_FRAME_IMAGE) ||
07145           (f->frametype == AST_FRAME_HTML) ||
07146           (f->frametype == AST_FRAME_MODEM) ||
07147           (f->frametype == AST_FRAME_TEXT)) {
07148          /* monitored dtmf causes exit from bridge */
07149          int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
07150 
07151          if (monitored_source &&
07152             (f->frametype == AST_FRAME_DTMF_END ||
07153             f->frametype == AST_FRAME_DTMF_BEGIN)) {
07154             *fo = f;
07155             *rc = who;
07156             ast_debug(1, "Got DTMF %s on channel (%s)\n", 
07157                f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
07158                who->name);
07159 
07160             break;
07161          }
07162          /* Write immediately frames, not passed through jb */
07163          if (!frame_put_in_jb)
07164             ast_write(other, f);
07165             
07166          /* Check if we have to deliver now */
07167          if (jb_in_use)
07168             ast_jb_get_and_deliver(c0, c1);
07169       }
07170       /* XXX do we want to pass on also frames not matched above ? */
07171       ast_frfree(f);
07172 
07173 #ifndef HAVE_EPOLL
07174       /* Swap who gets priority */
07175       cs[2] = cs[0];
07176       cs[0] = cs[1];
07177       cs[1] = cs[2];
07178 #endif
07179    }
07180 
07181    ast_poll_channel_del(c0, c1);
07182 
07183    return res;
07184 }
07185 
07186 /*! \brief Bridge two channels together (early) */
07187 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
07188 {
07189    /* Make sure we can early bridge, if not error out */
07190    if (!c0->tech->early_bridge || (c1 && (!c1->tech->early_bridge || c0->tech->early_bridge != c1->tech->early_bridge)))
07191       return -1;
07192 
07193    return c0->tech->early_bridge(c0, c1);
07194 }
07195 
07196 /*! \brief Send manager event for bridge link and unlink events.
07197  * \param onoff Link/Unlinked 
07198  * \param type 1 for core, 2 for native
07199  * \param c0 first channel in bridge
07200  * \param c1 second channel in bridge
07201 */
07202 static void manager_bridge_event(int onoff, int type, struct ast_channel *c0, struct ast_channel *c1)
07203 {
07204    struct ast_channel *chans[2] = { c0, c1 };
07205    ast_manager_event_multichan(EVENT_FLAG_CALL, "Bridge", 2, chans,
07206       "Bridgestate: %s\r\n"
07207       "Bridgetype: %s\r\n"
07208       "Channel1: %s\r\n"
07209       "Channel2: %s\r\n"
07210       "Uniqueid1: %s\r\n"
07211       "Uniqueid2: %s\r\n"
07212       "CallerID1: %s\r\n"
07213       "CallerID2: %s\r\n",
07214       onoff ? "Link" : "Unlink",
07215       type == 1 ? "core" : "native",
07216       c0->name, c1->name,
07217       c0->uniqueid, c1->uniqueid,
07218       S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, ""),
07219       S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, ""));
07220 }
07221 
07222 static void update_bridge_vars(struct ast_channel *c0, struct ast_channel *c1)
07223 {
07224    const char *c0_name;
07225    const char *c1_name;
07226    const char *c0_pvtid = NULL;
07227    const char *c1_pvtid = NULL;
07228 
07229    ast_channel_lock(c1);
07230    c1_name = ast_strdupa(c1->name);
07231    if (c1->tech->get_pvt_uniqueid) {
07232       c1_pvtid = ast_strdupa(c1->tech->get_pvt_uniqueid(c1));
07233    }
07234    ast_channel_unlock(c1);
07235 
07236    ast_channel_lock(c0);
07237    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER"))) {
07238       pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1_name);
07239    }
07240    if (c1_pvtid) {
07241       pbx_builtin_setvar_helper(c0, "BRIDGEPVTCALLID", c1_pvtid);
07242    }
07243    c0_name = ast_strdupa(c0->name);
07244    if (c0->tech->get_pvt_uniqueid) {
07245       c0_pvtid = ast_strdupa(c0->tech->get_pvt_uniqueid(c0));
07246    }
07247    ast_channel_unlock(c0);
07248 
07249    ast_channel_lock(c1);
07250    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER"))) {
07251       pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0_name);
07252    }
07253    if (c0_pvtid) {
07254       pbx_builtin_setvar_helper(c1, "BRIDGEPVTCALLID", c0_pvtid);
07255    }
07256    ast_channel_unlock(c1);
07257 }
07258 
07259 static void bridge_play_sounds(struct ast_channel *c0, struct ast_channel *c1)
07260 {
07261    const char *s, *sound;
07262 
07263    /* See if we need to play an audio file to any side of the bridge */
07264 
07265    ast_channel_lock(c0);
07266    if ((s = pbx_builtin_getvar_helper(c0, "BRIDGE_PLAY_SOUND"))) {
07267       sound = ast_strdupa(s);
07268       ast_channel_unlock(c0);
07269       bridge_playfile(c0, c1, sound, 0);
07270       pbx_builtin_setvar_helper(c0, "BRIDGE_PLAY_SOUND", NULL);
07271    } else {
07272       ast_channel_unlock(c0);
07273    }
07274 
07275    ast_channel_lock(c1);
07276    if ((s = pbx_builtin_getvar_helper(c1, "BRIDGE_PLAY_SOUND"))) {
07277       sound = ast_strdupa(s);
07278       ast_channel_unlock(c1);
07279       bridge_playfile(c1, c0, sound, 0);
07280       pbx_builtin_setvar_helper(c1, "BRIDGE_PLAY_SOUND", NULL);
07281    } else {
07282       ast_channel_unlock(c1);
07283    }
07284 }
07285 
07286 /*! \brief Bridge two channels together */
07287 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
07288                  struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
07289 {
07290    struct ast_channel *chans[2] = { c0, c1 };
07291    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
07292    format_t o0nativeformats;
07293    format_t o1nativeformats;
07294    long time_left_ms=0;
07295    char caller_warning = 0;
07296    char callee_warning = 0;
07297 
07298    *fo = NULL;
07299 
07300    if (c0->_bridge) {
07301       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
07302          c0->name, c0->_bridge->name);
07303       return -1;
07304    }
07305    if (c1->_bridge) {
07306       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
07307          c1->name, c1->_bridge->name);
07308       return -1;
07309    }
07310    
07311    /* Stop if we're a zombie or need a soft hangup */
07312    if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
07313        ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
07314       return -1;
07315 
07316    caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
07317    callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
07318 
07319    if (ast_tvzero(config->start_time)) {
07320       config->start_time = ast_tvnow();
07321       if (config->start_sound) {
07322          if (caller_warning) {
07323             bridge_playfile(c0, c1, config->start_sound, config->timelimit / 1000);
07324          }
07325          if (callee_warning) {
07326             bridge_playfile(c1, c0, config->start_sound, config->timelimit / 1000);
07327          }
07328       }
07329    }
07330 
07331    /* Keep track of bridge */
07332    c0->_bridge = c1;
07333    c1->_bridge = c0;
07334 
07335    ast_set_owners_and_peers(c0, c1);
07336 
07337    o0nativeformats = c0->nativeformats;
07338    o1nativeformats = c1->nativeformats;
07339 
07340    if (config->feature_timer && !ast_tvzero(config->nexteventts)) {
07341       config->nexteventts = ast_tvadd(config->feature_start_time, ast_samp2tv(config->feature_timer, 1000));
07342    } else if (config->timelimit) {
07343       time_left_ms = config->timelimit - ast_tvdiff_ms(ast_tvnow(), config->start_time);
07344       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
07345       if ((caller_warning || callee_warning) && config->play_warning) {
07346          long next_warn = config->play_warning;
07347          if (time_left_ms < config->play_warning && config->warning_freq > 0) {
07348             /* At least one warning was played, which means we are returning after feature */
07349             long warns_passed = (config->play_warning - time_left_ms) / config->warning_freq;
07350             /* It is 'warns_passed * warning_freq' NOT '(warns_passed + 1) * warning_freq',
07351                because nexteventts will be updated once again in the 'if (!to)' block */
07352             next_warn = config->play_warning - warns_passed * config->warning_freq;
07353          }
07354          config->nexteventts = ast_tvsub(config->nexteventts, ast_samp2tv(next_warn, 1000));
07355       }
07356    } else {
07357       config->nexteventts.tv_sec = 0;
07358       config->nexteventts.tv_usec = 0;
07359    }
07360 
07361    if (!c0->tech->send_digit_begin)
07362       ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
07363    if (!c1->tech->send_digit_begin)
07364       ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
07365    manager_bridge_event(1, 1, c0, c1);
07366 
07367    /* Before we enter in and bridge these two together tell them both the source of audio has changed */
07368    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
07369    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
07370 
07371    for (/* ever */;;) {
07372       struct timeval now = { 0, };
07373       int to;
07374 
07375       to = -1;
07376 
07377       if (!ast_tvzero(config->nexteventts)) {
07378          now = ast_tvnow();
07379          to = ast_tvdiff_ms(config->nexteventts, now);
07380          if (to <= 0) {
07381             if (!config->timelimit) {
07382                res = AST_BRIDGE_COMPLETE;
07383                break;
07384             }
07385             to = 0;
07386          }
07387       }
07388 
07389       if (config->timelimit) {
07390          time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
07391          if (time_left_ms < to)
07392             to = time_left_ms;
07393 
07394          if (time_left_ms <= 0) {
07395             if (caller_warning && config->end_sound)
07396                bridge_playfile(c0, c1, config->end_sound, 0);
07397             if (callee_warning && config->end_sound)
07398                bridge_playfile(c1, c0, config->end_sound, 0);
07399             *fo = NULL;
07400             res = 0;
07401             break;
07402          }
07403 
07404          if (!to) {
07405             if (time_left_ms >= 5000 && config->warning_sound && config->play_warning && ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
07406                int t = (time_left_ms + 500) / 1000; /* round to nearest second */
07407                if (caller_warning)
07408                   bridge_playfile(c0, c1, config->warning_sound, t);
07409                if (callee_warning)
07410                   bridge_playfile(c1, c0, config->warning_sound, t);
07411             }
07412 
07413             if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000))) {
07414                config->nexteventts = ast_tvadd(config->nexteventts, ast_samp2tv(config->warning_freq, 1000));
07415             } else {
07416                config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
07417             }
07418          }
07419          ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
07420       }
07421 
07422       if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
07423          if (c0->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
07424             ast_channel_clear_softhangup(c0, AST_SOFTHANGUP_UNBRIDGE);
07425          }
07426          if (c1->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
07427             ast_channel_clear_softhangup(c1, AST_SOFTHANGUP_UNBRIDGE);
07428          }
07429          c0->_bridge = c1;
07430          c1->_bridge = c0;
07431          ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
07432          continue;
07433       }
07434 
07435       /* Stop if we're a zombie or need a soft hangup */
07436       if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
07437           ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
07438          *fo = NULL;
07439          res = 0;
07440          ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
07441             c0->name, c1->name,
07442             ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
07443             ast_check_hangup(c0) ? "Yes" : "No",
07444             ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
07445             ast_check_hangup(c1) ? "Yes" : "No");
07446          break;
07447       }
07448 
07449       update_bridge_vars(c0, c1);
07450 
07451       bridge_play_sounds(c0, c1);
07452 
07453       if (c0->tech->bridge &&
07454          /* if < 1 ms remains use generic bridging for accurate timing */
07455          (!config->timelimit || to > 1000 || to == 0) &&
07456           (c0->tech->bridge == c1->tech->bridge) &&
07457           !c0->monitor && !c1->monitor &&
07458           !c0->audiohooks && !c1->audiohooks &&
07459           ast_framehook_list_is_empty(c0->framehooks) && ast_framehook_list_is_empty(c1->framehooks) &&
07460           !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
07461          int timeoutms = to - 1000 > 0 ? to - 1000 : to;
07462          /* Looks like they share a bridge method and nothing else is in the way */
07463          ast_set_flag(c0, AST_FLAG_NBRIDGE);
07464          ast_set_flag(c1, AST_FLAG_NBRIDGE);
07465          if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, timeoutms)) == AST_BRIDGE_COMPLETE) {
07466             ast_manager_event_multichan(EVENT_FLAG_CALL, "Unlink", 2, chans,
07467                "Channel1: %s\r\n"
07468                "Channel2: %s\r\n"
07469                "Uniqueid1: %s\r\n"
07470                "Uniqueid2: %s\r\n"
07471                "CallerID1: %s\r\n"
07472                "CallerID2: %s\r\n",
07473                c0->name, c1->name,
07474                c0->uniqueid, c1->uniqueid,
07475                S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, "<unknown>"),
07476                S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, "<unknown>"));
07477 
07478             ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
07479 
07480             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
07481             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
07482 
07483             if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
07484                continue;
07485             }
07486 
07487             c0->_bridge = NULL;
07488             c1->_bridge = NULL;
07489             return res;
07490          } else {
07491             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
07492             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
07493          }
07494          switch (res) {
07495          case AST_BRIDGE_RETRY:
07496             if (config->play_warning) {
07497                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
07498             }
07499             continue;
07500          default:
07501             ast_verb(3, "Native bridging %s and %s ended\n", c0->name, c1->name);
07502             /* fallthrough */
07503          case AST_BRIDGE_FAILED_NOWARN:
07504             break;
07505          }
07506       }
07507 
07508       if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
07509           (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
07510           !(c0->generator || c1->generator)) {
07511          if (ast_channel_make_compatible(c0, c1)) {
07512             ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
07513             manager_bridge_event(0, 1, c0, c1);
07514             return AST_BRIDGE_FAILED;
07515          }
07516          o0nativeformats = c0->nativeformats;
07517          o1nativeformats = c1->nativeformats;
07518       }
07519 
07520       update_bridge_vars(c0, c1);
07521 
07522       res = ast_generic_bridge(c0, c1, config, fo, rc);
07523       if (res != AST_BRIDGE_RETRY) {
07524          break;
07525       } else if (config->feature_timer) {
07526          /* feature timer expired but has not been updated, sending to ast_bridge_call to do so */
07527          break;
07528       }
07529    }
07530 
07531    ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
07532    ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
07533 
07534    /* Now that we have broken the bridge the source will change yet again */
07535    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
07536    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
07537 
07538    c0->_bridge = NULL;
07539    c1->_bridge = NULL;
07540 
07541    ast_manager_event_multichan(EVENT_FLAG_CALL, "Unlink", 2, chans,
07542       "Channel1: %s\r\n"
07543       "Channel2: %s\r\n"
07544       "Uniqueid1: %s\r\n"
07545       "Uniqueid2: %s\r\n"
07546       "CallerID1: %s\r\n"
07547       "CallerID2: %s\r\n",
07548       c0->name, c1->name,
07549       c0->uniqueid, c1->uniqueid,
07550       S_COR(c0->caller.id.number.valid, c0->caller.id.number.str, "<unknown>"),
07551       S_COR(c1->caller.id.number.valid, c1->caller.id.number.str, "<unknown>"));
07552    ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
07553 
07554    return res;
07555 }
07556 
07557 /*! \brief Sets an option on a channel */
07558 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
07559 {
07560    int res;
07561 
07562    ast_channel_lock(chan);
07563    if (!chan->tech->setoption) {
07564       errno = ENOSYS;
07565       ast_channel_unlock(chan);
07566       return -1;
07567    }
07568 
07569    if (block)
07570       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
07571 
07572    res = chan->tech->setoption(chan, option, data, datalen);
07573    ast_channel_unlock(chan);
07574 
07575    return res;
07576 }
07577 
07578 int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
07579 {
07580    int res;
07581 
07582    ast_channel_lock(chan);
07583    if (!chan->tech->queryoption) {
07584       errno = ENOSYS;
07585       ast_channel_unlock(chan);
07586       return -1;
07587    }
07588 
07589    if (block)
07590       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
07591 
07592    res = chan->tech->queryoption(chan, option, data, datalen);
07593    ast_channel_unlock(chan);
07594 
07595    return res;
07596 }
07597 
07598 struct tonepair_def {
07599    int freq1;
07600    int freq2;
07601    int duration;
07602    int vol;
07603 };
07604 
07605 struct tonepair_state {
07606    int fac1;
07607    int fac2;
07608    int v1_1;
07609    int v2_1;
07610    int v3_1;
07611    int v1_2;
07612    int v2_2;
07613    int v3_2;
07614    format_t origwfmt;
07615    int pos;
07616    int duration;
07617    int modulate;
07618    struct ast_frame f;
07619    unsigned char offset[AST_FRIENDLY_OFFSET];
07620    short data[4000];
07621 };
07622 
07623 static void tonepair_release(struct ast_channel *chan, void *params)
07624 {
07625    struct tonepair_state *ts = params;
07626 
07627    if (chan)
07628       ast_set_write_format(chan, ts->origwfmt);
07629    ast_free(ts);
07630 }
07631 
07632 static void *tonepair_alloc(struct ast_channel *chan, void *params)
07633 {
07634    struct tonepair_state *ts;
07635    struct tonepair_def *td = params;
07636 
07637    if (!(ts = ast_calloc(1, sizeof(*ts))))
07638       return NULL;
07639    ts->origwfmt = chan->writeformat;
07640    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
07641       ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
07642       tonepair_release(NULL, ts);
07643       ts = NULL;
07644    } else {
07645       ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
07646       ts->v1_1 = 0;
07647       ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
07648       ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
07649       ts->v2_1 = 0;
07650       ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
07651       ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
07652       ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
07653       ts->duration = td->duration;
07654       ts->modulate = 0;
07655    }
07656    /* Let interrupts interrupt :) */
07657    ast_set_flag(chan, AST_FLAG_WRITE_INT);
07658    return ts;
07659 }
07660 
07661 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
07662 {
07663    struct tonepair_state *ts = data;
07664    int x;
07665 
07666    /* we need to prepare a frame with 16 * timelen samples as we're
07667     * generating SLIN audio
07668     */
07669    len = samples * 2;
07670 
07671    if (len > sizeof(ts->data) / 2 - 1) {
07672       ast_log(LOG_WARNING, "Can't generate that much data!\n");
07673       return -1;
07674    }
07675    memset(&ts->f, 0, sizeof(ts->f));
07676    for (x=0;x<len/2;x++) {
07677       ts->v1_1 = ts->v2_1;
07678       ts->v2_1 = ts->v3_1;
07679       ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
07680       
07681       ts->v1_2 = ts->v2_2;
07682       ts->v2_2 = ts->v3_2;
07683       ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
07684       if (ts->modulate) {
07685          int p;
07686          p = ts->v3_2 - 32768;
07687          if (p < 0) p = -p;
07688          p = ((p * 9) / 10) + 1;
07689          ts->data[x] = (ts->v3_1 * p) >> 15;
07690       } else
07691          ts->data[x] = ts->v3_1 + ts->v3_2; 
07692    }
07693    ts->f.frametype = AST_FRAME_VOICE;
07694    ts->f.subclass.codec = AST_FORMAT_SLINEAR;
07695    ts->f.datalen = len;
07696    ts->f.samples = samples;
07697    ts->f.offset = AST_FRIENDLY_OFFSET;
07698    ts->f.data.ptr = ts->data;
07699    ast_write(chan, &ts->f);
07700    ts->pos += x;
07701    if (ts->duration > 0) {
07702       if (ts->pos >= ts->duration * 8)
07703          return -1;
07704    }
07705    return 0;
07706 }
07707 
07708 static struct ast_generator tonepair = {
07709    .alloc = tonepair_alloc,
07710    .release = tonepair_release,
07711    .generate = tonepair_generator,
07712 };
07713 
07714 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
07715 {
07716    struct tonepair_def d = { 0, };
07717 
07718    d.freq1 = freq1;
07719    d.freq2 = freq2;
07720    d.duration = duration;
07721    d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
07722    if (ast_activate_generator(chan, &tonepair, &d))
07723       return -1;
07724    return 0;
07725 }
07726 
07727 void ast_tonepair_stop(struct ast_channel *chan)
07728 {
07729    ast_deactivate_generator(chan);
07730 }
07731 
07732 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
07733 {
07734    int res;
07735 
07736    if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
07737       return res;
07738 
07739    /* Give us some wiggle room */
07740    while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
07741       struct ast_frame *f = ast_read(chan);
07742       if (f)
07743          ast_frfree(f);
07744       else
07745          return -1;
07746    }
07747    return 0;
07748 }
07749 
07750 ast_group_t ast_get_group(const char *s)
07751 {
07752    char *piece;
07753    char *c;
07754    int start=0, finish=0, x;
07755    ast_group_t group = 0;
07756 
07757    if (ast_strlen_zero(s))
07758       return 0;
07759 
07760    c = ast_strdupa(s);
07761    
07762    while ((piece = strsep(&c, ","))) {
07763       if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) {
07764          /* Range */
07765       } else if (sscanf(piece, "%30d", &start)) {
07766          /* Just one */
07767          finish = start;
07768       } else {
07769          ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
07770          continue;
07771       }
07772       for (x = start; x <= finish; x++) {
07773          if ((x > 63) || (x < 0)) {
07774             ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
07775          } else
07776             group |= ((ast_group_t) 1 << x);
07777       }
07778    }
07779    return group;
07780 }
07781 
07782 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
07783 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
07784 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
07785 
07786 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
07787              void (*stop_ptr)(struct ast_channel *),
07788              void (*cleanup_ptr)(struct ast_channel *))
07789 {
07790    ast_moh_start_ptr = start_ptr;
07791    ast_moh_stop_ptr = stop_ptr;
07792    ast_moh_cleanup_ptr = cleanup_ptr;
07793 }
07794 
07795 void ast_uninstall_music_functions(void)
07796 {
07797    ast_moh_start_ptr = NULL;
07798    ast_moh_stop_ptr = NULL;
07799    ast_moh_cleanup_ptr = NULL;
07800 }
07801 
07802 /*! \brief Turn on music on hold on a given channel */
07803 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
07804 {
07805    if (ast_moh_start_ptr)
07806       return ast_moh_start_ptr(chan, mclass, interpclass);
07807 
07808    ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));
07809 
07810    return 0;
07811 }
07812 
07813 /*! \brief Turn off music on hold on a given channel */
07814 void ast_moh_stop(struct ast_channel *chan)
07815 {
07816    if (ast_moh_stop_ptr)
07817       ast_moh_stop_ptr(chan);
07818 }
07819 
07820 void ast_moh_cleanup(struct ast_channel *chan)
07821 {
07822    if (ast_moh_cleanup_ptr)
07823       ast_moh_cleanup_ptr(chan);
07824 }
07825 
07826 static int ast_channel_hash_cb(const void *obj, const int flags)
07827 {
07828    const struct ast_channel *chan = obj;
07829 
07830    /* If the name isn't set, return 0 so that the ao2_find() search will
07831     * start in the first bucket. */
07832    if (ast_strlen_zero(chan->name)) {
07833       return 0;
07834    }
07835 
07836    return ast_str_case_hash(chan->name);
07837 }
07838 
07839 int ast_plc_reload(void)
07840 {
07841    struct ast_variable *var;
07842    struct ast_flags config_flags = { 0 };
07843    struct ast_config *cfg = ast_config_load("codecs.conf", config_flags);
07844    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
07845       return 0;
07846    for (var = ast_variable_browse(cfg, "plc"); var; var = var->next) {
07847       if (!strcasecmp(var->name, "genericplc")) {
07848          ast_set2_flag(&ast_options, ast_true(var->value), AST_OPT_FLAG_GENERIC_PLC);
07849       }
07850    }
07851    ast_config_destroy(cfg);
07852    return 0;
07853 }
07854 
07855 /*!
07856  * \internal
07857  * \brief Implements the channels provider.
07858  */
07859 static int data_channels_provider_handler(const struct ast_data_search *search,
07860    struct ast_data *root)
07861 {
07862    struct ast_channel *c;
07863    struct ast_channel_iterator *iter = NULL;
07864    struct ast_data *data_channel;
07865 
07866    for (iter = ast_channel_iterator_all_new();
07867       iter && (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
07868       ast_channel_lock(c);
07869 
07870       data_channel = ast_data_add_node(root, "channel");
07871       if (!data_channel) {
07872          ast_channel_unlock(c);
07873          continue;
07874       }
07875 
07876       if (ast_channel_data_add_structure(data_channel, c, 1) < 0) {
07877          ast_log(LOG_ERROR, "Unable to add channel structure for channel: %s\n", c->name);
07878       }
07879 
07880       ast_channel_unlock(c);
07881 
07882       if (!ast_data_search_match(search, data_channel)) {
07883          ast_data_remove_node(root, data_channel);
07884       }
07885    }
07886    if (iter) {
07887       ast_channel_iterator_destroy(iter);
07888    }
07889 
07890    return 0;
07891 }
07892 
07893 /*!
07894  * \internal
07895  * \brief Implements the channeltypes provider.
07896  */
07897 static int data_channeltypes_provider_handler(const struct ast_data_search *search,
07898    struct ast_data *data_root)
07899 {
07900    struct chanlist *cl;
07901    struct ast_data *data_type;
07902 
07903    AST_RWLIST_RDLOCK(&backends);
07904    AST_RWLIST_TRAVERSE(&backends, cl, list) {
07905       data_type = ast_data_add_node(data_root, "type");
07906       if (!data_type) {
07907          continue;
07908       }
07909       ast_data_add_str(data_type, "name", cl->tech->type);
07910       ast_data_add_str(data_type, "description", cl->tech->description);
07911       ast_data_add_bool(data_type, "devicestate", cl->tech->devicestate ? 1 : 0);
07912       ast_data_add_bool(data_type, "indications", cl->tech->indicate ? 1 : 0);
07913       ast_data_add_bool(data_type, "transfer", cl->tech->transfer ? 1 : 0);
07914       ast_data_add_bool(data_type, "send_digit_begin", cl->tech->send_digit_begin ? 1 : 0);
07915       ast_data_add_bool(data_type, "send_digit_end", cl->tech->send_digit_end ? 1 : 0);
07916       ast_data_add_bool(data_type, "call", cl->tech->call ? 1 : 0);
07917       ast_data_add_bool(data_type, "hangup", cl->tech->hangup ? 1 : 0);
07918       ast_data_add_bool(data_type, "answer", cl->tech->answer ? 1 : 0);
07919       ast_data_add_bool(data_type, "read", cl->tech->read ? 1 : 0);
07920       ast_data_add_bool(data_type, "write", cl->tech->write ? 1 : 0);
07921       ast_data_add_bool(data_type, "send_text", cl->tech->send_text ? 1 : 0);
07922       ast_data_add_bool(data_type, "send_image", cl->tech->send_image ? 1 : 0);
07923       ast_data_add_bool(data_type, "send_html", cl->tech->send_html ? 1 : 0);
07924       ast_data_add_bool(data_type, "exception", cl->tech->exception ? 1 : 0);
07925       ast_data_add_bool(data_type, "bridge", cl->tech->bridge ? 1 : 0);
07926       ast_data_add_bool(data_type, "early_bridge", cl->tech->early_bridge ? 1 : 0);
07927       ast_data_add_bool(data_type, "fixup", cl->tech->fixup ? 1 : 0);
07928       ast_data_add_bool(data_type, "setoption", cl->tech->setoption ? 1 : 0);
07929       ast_data_add_bool(data_type, "queryoption", cl->tech->queryoption ? 1 : 0);
07930       ast_data_add_bool(data_type, "write_video", cl->tech->write_video ? 1 : 0);
07931       ast_data_add_bool(data_type, "write_text", cl->tech->write_text ? 1 : 0);
07932       ast_data_add_bool(data_type, "bridged_channel", cl->tech->bridged_channel ? 1 : 0);
07933       ast_data_add_bool(data_type, "func_channel_read", cl->tech->func_channel_read ? 1 : 0);
07934       ast_data_add_bool(data_type, "func_channel_write", cl->tech->func_channel_write ? 1 : 0);
07935       ast_data_add_bool(data_type, "get_base_channel", cl->tech->get_base_channel ? 1 : 0);
07936       ast_data_add_bool(data_type, "set_base_channel", cl->tech->set_base_channel ? 1 : 0);
07937       ast_data_add_bool(data_type, "get_pvt_uniqueid", cl->tech->get_pvt_uniqueid ? 1 : 0);
07938       ast_data_add_bool(data_type, "cc_callback", cl->tech->cc_callback ? 1 : 0);
07939 
07940       ast_data_add_codecs(data_type, "capabilities", cl->tech->capabilities);
07941 
07942       if (!ast_data_search_match(search, data_type)) {
07943          ast_data_remove_node(data_root, data_type);
07944       }
07945    }
07946    AST_RWLIST_UNLOCK(&backends);
07947 
07948    return 0;
07949 }
07950 
07951 /*!
07952  * \internal
07953  * \brief /asterisk/core/channels provider.
07954  */
07955 static const struct ast_data_handler channels_provider = {
07956    .version = AST_DATA_HANDLER_VERSION,
07957    .get = data_channels_provider_handler
07958 };
07959 
07960 /*!
07961  * \internal
07962  * \brief /asterisk/core/channeltypes provider.
07963  */
07964 static const struct ast_data_handler channeltypes_provider = {
07965    .version = AST_DATA_HANDLER_VERSION,
07966    .get = data_channeltypes_provider_handler
07967 };
07968 
07969 static const struct ast_data_entry channel_providers[] = {
07970    AST_DATA_ENTRY("/asterisk/core/channels", &channels_provider),
07971    AST_DATA_ENTRY("/asterisk/core/channeltypes", &channeltypes_provider),
07972 };
07973 
07974 void ast_channels_init(void)
07975 {
07976    channels = ao2_container_alloc(NUM_CHANNEL_BUCKETS,
07977          ast_channel_hash_cb, ast_channel_cmp_cb);
07978 
07979    ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));
07980 
07981    ast_data_register_multiple_core(channel_providers, ARRAY_LEN(channel_providers));
07982 
07983    ast_plc_reload();
07984 }
07985 
07986 /*! \brief Print call group and pickup group ---*/
07987 char *ast_print_group(char *buf, int buflen, ast_group_t group)
07988 {
07989    unsigned int i;
07990    int first = 1;
07991    char num[3];
07992 
07993    buf[0] = '\0';
07994    
07995    if (!group) /* Return empty string if no group */
07996       return buf;
07997 
07998    for (i = 0; i <= 63; i++) {   /* Max group is 63 */
07999       if (group & ((ast_group_t) 1 << i)) {
08000             if (!first) {
08001             strncat(buf, ", ", buflen - strlen(buf) - 1);
08002          } else {
08003             first = 0;
08004          }
08005          snprintf(num, sizeof(num), "%u", i);
08006          strncat(buf, num, buflen - strlen(buf) - 1);
08007       }
08008    }
08009    return buf;
08010 }
08011 
08012 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
08013 {
08014    struct ast_variable *cur;
08015 
08016    for (cur = vars; cur; cur = cur->next)
08017       pbx_builtin_setvar_helper(chan, cur->name, cur->value);  
08018 }
08019 
08020 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
08021 {
08022    /* just store the data pointer in the channel structure */
08023    return data;
08024 }
08025 
08026 static void silence_generator_release(struct ast_channel *chan, void *data)
08027 {
08028    /* nothing to do */
08029 }
08030 
08031 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
08032 {
08033    short buf[samples];
08034    struct ast_frame frame = {
08035       .frametype = AST_FRAME_VOICE,
08036       .subclass.codec = AST_FORMAT_SLINEAR,
08037       .data.ptr = buf,
08038       .samples = samples,
08039       .datalen = sizeof(buf),
08040    };
08041 
08042    memset(buf, 0, sizeof(buf));
08043 
08044    if (ast_write(chan, &frame))
08045       return -1;
08046 
08047    return 0;
08048 }
08049 
08050 static struct ast_generator silence_generator = {
08051    .alloc = silence_generator_alloc,
08052    .release = silence_generator_release,
08053    .generate = silence_generator_generate,
08054 };
08055 
08056 struct ast_silence_generator {
08057    int old_write_format;
08058 };
08059 
08060 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
08061 {
08062    struct ast_silence_generator *state;
08063 
08064    if (!(state = ast_calloc(1, sizeof(*state)))) {
08065       return NULL;
08066    }
08067 
08068    state->old_write_format = chan->writeformat;
08069 
08070    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
08071       ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
08072       ast_free(state);
08073       return NULL;
08074    }
08075 
08076    ast_activate_generator(chan, &silence_generator, state);
08077 
08078    ast_debug(1, "Started silence generator on '%s'\n", chan->name);
08079 
08080    return state;
08081 }
08082 
08083 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
08084 {
08085    if (!state)
08086       return;
08087 
08088    ast_deactivate_generator(chan);
08089 
08090    ast_debug(1, "Stopped silence generator on '%s'\n", chan->name);
08091 
08092    if (ast_set_write_format(chan, state->old_write_format) < 0)
08093       ast_log(LOG_ERROR, "Could not return write format to its original state\n");
08094 
08095    ast_free(state);
08096 }
08097 
08098 
08099 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
08100 const char *channelreloadreason2txt(enum channelreloadreason reason)
08101 {
08102    switch (reason) {
08103    case CHANNEL_MODULE_LOAD:
08104       return "LOAD (Channel module load)";
08105 
08106    case CHANNEL_MODULE_RELOAD:
08107       return "RELOAD (Channel module reload)";
08108 
08109    case CHANNEL_CLI_RELOAD:
08110       return "CLIRELOAD (Channel module reload by CLI command)";
08111 
08112    default:
08113       return "MANAGERRELOAD (Channel module reload by manager)";
08114    }
08115 };
08116 
08117 /*
08118  * Wrappers for various ast_say_*() functions that call the full version
08119  * of the same functions.
08120  * The proper place would be say.c, but that file is optional and one
08121  * must be able to build asterisk even without it (using a loadable 'say'
08122  * implementation that only supplies the 'full' version of the functions.
08123  */
08124 
08125 int ast_say_number(struct ast_channel *chan, int num,
08126    const char *ints, const char *language, const char *options)
08127 {
08128    return ast_say_number_full(chan, num, ints, language, options, -1, -1);
08129 }
08130 
08131 int ast_say_enumeration(struct ast_channel *chan, int num,
08132    const char *ints, const char *language, const char *options)
08133 {
08134    return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
08135 }
08136 
08137 int ast_say_digits(struct ast_channel *chan, int num,
08138    const char *ints, const char *lang)
08139 {
08140    return ast_say_digits_full(chan, num, ints, lang, -1, -1);
08141 }
08142 
08143 int ast_say_digit_str(struct ast_channel *chan, const char *str,
08144    const char *ints, const char *lang)
08145 {
08146    return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
08147 }
08148 
08149 int ast_say_character_str(struct ast_channel *chan, const char *str,
08150    const char *ints, const char *lang)
08151 {
08152    return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
08153 }
08154 
08155 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
08156    const char *ints, const char *lang)
08157 {
08158    return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
08159 }
08160 
08161 int ast_say_digits_full(struct ast_channel *chan, int num,
08162    const char *ints, const char *lang, int audiofd, int ctrlfd)
08163 {
08164    char buf[256];
08165 
08166    snprintf(buf, sizeof(buf), "%d", num);
08167 
08168    return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
08169 }
08170 
08171 void ast_connected_line_copy_from_caller(struct ast_party_connected_line *dest, const struct ast_party_caller *src)
08172 {
08173    ast_party_id_copy(&dest->id, &src->id);
08174    ast_party_id_copy(&dest->ani, &src->ani);
08175    dest->ani2 = src->ani2;
08176 }
08177 
08178 void ast_connected_line_copy_to_caller(struct ast_party_caller *dest, const struct ast_party_connected_line *src)
08179 {
08180    ast_party_id_copy(&dest->id, &src->id);
08181    ast_party_id_copy(&dest->ani, &src->ani);
08182 
08183    dest->ani2 = src->ani2;
08184 }
08185 
08186 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)
08187 {
08188    if (&chan->connected == connected) {
08189       /* Don't set to self */
08190       return;
08191    }
08192 
08193    ast_channel_lock(chan);
08194    ast_party_connected_line_set(&chan->connected, connected, update);
08195    ast_channel_unlock(chan);
08196 }
08197 
08198 /*! \note Should follow struct ast_party_name */
08199 struct ast_party_name_ies {
08200    /*! \brief Subscriber name ie */
08201    int str;
08202    /*! \brief Character set ie. */
08203    int char_set;
08204    /*! \brief presentation-indicator ie */
08205    int presentation;
08206    /*! \brief valid/present ie */
08207    int valid;
08208 };
08209 
08210 /*!
08211  * \internal
08212  * \since 1.8
08213  * \brief Build a party name information data frame component.
08214  *
08215  * \param data Buffer to fill with the frame data
08216  * \param datalen Size of the buffer to fill
08217  * \param name Party name information
08218  * \param label Name of particular party name
08219  * \param ies Data frame ie values for the party name components
08220  *
08221  * \retval -1 if error
08222  * \retval Amount of data buffer used
08223  */
08224 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)
08225 {
08226    size_t length;
08227    size_t pos = 0;
08228 
08229    /*
08230     * The size of integer values must be fixed in case the frame is
08231     * shipped to another machine.
08232     */
08233    if (name->str) {
08234       length = strlen(name->str);
08235       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
08236          ast_log(LOG_WARNING, "No space left for %s name\n", label);
08237          return -1;
08238       }
08239       data[pos++] = ies->str;
08240       data[pos++] = length;
08241       memcpy(data + pos, name->str, length);
08242       pos += length;
08243    }
08244 
08245    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08246       ast_log(LOG_WARNING, "No space left for %s name char set\n", label);
08247       return -1;
08248    }
08249    data[pos++] = ies->char_set;
08250    data[pos++] = 1;
08251    data[pos++] = name->char_set;
08252 
08253    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08254       ast_log(LOG_WARNING, "No space left for %s name presentation\n", label);
08255       return -1;
08256    }
08257    data[pos++] = ies->presentation;
08258    data[pos++] = 1;
08259    data[pos++] = name->presentation;
08260 
08261    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08262       ast_log(LOG_WARNING, "No space left for %s name valid\n", label);
08263       return -1;
08264    }
08265    data[pos++] = ies->valid;
08266    data[pos++] = 1;
08267    data[pos++] = name->valid;
08268 
08269    return pos;
08270 }
08271 
08272 /*! \note Should follow struct ast_party_number */
08273 struct ast_party_number_ies {
08274    /*! \brief Subscriber phone number ie */
08275    int str;
08276    /*! \brief Type-Of-Number and Numbering-Plan ie */
08277    int plan;
08278    /*! \brief presentation-indicator ie */
08279    int presentation;
08280    /*! \brief valid/present ie */
08281    int valid;
08282 };
08283 
08284 /*!
08285  * \internal
08286  * \since 1.8
08287  * \brief Build a party number information data frame component.
08288  *
08289  * \param data Buffer to fill with the frame data
08290  * \param datalen Size of the buffer to fill
08291  * \param number Party number information
08292  * \param label Name of particular party number
08293  * \param ies Data frame ie values for the party number components
08294  *
08295  * \retval -1 if error
08296  * \retval Amount of data buffer used
08297  */
08298 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)
08299 {
08300    size_t length;
08301    size_t pos = 0;
08302 
08303    /*
08304     * The size of integer values must be fixed in case the frame is
08305     * shipped to another machine.
08306     */
08307    if (number->str) {
08308       length = strlen(number->str);
08309       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
08310          ast_log(LOG_WARNING, "No space left for %s number\n", label);
08311          return -1;
08312       }
08313       data[pos++] = ies->str;
08314       data[pos++] = length;
08315       memcpy(data + pos, number->str, length);
08316       pos += length;
08317    }
08318 
08319    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08320       ast_log(LOG_WARNING, "No space left for %s numbering plan\n", label);
08321       return -1;
08322    }
08323    data[pos++] = ies->plan;
08324    data[pos++] = 1;
08325    data[pos++] = number->plan;
08326 
08327    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08328       ast_log(LOG_WARNING, "No space left for %s number presentation\n", label);
08329       return -1;
08330    }
08331    data[pos++] = ies->presentation;
08332    data[pos++] = 1;
08333    data[pos++] = number->presentation;
08334 
08335    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08336       ast_log(LOG_WARNING, "No space left for %s number valid\n", label);
08337       return -1;
08338    }
08339    data[pos++] = ies->valid;
08340    data[pos++] = 1;
08341    data[pos++] = number->valid;
08342 
08343    return pos;
08344 }
08345 
08346 /*! \note Should follow struct ast_party_subaddress */
08347 struct ast_party_subaddress_ies {
08348    /*! \brief subaddress ie. */
08349    int str;
08350    /*! \brief subaddress type ie */
08351    int type;
08352    /*! \brief odd/even indicator ie */
08353    int odd_even_indicator;
08354    /*! \brief valid/present ie */
08355    int valid;
08356 };
08357 
08358 /*!
08359  * \internal
08360  * \since 1.8
08361  * \brief Build a party subaddress information data frame component.
08362  *
08363  * \param data Buffer to fill with the frame data
08364  * \param datalen Size of the buffer to fill
08365  * \param subaddress Party subaddress information
08366  * \param label Name of particular party subaddress
08367  * \param ies Data frame ie values for the party subaddress components
08368  *
08369  * \retval -1 if error
08370  * \retval Amount of data buffer used
08371  */
08372 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)
08373 {
08374    size_t length;
08375    size_t pos = 0;
08376 
08377    /*
08378     * The size of integer values must be fixed in case the frame is
08379     * shipped to another machine.
08380     */
08381    if (subaddress->str) {
08382       length = strlen(subaddress->str);
08383       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
08384          ast_log(LOG_WARNING, "No space left for %s subaddress\n", label);
08385          return -1;
08386       }
08387       data[pos++] = ies->str;
08388       data[pos++] = length;
08389       memcpy(data + pos, subaddress->str, length);
08390       pos += length;
08391    }
08392 
08393    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08394       ast_log(LOG_WARNING, "No space left for %s type of subaddress\n", label);
08395       return -1;
08396    }
08397    data[pos++] = ies->type;
08398    data[pos++] = 1;
08399    data[pos++] = subaddress->type;
08400 
08401    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08402       ast_log(LOG_WARNING,
08403          "No space left for %s subaddress odd-even indicator\n", label);
08404       return -1;
08405    }
08406    data[pos++] = ies->odd_even_indicator;
08407    data[pos++] = 1;
08408    data[pos++] = subaddress->odd_even_indicator;
08409 
08410    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08411       ast_log(LOG_WARNING, "No space left for %s subaddress valid\n", label);
08412       return -1;
08413    }
08414    data[pos++] = ies->valid;
08415    data[pos++] = 1;
08416    data[pos++] = subaddress->valid;
08417 
08418    return pos;
08419 }
08420 
08421 /*! \note Should follow struct ast_party_id */
08422 struct ast_party_id_ies {
08423    /*! \brief Subscriber name ies */
08424    struct ast_party_name_ies name;
08425    /*! \brief Subscriber phone number ies */
08426    struct ast_party_number_ies number;
08427    /*! \brief Subscriber subaddress ies. */
08428    struct ast_party_subaddress_ies subaddress;
08429    /*! \brief User party id tag ie. */
08430    int tag;
08431    /*! \brief Combined name and number presentation ie. */
08432    int combined_presentation;
08433 };
08434 
08435 /*!
08436  * \internal
08437  * \since 1.8
08438  * \brief Build a party id information data frame component.
08439  *
08440  * \param data Buffer to fill with the frame data
08441  * \param datalen Size of the buffer to fill
08442  * \param id Party id information
08443  * \param label Name of particular party id
08444  * \param ies Data frame ie values for the party id components
08445  * \param update What id information to build.  NULL if all.
08446  *
08447  * \retval -1 if error
08448  * \retval Amount of data buffer used
08449  */
08450 static int party_id_build_data(unsigned char *data, size_t datalen,
08451    const struct ast_party_id *id, const char *label, const struct ast_party_id_ies *ies,
08452    const struct ast_set_party_id *update)
08453 {
08454    size_t length;
08455    size_t pos = 0;
08456    int res;
08457 
08458    /*
08459     * The size of integer values must be fixed in case the frame is
08460     * shipped to another machine.
08461     */
08462 
08463    if (!update || update->name) {
08464       res = party_name_build_data(data + pos, datalen - pos, &id->name, label,
08465          &ies->name);
08466       if (res < 0) {
08467          return -1;
08468       }
08469       pos += res;
08470    }
08471 
08472    if (!update || update->number) {
08473       res = party_number_build_data(data + pos, datalen - pos, &id->number, label,
08474          &ies->number);
08475       if (res < 0) {
08476          return -1;
08477       }
08478       pos += res;
08479    }
08480 
08481    if (!update || update->subaddress) {
08482       res = party_subaddress_build_data(data + pos, datalen - pos, &id->subaddress,
08483          label, &ies->subaddress);
08484       if (res < 0) {
08485          return -1;
08486       }
08487       pos += res;
08488    }
08489 
08490    /* *************** Party id user tag **************************** */
08491    if (id->tag) {
08492       length = strlen(id->tag);
08493       if (datalen < pos + (sizeof(data[0]) * 2) + length) {
08494          ast_log(LOG_WARNING, "No space left for %s tag\n", label);
08495          return -1;
08496       }
08497       data[pos++] = ies->tag;
08498       data[pos++] = length;
08499       memcpy(data + pos, id->tag, length);
08500       pos += length;
08501    }
08502 
08503    /* *************** Party id combined presentation *************** */
08504    if (!update || update->number) {
08505       int presentation;
08506 
08507       if (!update || update->name) {
08508          presentation = ast_party_id_presentation(id);
08509       } else {
08510          /*
08511           * We must compromise because not all the information is available
08512           * to determine a combined presentation value.
08513           * We will only send the number presentation instead.
08514           */
08515          presentation = id->number.presentation;
08516       }
08517 
08518       if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08519          ast_log(LOG_WARNING, "No space left for %s combined presentation\n", label);
08520          return -1;
08521       }
08522       data[pos++] = ies->combined_presentation;
08523       data[pos++] = 1;
08524       data[pos++] = presentation;
08525    }
08526 
08527    return pos;
08528 }
08529 
08530 /*!
08531  * \brief Element identifiers for connected line indication frame data
08532  * \note Only add to the end of this enum.
08533  */
08534 enum {
08535    AST_CONNECTED_LINE_NUMBER,
08536    AST_CONNECTED_LINE_NAME,
08537    AST_CONNECTED_LINE_NUMBER_PLAN,
08538    AST_CONNECTED_LINE_ID_PRESENTATION,/* Combined number and name presentation. */
08539    AST_CONNECTED_LINE_SOURCE,
08540    AST_CONNECTED_LINE_SUBADDRESS,
08541    AST_CONNECTED_LINE_SUBADDRESS_TYPE,
08542    AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
08543    AST_CONNECTED_LINE_SUBADDRESS_VALID,
08544    AST_CONNECTED_LINE_TAG,
08545    AST_CONNECTED_LINE_VERSION,
08546    AST_CONNECTED_LINE_NAME_VALID,
08547    AST_CONNECTED_LINE_NAME_CHAR_SET,
08548    AST_CONNECTED_LINE_NAME_PRESENTATION,
08549    AST_CONNECTED_LINE_NUMBER_VALID,
08550    AST_CONNECTED_LINE_NUMBER_PRESENTATION,
08551 };
08552 
08553 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)
08554 {
08555    int32_t value;
08556    size_t pos = 0;
08557    int res;
08558 
08559    static const struct ast_party_id_ies ies = {
08560       .name.str = AST_CONNECTED_LINE_NAME,
08561       .name.char_set = AST_CONNECTED_LINE_NAME_CHAR_SET,
08562       .name.presentation = AST_CONNECTED_LINE_NAME_PRESENTATION,
08563       .name.valid = AST_CONNECTED_LINE_NAME_VALID,
08564 
08565       .number.str = AST_CONNECTED_LINE_NUMBER,
08566       .number.plan = AST_CONNECTED_LINE_NUMBER_PLAN,
08567       .number.presentation = AST_CONNECTED_LINE_NUMBER_PRESENTATION,
08568       .number.valid = AST_CONNECTED_LINE_NUMBER_VALID,
08569 
08570       .subaddress.str = AST_CONNECTED_LINE_SUBADDRESS,
08571       .subaddress.type = AST_CONNECTED_LINE_SUBADDRESS_TYPE,
08572       .subaddress.odd_even_indicator = AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN,
08573       .subaddress.valid = AST_CONNECTED_LINE_SUBADDRESS_VALID,
08574 
08575       .tag = AST_CONNECTED_LINE_TAG,
08576       .combined_presentation = AST_CONNECTED_LINE_ID_PRESENTATION,
08577    };
08578 
08579    /*
08580     * The size of integer values must be fixed in case the frame is
08581     * shipped to another machine.
08582     */
08583 
08584    /* Connected line frame version */
08585    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08586       ast_log(LOG_WARNING, "No space left for connected line frame version\n");
08587       return -1;
08588    }
08589    data[pos++] = AST_CONNECTED_LINE_VERSION;
08590    data[pos++] = 1;
08591    data[pos++] = 2;/* Version 1 did not have a version ie */
08592 
08593    res = party_id_build_data(data + pos, datalen - pos, &connected->id,
08594       "connected line", &ies, update ? &update->id : NULL);
08595    if (res < 0) {
08596       return -1;
08597    }
08598    pos += res;
08599 
08600    /* Connected line source */
08601    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08602       ast_log(LOG_WARNING, "No space left for connected line source\n");
08603       return -1;
08604    }
08605    data[pos++] = AST_CONNECTED_LINE_SOURCE;
08606    data[pos++] = sizeof(value);
08607    value = htonl(connected->source);
08608    memcpy(data + pos, &value, sizeof(value));
08609    pos += sizeof(value);
08610 
08611    return pos;
08612 }
08613 
08614 int ast_connected_line_parse_data(const unsigned char *data, size_t datalen, struct ast_party_connected_line *connected)
08615 {
08616    size_t pos;
08617    unsigned char ie_len;
08618    unsigned char ie_id;
08619    int32_t value;
08620    int frame_version = 1;
08621    int combined_presentation = 0;
08622    int got_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08623 
08624    for (pos = 0; pos < datalen; pos += ie_len) {
08625       if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
08626          ast_log(LOG_WARNING, "Invalid connected line update\n");
08627          return -1;
08628       }
08629       ie_id = data[pos++];
08630       ie_len = data[pos++];
08631       if (datalen < pos + ie_len) {
08632          ast_log(LOG_WARNING, "Invalid connected line update\n");
08633          return -1;
08634       }
08635 
08636       switch (ie_id) {
08637 /* Connected line party frame version */
08638       case AST_CONNECTED_LINE_VERSION:
08639          if (ie_len != 1) {
08640             ast_log(LOG_WARNING, "Invalid connected line frame version (%u)\n",
08641                (unsigned) ie_len);
08642             break;
08643          }
08644          frame_version = data[pos];
08645          break;
08646 /* Connected line party id name */
08647       case AST_CONNECTED_LINE_NAME:
08648          ast_free(connected->id.name.str);
08649          connected->id.name.str = ast_malloc(ie_len + 1);
08650          if (connected->id.name.str) {
08651             memcpy(connected->id.name.str, data + pos, ie_len);
08652             connected->id.name.str[ie_len] = 0;
08653          }
08654          break;
08655       case AST_CONNECTED_LINE_NAME_CHAR_SET:
08656          if (ie_len != 1) {
08657             ast_log(LOG_WARNING, "Invalid connected line name char set (%u)\n",
08658                (unsigned) ie_len);
08659             break;
08660          }
08661          connected->id.name.char_set = data[pos];
08662          break;
08663       case AST_CONNECTED_LINE_NAME_PRESENTATION:
08664          if (ie_len != 1) {
08665             ast_log(LOG_WARNING, "Invalid connected line name presentation (%u)\n",
08666                (unsigned) ie_len);
08667             break;
08668          }
08669          connected->id.name.presentation = data[pos];
08670          break;
08671       case AST_CONNECTED_LINE_NAME_VALID:
08672          if (ie_len != 1) {
08673             ast_log(LOG_WARNING, "Invalid connected line name valid (%u)\n",
08674                (unsigned) ie_len);
08675             break;
08676          }
08677          connected->id.name.valid = data[pos];
08678          break;
08679 /* Connected line party id number */
08680       case AST_CONNECTED_LINE_NUMBER:
08681          ast_free(connected->id.number.str);
08682          connected->id.number.str = ast_malloc(ie_len + 1);
08683          if (connected->id.number.str) {
08684             memcpy(connected->id.number.str, data + pos, ie_len);
08685             connected->id.number.str[ie_len] = 0;
08686          }
08687          break;
08688       case AST_CONNECTED_LINE_NUMBER_PLAN:
08689          if (ie_len != 1) {
08690             ast_log(LOG_WARNING, "Invalid connected line numbering plan (%u)\n",
08691                (unsigned) ie_len);
08692             break;
08693          }
08694          connected->id.number.plan = data[pos];
08695          break;
08696       case AST_CONNECTED_LINE_NUMBER_PRESENTATION:
08697          if (ie_len != 1) {
08698             ast_log(LOG_WARNING, "Invalid connected line number presentation (%u)\n",
08699                (unsigned) ie_len);
08700             break;
08701          }
08702          connected->id.number.presentation = data[pos];
08703          break;
08704       case AST_CONNECTED_LINE_NUMBER_VALID:
08705          if (ie_len != 1) {
08706             ast_log(LOG_WARNING, "Invalid connected line number valid (%u)\n",
08707                (unsigned) ie_len);
08708             break;
08709          }
08710          connected->id.number.valid = data[pos];
08711          break;
08712 /* Connected line party id combined presentation */
08713       case AST_CONNECTED_LINE_ID_PRESENTATION:
08714          if (ie_len != 1) {
08715             ast_log(LOG_WARNING, "Invalid connected line combined presentation (%u)\n",
08716                (unsigned) ie_len);
08717             break;
08718          }
08719          combined_presentation = data[pos];
08720          got_combined_presentation = 1;
08721          break;
08722 /* Connected line party id subaddress */
08723       case AST_CONNECTED_LINE_SUBADDRESS:
08724          ast_free(connected->id.subaddress.str);
08725          connected->id.subaddress.str = ast_malloc(ie_len + 1);
08726          if (connected->id.subaddress.str) {
08727             memcpy(connected->id.subaddress.str, data + pos, ie_len);
08728             connected->id.subaddress.str[ie_len] = 0;
08729          }
08730          break;
08731       case AST_CONNECTED_LINE_SUBADDRESS_TYPE:
08732          if (ie_len != 1) {
08733             ast_log(LOG_WARNING, "Invalid connected line type of subaddress (%u)\n",
08734                (unsigned) ie_len);
08735             break;
08736          }
08737          connected->id.subaddress.type = data[pos];
08738          break;
08739       case AST_CONNECTED_LINE_SUBADDRESS_ODD_EVEN:
08740          if (ie_len != 1) {
08741             ast_log(LOG_WARNING,
08742                "Invalid connected line subaddress odd-even indicator (%u)\n",
08743                (unsigned) ie_len);
08744             break;
08745          }
08746          connected->id.subaddress.odd_even_indicator = data[pos];
08747          break;
08748       case AST_CONNECTED_LINE_SUBADDRESS_VALID:
08749          if (ie_len != 1) {
08750             ast_log(LOG_WARNING, "Invalid connected line subaddress valid (%u)\n",
08751                (unsigned) ie_len);
08752             break;
08753          }
08754          connected->id.subaddress.valid = data[pos];
08755          break;
08756 /* Connected line party tag */
08757       case AST_CONNECTED_LINE_TAG:
08758          ast_free(connected->id.tag);
08759          connected->id.tag = ast_malloc(ie_len + 1);
08760          if (connected->id.tag) {
08761             memcpy(connected->id.tag, data + pos, ie_len);
08762             connected->id.tag[ie_len] = 0;
08763          }
08764          break;
08765 /* Connected line party source */
08766       case AST_CONNECTED_LINE_SOURCE:
08767          if (ie_len != sizeof(value)) {
08768             ast_log(LOG_WARNING, "Invalid connected line source (%u)\n",
08769                (unsigned) ie_len);
08770             break;
08771          }
08772          memcpy(&value, data + pos, sizeof(value));
08773          connected->source = ntohl(value);
08774          break;
08775 /* Connected line party unknown element */
08776       default:
08777          ast_log(LOG_DEBUG, "Unknown connected line element: %u (%u)\n",
08778             (unsigned) ie_id, (unsigned) ie_len);
08779          break;
08780       }
08781    }
08782 
08783    switch (frame_version) {
08784    case 1:
08785       /*
08786        * The other end is an earlier version that we need to adjust
08787        * for compatibility.
08788        */
08789       connected->id.name.valid = 1;
08790       connected->id.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
08791       connected->id.number.valid = 1;
08792       if (got_combined_presentation) {
08793          connected->id.name.presentation = combined_presentation;
08794          connected->id.number.presentation = combined_presentation;
08795       }
08796       break;
08797    case 2:
08798       /* The other end is at the same level as we are. */
08799       break;
08800    default:
08801       /*
08802        * The other end is newer than we are.
08803        * We need to assume that they are compatible with us.
08804        */
08805       ast_log(LOG_DEBUG, "Connected line frame has newer version: %u\n",
08806          (unsigned) frame_version);
08807       break;
08808    }
08809 
08810    return 0;
08811 }
08812 
08813 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)
08814 {
08815    unsigned char data[1024];  /* This should be large enough */
08816    size_t datalen;
08817 
08818    datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
08819    if (datalen == (size_t) -1) {
08820       return;
08821    }
08822 
08823    ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
08824 }
08825 
08826 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)
08827 {
08828    unsigned char data[1024];  /* This should be large enough */
08829    size_t datalen;
08830 
08831    datalen = ast_connected_line_build_data(data, sizeof(data), connected, update);
08832    if (datalen == (size_t) -1) {
08833       return;
08834    }
08835 
08836    ast_queue_control_data(chan, AST_CONTROL_CONNECTED_LINE, data, datalen);
08837 }
08838 
08839 void ast_channel_set_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08840 {
08841    if (&chan->redirecting == redirecting) {
08842       /* Don't set to self */
08843       return;
08844    }
08845 
08846    ast_channel_lock(chan);
08847    ast_party_redirecting_set(&chan->redirecting, redirecting, update);
08848    ast_channel_unlock(chan);
08849 }
08850 
08851 /*!
08852  * \brief Element identifiers for redirecting indication frame data
08853  * \note Only add to the end of this enum.
08854  */
08855 enum {
08856    AST_REDIRECTING_FROM_NUMBER,
08857    AST_REDIRECTING_FROM_NAME,
08858    AST_REDIRECTING_FROM_NUMBER_PLAN,
08859    AST_REDIRECTING_FROM_ID_PRESENTATION,
08860    AST_REDIRECTING_TO_NUMBER,
08861    AST_REDIRECTING_TO_NAME,
08862    AST_REDIRECTING_TO_NUMBER_PLAN,
08863    AST_REDIRECTING_TO_ID_PRESENTATION,
08864    AST_REDIRECTING_REASON,
08865    AST_REDIRECTING_COUNT,
08866    AST_REDIRECTING_FROM_SUBADDRESS,
08867    AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
08868    AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
08869    AST_REDIRECTING_FROM_SUBADDRESS_VALID,
08870    AST_REDIRECTING_TO_SUBADDRESS,
08871    AST_REDIRECTING_TO_SUBADDRESS_TYPE,
08872    AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
08873    AST_REDIRECTING_TO_SUBADDRESS_VALID,
08874    AST_REDIRECTING_FROM_TAG,
08875    AST_REDIRECTING_TO_TAG,
08876    AST_REDIRECTING_VERSION,
08877    AST_REDIRECTING_FROM_NAME_VALID,
08878    AST_REDIRECTING_FROM_NAME_CHAR_SET,
08879    AST_REDIRECTING_FROM_NAME_PRESENTATION,
08880    AST_REDIRECTING_FROM_NUMBER_VALID,
08881    AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
08882    AST_REDIRECTING_TO_NAME_VALID,
08883    AST_REDIRECTING_TO_NAME_CHAR_SET,
08884    AST_REDIRECTING_TO_NAME_PRESENTATION,
08885    AST_REDIRECTING_TO_NUMBER_VALID,
08886    AST_REDIRECTING_TO_NUMBER_PRESENTATION,
08887 };
08888 
08889 int ast_redirecting_build_data(unsigned char *data, size_t datalen, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
08890 {
08891    int32_t value;
08892    size_t pos = 0;
08893    int res;
08894 
08895    static const struct ast_party_id_ies from_ies = {
08896       .name.str = AST_REDIRECTING_FROM_NAME,
08897       .name.char_set = AST_REDIRECTING_FROM_NAME_CHAR_SET,
08898       .name.presentation = AST_REDIRECTING_FROM_NAME_PRESENTATION,
08899       .name.valid = AST_REDIRECTING_FROM_NAME_VALID,
08900 
08901       .number.str = AST_REDIRECTING_FROM_NUMBER,
08902       .number.plan = AST_REDIRECTING_FROM_NUMBER_PLAN,
08903       .number.presentation = AST_REDIRECTING_FROM_NUMBER_PRESENTATION,
08904       .number.valid = AST_REDIRECTING_FROM_NUMBER_VALID,
08905 
08906       .subaddress.str = AST_REDIRECTING_FROM_SUBADDRESS,
08907       .subaddress.type = AST_REDIRECTING_FROM_SUBADDRESS_TYPE,
08908       .subaddress.odd_even_indicator = AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN,
08909       .subaddress.valid = AST_REDIRECTING_FROM_SUBADDRESS_VALID,
08910 
08911       .tag = AST_REDIRECTING_FROM_TAG,
08912       .combined_presentation = AST_REDIRECTING_FROM_ID_PRESENTATION,
08913    };
08914    static const struct ast_party_id_ies to_ies = {
08915       .name.str = AST_REDIRECTING_TO_NAME,
08916       .name.char_set = AST_REDIRECTING_TO_NAME_CHAR_SET,
08917       .name.presentation = AST_REDIRECTING_TO_NAME_PRESENTATION,
08918       .name.valid = AST_REDIRECTING_TO_NAME_VALID,
08919 
08920       .number.str = AST_REDIRECTING_TO_NUMBER,
08921       .number.plan = AST_REDIRECTING_TO_NUMBER_PLAN,
08922       .number.presentation = AST_REDIRECTING_TO_NUMBER_PRESENTATION,
08923       .number.valid = AST_REDIRECTING_TO_NUMBER_VALID,
08924 
08925       .subaddress.str = AST_REDIRECTING_TO_SUBADDRESS,
08926       .subaddress.type = AST_REDIRECTING_TO_SUBADDRESS_TYPE,
08927       .subaddress.odd_even_indicator = AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN,
08928       .subaddress.valid = AST_REDIRECTING_TO_SUBADDRESS_VALID,
08929 
08930       .tag = AST_REDIRECTING_TO_TAG,
08931       .combined_presentation = AST_REDIRECTING_TO_ID_PRESENTATION,
08932    };
08933 
08934    /* Redirecting frame version */
08935    if (datalen < pos + (sizeof(data[0]) * 2) + 1) {
08936       ast_log(LOG_WARNING, "No space left for redirecting frame version\n");
08937       return -1;
08938    }
08939    data[pos++] = AST_REDIRECTING_VERSION;
08940    data[pos++] = 1;
08941    data[pos++] = 2;/* Version 1 did not have a version ie */
08942 
08943    res = party_id_build_data(data + pos, datalen - pos, &redirecting->from,
08944       "redirecting-from", &from_ies, update ? &update->from : NULL);
08945    if (res < 0) {
08946       return -1;
08947    }
08948    pos += res;
08949 
08950    res = party_id_build_data(data + pos, datalen - pos, &redirecting->to,
08951       "redirecting-to", &to_ies, update ? &update->to : NULL);
08952    if (res < 0) {
08953       return -1;
08954    }
08955    pos += res;
08956 
08957    /* Redirecting reason */
08958    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08959       ast_log(LOG_WARNING, "No space left for redirecting reason\n");
08960       return -1;
08961    }
08962    data[pos++] = AST_REDIRECTING_REASON;
08963    data[pos++] = sizeof(value);
08964    value = htonl(redirecting->reason);
08965    memcpy(data + pos, &value, sizeof(value));
08966    pos += sizeof(value);
08967 
08968    /* Redirecting count */
08969    if (datalen < pos + (sizeof(data[0]) * 2) + sizeof(value)) {
08970       ast_log(LOG_WARNING, "No space left for redirecting count\n");
08971       return -1;
08972    }
08973    data[pos++] = AST_REDIRECTING_COUNT;
08974    data[pos++] = sizeof(value);
08975    value = htonl(redirecting->count);
08976    memcpy(data + pos, &value, sizeof(value));
08977    pos += sizeof(value);
08978 
08979    return pos;
08980 }
08981 
08982 int ast_redirecting_parse_data(const unsigned char *data, size_t datalen, struct ast_party_redirecting *redirecting)
08983 {
08984    size_t pos;
08985    unsigned char ie_len;
08986    unsigned char ie_id;
08987    int32_t value;
08988    int frame_version = 1;
08989    int from_combined_presentation = 0;
08990    int got_from_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08991    int to_combined_presentation = 0;
08992    int got_to_combined_presentation = 0;/* TRUE if got a combined name and number presentation value. */
08993 
08994    for (pos = 0; pos < datalen; pos += ie_len) {
08995       if (datalen < pos + sizeof(ie_id) + sizeof(ie_len)) {
08996          ast_log(LOG_WARNING, "Invalid redirecting update\n");
08997          return -1;
08998       }
08999       ie_id = data[pos++];
09000       ie_len = data[pos++];
09001       if (datalen < pos + ie_len) {
09002          ast_log(LOG_WARNING, "Invalid redirecting update\n");
09003          return -1;
09004       }
09005 
09006       switch (ie_id) {
09007 /* Redirecting frame version */
09008       case AST_REDIRECTING_VERSION:
09009          if (ie_len != 1) {
09010             ast_log(LOG_WARNING, "Invalid redirecting frame version (%u)\n",
09011                (unsigned) ie_len);
09012             break;
09013          }
09014          frame_version = data[pos];
09015          break;
09016 /* Redirecting-from party id name */
09017       case AST_REDIRECTING_FROM_NAME:
09018          ast_free(redirecting->from.name.str);
09019          redirecting->from.name.str = ast_malloc(ie_len + 1);
09020          if (redirecting->from.name.str) {
09021             memcpy(redirecting->from.name.str, data + pos, ie_len);
09022             redirecting->from.name.str[ie_len] = 0;
09023          }
09024          break;
09025       case AST_REDIRECTING_FROM_NAME_CHAR_SET:
09026          if (ie_len != 1) {
09027             ast_log(LOG_WARNING, "Invalid redirecting-from name char set (%u)\n",
09028                (unsigned) ie_len);
09029             break;
09030          }
09031          redirecting->from.name.char_set = data[pos];
09032          break;
09033       case AST_REDIRECTING_FROM_NAME_PRESENTATION:
09034          if (ie_len != 1) {
09035             ast_log(LOG_WARNING, "Invalid redirecting-from name presentation (%u)\n",
09036                (unsigned) ie_len);
09037             break;
09038          }
09039          redirecting->from.name.presentation = data[pos];
09040          break;
09041       case AST_REDIRECTING_FROM_NAME_VALID:
09042          if (ie_len != 1) {
09043             ast_log(LOG_WARNING, "Invalid redirecting-from name valid (%u)\n",
09044                (unsigned) ie_len);
09045             break;
09046          }
09047          redirecting->from.name.valid = data[pos];
09048          break;
09049 /* Redirecting-from party id number */
09050       case AST_REDIRECTING_FROM_NUMBER:
09051          ast_free(redirecting->from.number.str);
09052          redirecting->from.number.str = ast_malloc(ie_len + 1);
09053          if (redirecting->from.number.str) {
09054             memcpy(redirecting->from.number.str, data + pos, ie_len);
09055             redirecting->from.number.str[ie_len] = 0;
09056          }
09057          break;
09058       case AST_REDIRECTING_FROM_NUMBER_PLAN:
09059          if (ie_len != 1) {
09060             ast_log(LOG_WARNING, "Invalid redirecting-from numbering plan (%u)\n",
09061                (unsigned) ie_len);
09062             break;
09063          }
09064          redirecting->from.number.plan = data[pos];
09065          break;
09066       case AST_REDIRECTING_FROM_NUMBER_PRESENTATION:
09067          if (ie_len != 1) {
09068             ast_log(LOG_WARNING, "Invalid redirecting-from number presentation (%u)\n",
09069                (unsigned) ie_len);
09070             break;
09071          }
09072          redirecting->from.number.presentation = data[pos];
09073          break;
09074       case AST_REDIRECTING_FROM_NUMBER_VALID:
09075          if (ie_len != 1) {
09076             ast_log(LOG_WARNING, "Invalid redirecting-from number valid (%u)\n",
09077                (unsigned) ie_len);
09078             break;
09079          }
09080          redirecting->from.number.valid = data[pos];
09081          break;
09082 /* Redirecting-from party id combined presentation */
09083       case AST_REDIRECTING_FROM_ID_PRESENTATION:
09084          if (ie_len != 1) {
09085             ast_log(LOG_WARNING, "Invalid redirecting-from combined presentation (%u)\n",
09086                (unsigned) ie_len);
09087             break;
09088          }
09089          from_combined_presentation = data[pos];
09090          got_from_combined_presentation = 1;
09091          break;
09092 /* Redirecting-from party id subaddress */
09093       case AST_REDIRECTING_FROM_SUBADDRESS:
09094          ast_free(redirecting->from.subaddress.str);
09095          redirecting->from.subaddress.str = ast_malloc(ie_len + 1);
09096          if (redirecting->from.subaddress.str) {
09097             memcpy(redirecting->from.subaddress.str, data + pos, ie_len);
09098             redirecting->from.subaddress.str[ie_len] = 0;
09099          }
09100          break;
09101       case AST_REDIRECTING_FROM_SUBADDRESS_TYPE:
09102          if (ie_len != 1) {
09103             ast_log(LOG_WARNING, "Invalid redirecting-from type of subaddress (%u)\n",
09104                (unsigned) ie_len);
09105             break;
09106          }
09107          redirecting->from.subaddress.type = data[pos];
09108          break;
09109       case AST_REDIRECTING_FROM_SUBADDRESS_ODD_EVEN:
09110          if (ie_len != 1) {
09111             ast_log(LOG_WARNING,
09112                "Invalid redirecting-from subaddress odd-even indicator (%u)\n",
09113                (unsigned) ie_len);
09114             break;
09115          }
09116          redirecting->from.subaddress.odd_even_indicator = data[pos];
09117          break;
09118       case AST_REDIRECTING_FROM_SUBADDRESS_VALID:
09119          if (ie_len != 1) {
09120             ast_log(LOG_WARNING, "Invalid redirecting-from subaddress valid (%u)\n",
09121                (unsigned) ie_len);
09122             break;
09123          }
09124          redirecting->from.subaddress.valid = data[pos];
09125          break;
09126 /* Redirecting-from party id tag */
09127       case AST_REDIRECTING_FROM_TAG:
09128          ast_free(redirecting->from.tag);
09129          redirecting->from.tag = ast_malloc(ie_len + 1);
09130          if (redirecting->from.tag) {
09131             memcpy(redirecting->from.tag, data + pos, ie_len);
09132             redirecting->from.tag[ie_len] = 0;
09133          }
09134          break;
09135 /* Redirecting-to party id name */
09136       case AST_REDIRECTING_TO_NAME:
09137          ast_free(redirecting->to.name.str);
09138          redirecting->to.name.str = ast_malloc(ie_len + 1);
09139          if (redirecting->to.name.str) {
09140             memcpy(redirecting->to.name.str, data + pos, ie_len);
09141             redirecting->to.name.str[ie_len] = 0;
09142          }
09143          break;
09144       case AST_REDIRECTING_TO_NAME_CHAR_SET:
09145          if (ie_len != 1) {
09146             ast_log(LOG_WARNING, "Invalid redirecting-to name char set (%u)\n",
09147                (unsigned) ie_len);
09148             break;
09149          }
09150          redirecting->to.name.char_set = data[pos];
09151          break;
09152       case AST_REDIRECTING_TO_NAME_PRESENTATION:
09153          if (ie_len != 1) {
09154             ast_log(LOG_WARNING, "Invalid redirecting-to name presentation (%u)\n",
09155                (unsigned) ie_len);
09156             break;
09157          }
09158          redirecting->to.name.presentation = data[pos];
09159          break;
09160       case AST_REDIRECTING_TO_NAME_VALID:
09161          if (ie_len != 1) {
09162             ast_log(LOG_WARNING, "Invalid redirecting-to name valid (%u)\n",
09163                (unsigned) ie_len);
09164             break;
09165          }
09166          redirecting->to.name.valid = data[pos];
09167          break;
09168 /* Redirecting-to party id number */
09169       case AST_REDIRECTING_TO_NUMBER:
09170          ast_free(redirecting->to.number.str);
09171          redirecting->to.number.str = ast_malloc(ie_len + 1);
09172          if (redirecting->to.number.str) {
09173             memcpy(redirecting->to.number.str, data + pos, ie_len);
09174             redirecting->to.number.str[ie_len] = 0;
09175          }
09176          break;
09177       case AST_REDIRECTING_TO_NUMBER_PLAN:
09178          if (ie_len != 1) {
09179             ast_log(LOG_WARNING, "Invalid redirecting-to numbering plan (%u)\n",
09180                (unsigned) ie_len);
09181             break;
09182          }
09183          redirecting->to.number.plan = data[pos];
09184          break;
09185       case AST_REDIRECTING_TO_NUMBER_PRESENTATION:
09186          if (ie_len != 1) {
09187             ast_log(LOG_WARNING, "Invalid redirecting-to number presentation (%u)\n",
09188                (unsigned) ie_len);
09189             break;
09190          }
09191          redirecting->to.number.presentation = data[pos];
09192          break;
09193       case AST_REDIRECTING_TO_NUMBER_VALID:
09194          if (ie_len != 1) {
09195             ast_log(LOG_WARNING, "Invalid redirecting-to number valid (%u)\n",
09196                (unsigned) ie_len);
09197             break;
09198          }
09199          redirecting->to.number.valid = data[pos];
09200          break;
09201 /* Redirecting-to party id combined presentation */
09202       case AST_REDIRECTING_TO_ID_PRESENTATION:
09203          if (ie_len != 1) {
09204             ast_log(LOG_WARNING, "Invalid redirecting-to combined presentation (%u)\n",
09205                (unsigned) ie_len);
09206             break;
09207          }
09208          to_combined_presentation = data[pos];
09209          got_to_combined_presentation = 1;
09210          break;
09211 /* Redirecting-to party id subaddress */
09212       case AST_REDIRECTING_TO_SUBADDRESS:
09213          ast_free(redirecting->to.subaddress.str);
09214          redirecting->to.subaddress.str = ast_malloc(ie_len + 1);
09215          if (redirecting->to.subaddress.str) {
09216             memcpy(redirecting->to.subaddress.str, data + pos, ie_len);
09217             redirecting->to.subaddress.str[ie_len] = 0;
09218          }
09219          break;
09220       case AST_REDIRECTING_TO_SUBADDRESS_TYPE:
09221          if (ie_len != 1) {
09222             ast_log(LOG_WARNING, "Invalid redirecting-to type of subaddress (%u)\n",
09223                (unsigned) ie_len);
09224             break;
09225          }
09226          redirecting->to.subaddress.type = data[pos];
09227          break;
09228       case AST_REDIRECTING_TO_SUBADDRESS_ODD_EVEN:
09229          if (ie_len != 1) {
09230             ast_log(LOG_WARNING,
09231                "Invalid redirecting-to subaddress odd-even indicator (%u)\n",
09232                (unsigned) ie_len);
09233             break;
09234          }
09235          redirecting->to.subaddress.odd_even_indicator = data[pos];
09236          break;
09237       case AST_REDIRECTING_TO_SUBADDRESS_VALID:
09238          if (ie_len != 1) {
09239             ast_log(LOG_WARNING, "Invalid redirecting-to subaddress valid (%u)\n",
09240                (unsigned) ie_len);
09241             break;
09242          }
09243          redirecting->to.subaddress.valid = data[pos];
09244          break;
09245 /* Redirecting-to party id tag */
09246       case AST_REDIRECTING_TO_TAG:
09247          ast_free(redirecting->to.tag);
09248          redirecting->to.tag = ast_malloc(ie_len + 1);
09249          if (redirecting->to.tag) {
09250             memcpy(redirecting->to.tag, data + pos, ie_len);
09251             redirecting->to.tag[ie_len] = 0;
09252          }
09253          break;
09254 /* Redirecting reason */
09255       case AST_REDIRECTING_REASON:
09256          if (ie_len != sizeof(value)) {
09257             ast_log(LOG_WARNING, "Invalid redirecting reason (%u)\n",
09258                (unsigned) ie_len);
09259             break;
09260          }
09261          memcpy(&value, data + pos, sizeof(value));
09262          redirecting->reason = ntohl(value);
09263          break;
09264 /* Redirecting count */
09265       case AST_REDIRECTING_COUNT:
09266          if (ie_len != sizeof(value)) {
09267             ast_log(LOG_WARNING, "Invalid redirecting count (%u)\n",
09268                (unsigned) ie_len);
09269             break;
09270          }
09271          memcpy(&value, data + pos, sizeof(value));
09272          redirecting->count = ntohl(value);
09273          break;
09274 /* Redirecting unknown element */
09275       default:
09276          ast_log(LOG_DEBUG, "Unknown redirecting element: %u (%u)\n",
09277             (unsigned) ie_id, (unsigned) ie_len);
09278          break;
09279       }
09280    }
09281 
09282    switch (frame_version) {
09283    case 1:
09284       /*
09285        * The other end is an earlier version that we need to adjust
09286        * for compatibility.
09287        */
09288       redirecting->from.name.valid = 1;
09289       redirecting->from.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
09290       redirecting->from.number.valid = 1;
09291       if (got_from_combined_presentation) {
09292          redirecting->from.name.presentation = from_combined_presentation;
09293          redirecting->from.number.presentation = from_combined_presentation;
09294       }
09295 
09296       redirecting->to.name.valid = 1;
09297       redirecting->to.name.char_set = AST_PARTY_CHAR_SET_ISO8859_1;
09298       redirecting->to.number.valid = 1;
09299       if (got_to_combined_presentation) {
09300          redirecting->to.name.presentation = to_combined_presentation;
09301          redirecting->to.number.presentation = to_combined_presentation;
09302       }
09303       break;
09304    case 2:
09305       /* The other end is at the same level as we are. */
09306       break;
09307    default:
09308       /*
09309        * The other end is newer than we are.
09310        * We need to assume that they are compatible with us.
09311        */
09312       ast_log(LOG_DEBUG, "Redirecting frame has newer version: %u\n",
09313          (unsigned) frame_version);
09314       break;
09315    }
09316 
09317    return 0;
09318 }
09319 
09320 void ast_channel_update_redirecting(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
09321 {
09322    unsigned char data[1024];  /* This should be large enough */
09323    size_t datalen;
09324 
09325    datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
09326    if (datalen == (size_t) -1) {
09327       return;
09328    }
09329 
09330    ast_indicate_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
09331 }
09332 
09333 void ast_channel_queue_redirecting_update(struct ast_channel *chan, const struct ast_party_redirecting *redirecting, const struct ast_set_party_redirecting *update)
09334 {
09335    unsigned char data[1024];  /* This should be large enough */
09336    size_t datalen;
09337 
09338    datalen = ast_redirecting_build_data(data, sizeof(data), redirecting, update);
09339    if (datalen == (size_t) -1) {
09340       return;
09341    }
09342 
09343    ast_queue_control_data(chan, AST_CONTROL_REDIRECTING, data, datalen);
09344 }
09345 
09346 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)
09347 {
09348    const char *macro;
09349    const char *macro_args;
09350    int retval;
09351 
09352    ast_channel_lock(macro_chan);
09353    macro = pbx_builtin_getvar_helper(macro_chan, is_caller
09354       ? "CONNECTED_LINE_CALLER_SEND_MACRO" : "CONNECTED_LINE_CALLEE_SEND_MACRO");
09355    macro = ast_strdupa(S_OR(macro, ""));
09356    macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
09357       ? "CONNECTED_LINE_CALLER_SEND_MACRO_ARGS" : "CONNECTED_LINE_CALLEE_SEND_MACRO_ARGS");
09358    macro_args = ast_strdupa(S_OR(macro_args, ""));
09359 
09360    if (ast_strlen_zero(macro)) {
09361       ast_channel_unlock(macro_chan);
09362       return -1;
09363    }
09364 
09365    if (is_frame) {
09366       const struct ast_frame *frame = connected_info;
09367 
09368       ast_connected_line_parse_data(frame->data.ptr, frame->datalen, &macro_chan->connected);
09369    } else {
09370       const struct ast_party_connected_line *connected = connected_info;
09371 
09372       ast_party_connected_line_copy(&macro_chan->connected, connected);
09373    }
09374    ast_channel_unlock(macro_chan);
09375 
09376    retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args);
09377    if (!retval) {
09378       struct ast_party_connected_line saved_connected;
09379 
09380       ast_party_connected_line_init(&saved_connected);
09381       ast_channel_lock(macro_chan);
09382       ast_party_connected_line_copy(&saved_connected, &macro_chan->connected);
09383       ast_channel_unlock(macro_chan);
09384       ast_channel_update_connected_line(macro_chan, &saved_connected, NULL);
09385       ast_party_connected_line_free(&saved_connected);
09386    }
09387 
09388    return retval;
09389 }
09390 
09391 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)
09392 {
09393    const char *macro;
09394    const char *macro_args;
09395    int retval;
09396 
09397    ast_channel_lock(macro_chan);
09398    macro = pbx_builtin_getvar_helper(macro_chan, is_caller
09399       ? "REDIRECTING_CALLER_SEND_MACRO" : "REDIRECTING_CALLEE_SEND_MACRO");
09400    macro = ast_strdupa(S_OR(macro, ""));
09401    macro_args = pbx_builtin_getvar_helper(macro_chan, is_caller
09402       ? "REDIRECTING_CALLER_SEND_MACRO_ARGS" : "REDIRECTING_CALLEE_SEND_MACRO_ARGS");
09403    macro_args = ast_strdupa(S_OR(macro_args, ""));
09404 
09405    if (ast_strlen_zero(macro)) {
09406       ast_channel_unlock(macro_chan);
09407       return -1;
09408    }
09409 
09410    if (is_frame) {
09411       const struct ast_frame *frame = redirecting_info;
09412 
09413       ast_redirecting_parse_data(frame->data.ptr, frame->datalen, &macro_chan->redirecting);
09414    } else {
09415       const struct ast_party_redirecting *redirecting = redirecting_info;
09416 
09417       ast_party_redirecting_copy(&macro_chan->redirecting, redirecting);
09418    }
09419    ast_channel_unlock(macro_chan);
09420 
09421    retval = ast_app_run_macro(autoservice_chan, macro_chan, macro, macro_args);
09422    if (!retval) {
09423       struct ast_party_redirecting saved_redirecting;
09424 
09425       ast_party_redirecting_init(&saved_redirecting);
09426       ast_channel_lock(macro_chan);
09427       ast_party_redirecting_copy(&saved_redirecting, &macro_chan->redirecting);
09428       ast_channel_unlock(macro_chan);
09429       ast_channel_update_redirecting(macro_chan, &saved_redirecting, NULL);
09430       ast_party_redirecting_free(&saved_redirecting);
09431    }
09432 
09433    return retval;
09434 }
09435 
09436 static void *channel_cc_params_copy(void *data)
09437 {
09438    const struct ast_cc_config_params *src = data;
09439    struct ast_cc_config_params *dest = ast_cc_config_params_init();
09440    if (!dest) {
09441       return NULL;
09442    }
09443    ast_cc_copy_config_params(dest, src);
09444    return dest;
09445 }
09446 
09447 static void channel_cc_params_destroy(void *data)
09448 {
09449    struct ast_cc_config_params *cc_params = data;
09450    ast_cc_config_params_destroy(cc_params);
09451 }
09452 
09453 static const struct ast_datastore_info cc_channel_datastore_info = {
09454    .type = "Call Completion",
09455    .duplicate = channel_cc_params_copy,
09456    .destroy = channel_cc_params_destroy,
09457 };
09458 
09459 int ast_channel_cc_params_init(struct ast_channel *chan,
09460       const struct ast_cc_config_params *base_params)
09461 {
09462    struct ast_cc_config_params *cc_params;
09463    struct ast_datastore *cc_datastore;
09464 
09465    if (!(cc_params = ast_cc_config_params_init())) {
09466       return -1;
09467    }
09468 
09469    if (!(cc_datastore = ast_datastore_alloc(&cc_channel_datastore_info, NULL))) {
09470       ast_cc_config_params_destroy(cc_params);
09471       return -1;
09472    }
09473 
09474    if (base_params) {
09475       ast_cc_copy_config_params(cc_params, base_params);
09476    }
09477    cc_datastore->data = cc_params;
09478    ast_channel_datastore_add(chan, cc_datastore);
09479    return 0;
09480 }
09481 
09482 struct ast_cc_config_params *ast_channel_get_cc_config_params(struct ast_channel *chan)
09483 {
09484    struct ast_datastore *cc_datastore;
09485 
09486    if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
09487       /* If we can't find the datastore, it almost definitely means that the channel type being
09488        * used has not had its driver modified to parse CC config parameters. The best action
09489        * to take here is to create the parameters on the spot with the defaults set.
09490        */
09491       if (ast_channel_cc_params_init(chan, NULL)) {
09492          return NULL;
09493       }
09494       if (!(cc_datastore = ast_channel_datastore_find(chan, &cc_channel_datastore_info, NULL))) {
09495          /* Should be impossible */
09496          return NULL;
09497       }
09498    }
09499 
09500    ast_assert(cc_datastore->data != NULL);
09501    return cc_datastore->data;
09502 }
09503 
09504 int ast_channel_get_device_name(struct ast_channel *chan, char *device_name, size_t name_buffer_length)
09505 {
09506    int len = name_buffer_length;
09507    char *dash;
09508    if (!ast_channel_queryoption(chan, AST_OPTION_DEVICE_NAME, device_name, &len, 0)) {
09509       return 0;
09510    }
09511 
09512    /* Dang. Do it the old-fashioned way */
09513    ast_copy_string(device_name, chan->name, name_buffer_length);
09514    if ((dash = strrchr(device_name, '-'))) {
09515       *dash = '\0';
09516    }
09517 
09518    return 0;
09519 }
09520 
09521 int ast_channel_get_cc_agent_type(struct ast_channel *chan, char *agent_type, size_t size)
09522 {
09523    int len = size;
09524    char *slash;
09525 
09526    if (!ast_channel_queryoption(chan, AST_OPTION_CC_AGENT_TYPE, agent_type, &len, 0)) {
09527       return 0;
09528    }
09529 
09530    ast_copy_string(agent_type, chan->name, size);
09531    if ((slash = strchr(agent_type, '/'))) {
09532       *slash = '\0';
09533    }
09534    return 0;
09535 }
09536 
09537 /* DO NOT PUT ADDITIONAL FUNCTIONS BELOW THIS BOUNDARY
09538  *
09539  * ONLY FUNCTIONS FOR PROVIDING BACKWARDS ABI COMPATIBILITY BELONG HERE
09540  *
09541  */
09542 
09543 /* Provide binary compatibility for modules that call ast_channel_alloc() directly;
09544  * newly compiled modules will call __ast_channel_alloc() via the macros in channel.h
09545  */
09546 #undef ast_channel_alloc
09547 struct ast_channel __attribute__((format(printf, 10, 11)))
09548    *ast_channel_alloc(int needqueue, int state, const char *cid_num,
09549             const char *cid_name, const char *acctcode,
09550             const char *exten, const char *context,
09551             const char *linkedid, const int amaflag,
09552             const char *name_fmt, ...);
09553 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num,
09554                   const char *cid_name, const char *acctcode,
09555                   const char *exten, const char *context,
09556                   const char *linkedid, const int amaflag,
09557                   const char *name_fmt, ...)
09558 {
09559    va_list ap1, ap2;
09560    struct ast_channel *result;
09561 
09562 
09563    va_start(ap1, name_fmt);
09564    va_start(ap2, name_fmt);
09565    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
09566                linkedid, amaflag, __FILE__, __LINE__, __FUNCTION__, name_fmt, ap1, ap2);
09567    va_end(ap1);
09568    va_end(ap2);
09569 
09570    return result;
09571 }