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 /*** MODULEINFO
00027    <support_level>core</support_level>
00028  ***/
00029 
00030 #include "asterisk.h"
00031 
00032 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 434672 $")
00033 
00034 #include "asterisk/_private.h"
00035 
00036 #include <sys/time.h>
00037 #include <signal.h>
00038 #include <math.h>
00039 
00040 #include "asterisk/paths.h"   /* use ast_config_AST_SYSTEM_NAME */
00041 
00042 #include "asterisk/pbx.h"
00043 #include "asterisk/frame.h"
00044 #include "asterisk/mod_format.h"
00045 #include "asterisk/sched.h"
00046 #include "asterisk/channel.h"
00047 #include "asterisk/musiconhold.h"
00048 #include "asterisk/say.h"
00049 #include "asterisk/file.h"
00050 #include "asterisk/cli.h"
00051 #include "asterisk/translate.h"
00052 #include "asterisk/manager.h"
00053 #include "asterisk/chanvars.h"
00054 #include "asterisk/linkedlists.h"
00055 #include "asterisk/indications.h"
00056 #include "asterisk/monitor.h"
00057 #include "asterisk/causes.h"
00058 #include "asterisk/callerid.h"
00059 #include "asterisk/utils.h"
00060 #include "asterisk/lock.h"
00061 #include "asterisk/app.h"
00062 #include "asterisk/transcap.h"
00063 #include "asterisk/devicestate.h"
00064 #include "asterisk/threadstorage.h"
00065 #include "asterisk/slinfactory.h"
00066 #include "asterisk/audiohook.h"
00067 #include "asterisk/framehook.h"
00068 #include "asterisk/timing.h"
00069 #include "asterisk/autochan.h"
00070 #include "asterisk/stringfields.h"
00071 #include "asterisk/global_datastores.h"
00072 #include "asterisk/data.h"
00073 #include "asterisk/channel_internal.h"
00074 #include "asterisk/features.h"
00075 #include "asterisk/bridge.h"
00076 #include "asterisk/test.h"
00077 #include "asterisk/stasis_channels.h"
00078 
00079 /*** DOCUMENTATION
00080  ***/
00081 
00082 #ifdef HAVE_EPOLL
00083 #include <sys/epoll.h>
00084 #endif
00085 
00086 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00087 #if defined(HAVE_PRI)
00088 #include "libpri.h"
00089 #endif   /* defined(HAVE_PRI) */
00090 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00091 
00092 struct ast_epoll_data {
00093    struct ast_channel *chan;
00094    int which;
00095 };
00096 
00097 /* uncomment if you have problems with 'monitoring' synchronized files */
00098 #if 0
00099 #define MONITOR_CONSTANT_DELAY
00100 #define MONITOR_DELAY   150 * 8     /*!< 150 ms of MONITORING DELAY */
00101 #endif
00102 
00103 static int chancount;
00104 
00105 unsigned long global_fin, global_fout;
00106 
00107 AST_THREADSTORAGE(state2str_threadbuf);
00108 #define STATE2STR_BUFSIZE   32
00109 
00110 /*! Default amount of time to use when emulating a digit as a begin and end
00111  *  100ms */
00112 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
00113 
00114 #define DEFAULT_AMA_FLAGS AST_AMA_DOCUMENTATION
00115 
00116 /*! Minimum amount of time between the end of the last digit and the beginning
00117  *  of a new one - 45ms */
00118 #define AST_MIN_DTMF_GAP 45
00119 
00120 /*! \brief List of channel drivers */
00121 struct chanlist {
00122    const struct ast_channel_tech *tech;
00123    AST_LIST_ENTRY(chanlist) list;
00124 };
00125 
00126 /*! \brief the list of registered channel types */
00127 static AST_RWLIST_HEAD_STATIC(backends, chanlist);
00128 
00129 #ifdef LOW_MEMORY
00130 #define NUM_CHANNEL_BUCKETS 61
00131 #else
00132 #define NUM_CHANNEL_BUCKETS 1567
00133 #endif
00134 
00135 /*! \brief All active channels on the system */
00136 static struct ao2_container *channels;
00137 
00138 /*! \brief map AST_CAUSE's to readable string representations
00139  *
00140  * \ref causes.h
00141 */
00142 struct causes_map {
00143    int cause;
00144    const char *name;
00145    const char *desc;
00146 };
00147 
00148 static const struct causes_map causes[] = {
00149    { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
00150    { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
00151    { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
00152    { AST_CAUSE_MISDIALLED_TRUNK_PREFIX, "MISDIALLED_TRUNK_PREFIX", "Misdialed trunk prefix" },
00153    { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
00154    { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
00155    { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
00156    { AST_CAUSE_NUMBER_PORTED_NOT_HERE, "NUMBER_PORTED_NOT_HERE", "Number ported elsewhere" },
00157    { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
00158    { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
00159    { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
00160    { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
00161    { AST_CAUSE_SUBSCRIBER_ABSENT, "SUBSCRIBER_ABSENT", "Subscriber absent" },
00162    { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
00163    { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
00164    { AST_CAUSE_REDIRECTED_TO_NEW_DESTINATION, "REDIRECTED_TO_NEW_DESTINATION", "Redirected to new destination" },
00165    { AST_CAUSE_ANSWERED_ELSEWHERE, "ANSWERED_ELSEWHERE", "Answered elsewhere" },
00166    { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
00167    { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
00168    { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
00169    { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
00170    { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
00171    { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
00172    { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
00173    { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
00174    { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
00175    { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
00176    { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
00177    { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
00178    { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
00179    { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
00180    { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
00181    { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
00182    { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
00183    { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
00184    { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
00185    { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
00186    { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
00187    { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
00188    { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
00189    { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
00190    { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
00191    { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
00192    { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
00193    { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
00194    { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
00195    { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
00196    { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
00197    { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
00198 };
00199 
00200 struct ast_variable *ast_channeltype_list(void)
00201 {
00202    struct chanlist *cl;
00203    struct ast_variable *var = NULL, *prev = NULL;
00204 
00205    AST_RWLIST_RDLOCK(&backends);
00206    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00207       if (prev)  {
00208          if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
00209             prev = prev->next;
00210       } else {
00211          var = ast_variable_new(cl->tech->type, cl->tech->description, "");
00212          prev = var;
00213       }
00214    }
00215    AST_RWLIST_UNLOCK(&backends);
00216 
00217    return var;
00218 }
00219 
00220 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00221 static const char *party_number_ton2str(int ton)
00222 {
00223 #if defined(HAVE_PRI)
00224    switch ((ton >> 4) & 0x07) {
00225    case PRI_TON_INTERNATIONAL:
00226       return "International";
00227    case PRI_TON_NATIONAL:
00228       return "National";
00229    case PRI_TON_NET_SPECIFIC:
00230       return "Network Specific";
00231    case PRI_TON_SUBSCRIBER:
00232       return "Subscriber";
00233    case PRI_TON_ABBREVIATED:
00234       return "Abbreviated";
00235    case PRI_TON_RESERVED:
00236       return "Reserved";
00237    case PRI_TON_UNKNOWN:
00238    default:
00239       break;
00240    }
00241 #endif   /* defined(HAVE_PRI) */
00242    return "Unknown";
00243 }
00244 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00245 
00246 #if defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED)
00247 static const char *party_number_plan2str(int plan)
00248 {
00249 #if defined(HAVE_PRI)
00250    switch (plan & 0x0F) {
00251    default:
00252    case PRI_NPI_UNKNOWN:
00253       break;
00254    case PRI_NPI_E163_E164:
00255       return "Public (E.163/E.164)";
00256    case PRI_NPI_X121:
00257       return "Data (X.121)";
00258    case PRI_NPI_F69:
00259       return "Telex (F.69)";
00260    case PRI_NPI_NATIONAL:
00261       return "National Standard";
00262    case PRI_NPI_PRIVATE:
00263       return "Private";
00264    case PRI_NPI_RESERVED:
00265       return "Reserved";
00266    }
00267 #endif   /* defined(HAVE_PRI) */
00268    return "Unknown";
00269 }
00270 #endif   /* defined(KEEP_TILL_CHANNEL_PARTY_NUMBER_INFO_NEEDED) */
00271 
00272 /*! \brief Show channel types - CLI command */
00273 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00274 {
00275 #define FORMAT  "%-15.15s  %-40.40s %-13.13s %-13.13s %-13.13s %-13.13s\n"
00276    struct chanlist *cl;
00277    int count_chan = 0;
00278 
00279    switch (cmd) {
00280    case CLI_INIT:
00281       e->command = "core show channeltypes";
00282       e->usage =
00283          "Usage: core show channeltypes\n"
00284          "       Lists available channel types registered in your\n"
00285          "       Asterisk server.\n";
00286       return NULL;
00287    case CLI_GENERATE:
00288       return NULL;
00289    }
00290 
00291    if (a->argc != 3)
00292       return CLI_SHOWUSAGE;
00293 
00294    ast_cli(a->fd, FORMAT, "Type", "Description", "Devicestate", "Presencestate", "Indications", "Transfer");
00295    ast_cli(a->fd, FORMAT, "-------------", "-------------", "-------------", "-------------", "-------------", "-------------");
00296 
00297    AST_RWLIST_RDLOCK(&backends);
00298    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00299       ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
00300          (cl->tech->devicestate) ? "yes" : "no",
00301          (cl->tech->presencestate) ? "yes" : "no",
00302          (cl->tech->indicate) ? "yes" : "no",
00303          (cl->tech->transfer) ? "yes" : "no");
00304       count_chan++;
00305    }
00306    AST_RWLIST_UNLOCK(&backends);
00307 
00308    ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
00309 
00310    return CLI_SUCCESS;
00311 
00312 #undef FORMAT
00313 }
00314 
00315 static char *complete_channeltypes(struct ast_cli_args *a)
00316 {
00317    struct chanlist *cl;
00318    int which = 0;
00319    int wordlen;
00320    char *ret = NULL;
00321 
00322    if (a->pos != 3)
00323       return NULL;
00324 
00325    wordlen = strlen(a->word);
00326 
00327    AST_RWLIST_RDLOCK(&backends);
00328    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00329       if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
00330          ret = ast_strdup(cl->tech->type);
00331          break;
00332       }
00333    }
00334    AST_RWLIST_UNLOCK(&backends);
00335 
00336    return ret;
00337 }
00338 
00339 /*! \brief Show details about a channel driver - CLI command */
00340 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00341 {
00342    struct chanlist *cl = NULL;
00343    struct ast_str *codec_buf = ast_str_alloca(256);
00344 
00345    switch (cmd) {
00346    case CLI_INIT:
00347       e->command = "core show channeltype";
00348       e->usage =
00349          "Usage: core show channeltype <name>\n"
00350          "  Show details about the specified channel type, <name>.\n";
00351       return NULL;
00352    case CLI_GENERATE:
00353       return complete_channeltypes(a);
00354    }
00355 
00356    if (a->argc != 4)
00357       return CLI_SHOWUSAGE;
00358 
00359    AST_RWLIST_RDLOCK(&backends);
00360 
00361    AST_RWLIST_TRAVERSE(&backends, cl, list) {
00362       if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
00363          break;
00364    }
00365 
00366 
00367    if (!cl) {
00368       ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
00369       AST_RWLIST_UNLOCK(&backends);
00370       return CLI_FAILURE;
00371    }
00372 
00373    ast_cli(a->fd,
00374       "-- Info about channel driver: %s --\n"
00375       "  Device State: %s\n"
00376       "Presence State: %s\n"
00377       "    Indication: %s\n"
00378       "     Transfer : %s\n"
00379       "  Capabilities: %s\n"
00380       "   Digit Begin: %s\n"
00381       "     Digit End: %s\n"
00382       "    Send HTML : %s\n"
00383       " Image Support: %s\n"
00384       "  Text Support: %s\n",
00385       cl->tech->type,
00386       (cl->tech->devicestate) ? "yes" : "no",
00387       (cl->tech->presencestate) ? "yes" : "no",
00388       (cl->tech->indicate) ? "yes" : "no",
00389       (cl->tech->transfer) ? "yes" : "no",
00390       ast_format_cap_get_names(cl->tech->capabilities, &codec_buf),
00391       (cl->tech->send_digit_begin) ? "yes" : "no",
00392       (cl->tech->send_digit_end) ? "yes" : "no",
00393       (cl->tech->send_html) ? "yes" : "no",
00394       (cl->tech->send_image) ? "yes" : "no",
00395       (cl->tech->send_text) ? "yes" : "no"
00396 
00397    );
00398 
00399    AST_RWLIST_UNLOCK(&backends);
00400 
00401    return CLI_SUCCESS;
00402 }
00403 
00404 static struct ast_cli_entry cli_channel[] = {
00405    AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
00406    AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
00407 };
00408 
00409 static struct ast_frame *kill_read(struct ast_channel *chan)
00410 {
00411    /* Hangup channel. */
00412    return NULL;
00413 }
00414 
00415 static struct ast_frame *kill_exception(struct ast_channel *chan)
00416 {
00417    /* Hangup channel. */
00418    return NULL;
00419 }
00420 
00421 static int kill_write(struct ast_channel *chan, struct ast_frame *frame)
00422 {
00423    /* Hangup channel. */
00424    return -1;
00425 }
00426 
00427 static int kill_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
00428 {
00429    /* No problem fixing up the channel. */
00430    return 0;
00431 }
00432 
00433 static int kill_hangup(struct ast_channel *chan)
00434 {
00435    ast_channel_tech_pvt_set(chan, NULL);
00436    return 0;
00437 }
00438 
00439 /*!
00440  * \brief Kill the channel channel driver technology descriptor.
00441  *
00442  * \details
00443  * The purpose of this channel technology is to encourage the
00444  * channel to hangup as quickly as possible.
00445  *
00446  * \note Used by DTMF atxfer and zombie channels.
00447  */
00448 const struct ast_channel_tech ast_kill_tech = {
00449    .type = "Kill",
00450    .description = "Kill channel (should not see this)",
00451    .read = kill_read,
00452    .exception = kill_exception,
00453    .write = kill_write,
00454    .fixup = kill_fixup,
00455    .hangup = kill_hangup,
00456 };
00457 
00458 /*! \brief Checks to see if a channel is needing hang up */
00459 int ast_check_hangup(struct ast_channel *chan)
00460 {
00461    if (ast_channel_softhangup_internal_flag(chan))    /* yes if soft hangup flag set */
00462       return 1;
00463    if (ast_tvzero(*ast_channel_whentohangup(chan)))   /* no if no hangup scheduled */
00464       return 0;
00465    if (ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()) > 0)    /* no if hangup time has not come yet. */
00466       return 0;
00467    ast_debug(4, "Hangup time has come: %" PRIi64 "\n", ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow()));
00468    ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(chan));
00469    ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT); /* record event */
00470    return 1;
00471 }
00472 
00473 int ast_check_hangup_locked(struct ast_channel *chan)
00474 {
00475    int res;
00476    ast_channel_lock(chan);
00477    res = ast_check_hangup(chan);
00478    ast_channel_unlock(chan);
00479    return res;
00480 }
00481 
00482 void ast_channel_softhangup_withcause_locked(struct ast_channel *chan, int causecode)
00483 {
00484    ast_channel_lock(chan);
00485 
00486    if (causecode > 0) {
00487       ast_debug(1, "Setting hangupcause of channel %s to %d (is %d now)\n",
00488          ast_channel_name(chan), causecode, ast_channel_hangupcause(chan));
00489 
00490       ast_channel_hangupcause_set(chan, causecode);
00491    }
00492 
00493    ast_softhangup_nolock(chan, AST_SOFTHANGUP_EXPLICIT);
00494 
00495    ast_channel_unlock(chan);
00496 }
00497 
00498 static int ast_channel_softhangup_cb(void *obj, void *arg, int flags)
00499 {
00500    struct ast_channel *chan = obj;
00501 
00502    ast_softhangup(chan, AST_SOFTHANGUP_SHUTDOWN);
00503 
00504    return 0;
00505 }
00506 
00507 void ast_softhangup_all(void)
00508 {
00509    ao2_callback(channels, OBJ_NODATA | OBJ_MULTIPLE, ast_channel_softhangup_cb, NULL);
00510 }
00511 
00512 /*! \brief returns number of active/allocated channels */
00513 int ast_active_channels(void)
00514 {
00515    return channels ? ao2_container_count(channels) : 0;
00516 }
00517 
00518 int ast_undestroyed_channels(void)
00519 {
00520    return ast_atomic_fetchadd_int(&chancount, 0);
00521 }
00522 
00523 /*! \brief Set when to hangup channel */
00524 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00525 {
00526    if (ast_tvzero(offset)) {
00527       ast_channel_whentohangup_set(chan, &offset);
00528    } else {
00529       struct timeval tv = ast_tvadd(offset, ast_tvnow());
00530       ast_channel_whentohangup_set(chan, &tv);
00531    }
00532    ast_queue_frame(chan, &ast_null_frame);
00533    return;
00534 }
00535 
00536 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
00537 {
00538    struct timeval when = { offset, };
00539    ast_channel_setwhentohangup_tv(chan, when);
00540 }
00541 
00542 /*! \brief Compare a offset with when to hangup channel */
00543 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00544 {
00545    struct timeval whentohangup;
00546 
00547    if (ast_tvzero(*ast_channel_whentohangup(chan)))
00548       return ast_tvzero(offset) ? 0 : -1;
00549 
00550    if (ast_tvzero(offset))
00551       return 1;
00552 
00553    whentohangup = ast_tvadd(offset, ast_tvnow());
00554 
00555    return ast_tvdiff_ms(whentohangup, *ast_channel_whentohangup(chan));
00556 }
00557 
00558 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
00559 {
00560    struct timeval when = { offset, };
00561    return ast_channel_cmpwhentohangup_tv(chan, when);
00562 }
00563 
00564 /*! \brief Register a new telephony channel in Asterisk */
00565 int ast_channel_register(const struct ast_channel_tech *tech)
00566 {
00567    struct chanlist *chan;
00568 
00569    AST_RWLIST_WRLOCK(&backends);
00570 
00571    AST_RWLIST_TRAVERSE(&backends, chan, list) {
00572       if (!strcasecmp(tech->type, chan->tech->type)) {
00573          ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
00574          AST_RWLIST_UNLOCK(&backends);
00575          return -1;
00576       }
00577    }
00578 
00579    if (!(chan = ast_calloc(1, sizeof(*chan)))) {
00580       AST_RWLIST_UNLOCK(&backends);
00581       return -1;
00582    }
00583    chan->tech = tech;
00584    AST_RWLIST_INSERT_HEAD(&backends, chan, list);
00585 
00586    ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
00587 
00588    ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
00589 
00590    AST_RWLIST_UNLOCK(&backends);
00591 
00592    return 0;
00593 }
00594 
00595 /*! \brief Unregister channel driver */
00596 void ast_channel_unregister(const struct ast_channel_tech *tech)
00597 {
00598    struct chanlist *chan;
00599 
00600    ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
00601 
00602    AST_RWLIST_WRLOCK(&backends);
00603 
00604    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
00605       if (chan->tech == tech) {
00606          AST_LIST_REMOVE_CURRENT(list);
00607          ast_free(chan);
00608          ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
00609          break;
00610       }
00611    }
00612    AST_LIST_TRAVERSE_SAFE_END;
00613 
00614    AST_RWLIST_UNLOCK(&backends);
00615 }
00616 
00617 /*! \brief Get handle to channel driver based on name */
00618 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
00619 {
00620    struct chanlist *chanls;
00621    const struct ast_channel_tech *ret = NULL;
00622 
00623    AST_RWLIST_RDLOCK(&backends);
00624 
00625    AST_RWLIST_TRAVERSE(&backends, chanls, list) {
00626       if (!strcasecmp(name, chanls->tech->type)) {
00627          ret = chanls->tech;
00628          break;
00629       }
00630    }
00631 
00632    AST_RWLIST_UNLOCK(&backends);
00633 
00634    return ret;
00635 }
00636 
00637 /*! \brief Gives the string form of a given hangup cause */
00638 const char *ast_cause2str(int cause)
00639 {
00640    int x;
00641 
00642    for (x = 0; x < ARRAY_LEN(causes); x++) {
00643       if (causes[x].cause == cause)
00644          return causes[x].desc;
00645    }
00646 
00647    return "Unknown";
00648 }
00649 
00650 /*! \brief Convert a symbolic hangup cause to number */
00651 int ast_str2cause(const char *name)
00652 {
00653    int x;
00654 
00655    for (x = 0; x < ARRAY_LEN(causes); x++)
00656       if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
00657          return causes[x].cause;
00658 
00659    return -1;
00660 }
00661 
00662 static struct stasis_message *create_channel_snapshot_message(struct ast_channel *channel)
00663 {
00664    RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
00665 
00666    if (!ast_channel_snapshot_type()) {
00667       return NULL;
00668    }
00669 
00670    ast_channel_lock(channel);
00671    snapshot = ast_channel_snapshot_create(channel);
00672    ast_channel_unlock(channel);
00673    if (!snapshot) {
00674       return NULL;
00675    }
00676 
00677    return stasis_message_create(ast_channel_snapshot_type(), snapshot);
00678 }
00679 
00680 static void publish_cache_clear(struct ast_channel *chan)
00681 {
00682    RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
00683    RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
00684 
00685    clear_msg = create_channel_snapshot_message(chan);
00686    if (!clear_msg) {
00687       return;
00688    }
00689 
00690    message = stasis_cache_clear_create(clear_msg);
00691    stasis_publish(ast_channel_topic(chan), message);
00692 }
00693 
00694 /*! \brief Gives the string form of a given channel state.
00695  *
00696  * \note This function is not reentrant.
00697  *
00698  * \param state
00699  */
00700 const char *ast_state2str(enum ast_channel_state state)
00701 {
00702    char *buf;
00703 
00704    switch (state) {
00705    case AST_STATE_DOWN:
00706       return "Down";
00707    case AST_STATE_RESERVED:
00708       return "Rsrvd";
00709    case AST_STATE_OFFHOOK:
00710       return "OffHook";
00711    case AST_STATE_DIALING:
00712       return "Dialing";
00713    case AST_STATE_RING:
00714       return "Ring";
00715    case AST_STATE_RINGING:
00716       return "Ringing";
00717    case AST_STATE_UP:
00718       return "Up";
00719    case AST_STATE_BUSY:
00720       return "Busy";
00721    case AST_STATE_DIALING_OFFHOOK:
00722       return "Dialing Offhook";
00723    case AST_STATE_PRERING:
00724       return "Pre-ring";
00725    case AST_STATE_MUTE:
00726       return "Mute";
00727    default:
00728       if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
00729          return "Unknown";
00730       snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%u)", state);
00731       return buf;
00732    }
00733 }
00734 
00735 /*! \brief Gives the string form of a given transfer capability */
00736 char *ast_transfercapability2str(int transfercapability)
00737 {
00738    switch (transfercapability) {
00739    case AST_TRANS_CAP_SPEECH:
00740       return "SPEECH";
00741    case AST_TRANS_CAP_DIGITAL:
00742       return "DIGITAL";
00743    case AST_TRANS_CAP_RESTRICTED_DIGITAL:
00744       return "RESTRICTED_DIGITAL";
00745    case AST_TRANS_CAP_3_1K_AUDIO:
00746       return "3K1AUDIO";
00747    case AST_TRANS_CAP_DIGITAL_W_TONES:
00748       return "DIGITAL_W_TONES";
00749    case AST_TRANS_CAP_VIDEO:
00750       return "VIDEO";
00751    default:
00752       return "UNKNOWN";
00753    }
00754 }
00755 
00756 /*! \brief Channel technology used to extract a channel from a running application. The
00757  * channel created with this technology will be immediately hung up - most external
00758  * applications won't ever want to see this.
00759  */
00760 static const struct ast_channel_tech surrogate_tech = {
00761    .type = "Surrogate",
00762    .description = "Surrogate channel used to pull channel from an application",
00763    .properties = AST_CHAN_TP_INTERNAL,
00764 };
00765 
00766 static const struct ast_channel_tech null_tech = {
00767    .type = "NULL",
00768    .description = "Null channel (should not see this)",
00769 };
00770 
00771 static void ast_channel_destructor(void *obj);
00772 static void ast_dummy_channel_destructor(void *obj);
00773 
00774 /*! \brief Create a new channel structure */
00775 static struct ast_channel * attribute_malloc __attribute__((format(printf, 15, 0)))
00776 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
00777              const char *acctcode, const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
00778              const struct ast_channel *requestor, enum ama_flags amaflag, struct ast_endpoint *endpoint,
00779              const char *file, int line,
00780              const char *function, const char *name_fmt, va_list ap)
00781 {
00782    struct ast_channel *tmp;
00783    struct varshead *headp;
00784    char *tech = "", *tech2 = NULL;
00785    struct ast_format_cap *nativeformats;
00786    struct ast_sched_context *schedctx;
00787    struct ast_timer *timer;
00788    struct timeval now;
00789    const struct ast_channel_tech *channel_tech;
00790 
00791    /* If shutting down, don't allocate any new channels */
00792    if (ast_shutting_down()) {
00793       ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
00794       return NULL;
00795    }
00796 
00797    if (!(tmp = ast_channel_internal_alloc(ast_channel_destructor, assignedids, requestor))) {
00798       /* Channel structure allocation failure. */
00799       return NULL;
00800    }
00801 
00802    ast_channel_stage_snapshot(tmp);
00803 
00804    if (!(nativeformats = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
00805       /* format capabilities structure allocation failure */
00806       return ast_channel_unref(tmp);
00807    }
00808    ast_format_cap_append(nativeformats, ast_format_none, 0);
00809    ast_channel_nativeformats_set(tmp, nativeformats);
00810    ao2_ref(nativeformats, -1);
00811 
00812    ast_channel_set_rawwriteformat(tmp, ast_format_none);
00813    ast_channel_set_rawreadformat(tmp, ast_format_none);
00814    ast_channel_set_writeformat(tmp, ast_format_none);
00815    ast_channel_set_readformat(tmp, ast_format_none);
00816 
00817    /*
00818     * Init file descriptors to unopened state so
00819     * the destructor can know not to close them.
00820     */
00821    ast_channel_timingfd_set(tmp, -1);
00822    ast_channel_internal_alertpipe_clear(tmp);
00823    ast_channel_internal_fd_clear_all(tmp);
00824 
00825 #ifdef HAVE_EPOLL
00826    ast_channel_epfd_set(tmp, epoll_create(25));
00827 #endif
00828 
00829    if (!(schedctx = ast_sched_context_create())) {
00830       ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
00831       return ast_channel_unref(tmp);
00832    }
00833    ast_channel_sched_set(tmp, schedctx);
00834 
00835    ast_party_dialed_init(ast_channel_dialed(tmp));
00836    ast_party_caller_init(ast_channel_caller(tmp));
00837    ast_party_connected_line_init(ast_channel_connected(tmp));
00838    ast_party_connected_line_init(ast_channel_connected_indicated(tmp));
00839    ast_party_redirecting_init(ast_channel_redirecting(tmp));
00840 
00841    if (cid_name) {
00842       ast_channel_caller(tmp)->id.name.valid = 1;
00843       ast_channel_caller(tmp)->id.name.str = ast_strdup(cid_name);
00844       if (!ast_channel_caller(tmp)->id.name.str) {
00845          return ast_channel_unref(tmp);
00846       }
00847    }
00848    if (cid_num) {
00849       ast_channel_caller(tmp)->id.number.valid = 1;
00850       ast_channel_caller(tmp)->id.number.str = ast_strdup(cid_num);
00851       if (!ast_channel_caller(tmp)->id.number.str) {
00852          return ast_channel_unref(tmp);
00853       }
00854    }
00855 
00856    if ((timer = ast_timer_open())) {
00857       ast_channel_timer_set(tmp, timer);
00858       if (strcmp(ast_timer_get_name(ast_channel_timer(tmp)), "timerfd")) {
00859          needqueue = 0;
00860       }
00861       ast_channel_timingfd_set(tmp, ast_timer_fd(ast_channel_timer(tmp)));
00862    }
00863 
00864    if (needqueue && ast_channel_internal_alertpipe_init(tmp)) {
00865       return ast_channel_unref(tmp);
00866    }
00867 
00868    /* Always watch the alertpipe */
00869    ast_channel_set_fd(tmp, AST_ALERT_FD, ast_channel_internal_alert_readfd(tmp));
00870    /* And timing pipe */
00871    ast_channel_set_fd(tmp, AST_TIMING_FD, ast_channel_timingfd(tmp));
00872 
00873    /* Initial state */
00874    ast_channel_state_set(tmp, state);
00875    ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);
00876 
00877    ast_channel_streamid_set(tmp, -1);
00878 
00879    ast_channel_fin_set(tmp, global_fin);
00880    ast_channel_fout_set(tmp, global_fout);
00881 
00882    now = ast_tvnow();
00883    ast_channel_creationtime_set(tmp, &now);
00884 
00885    ast_channel_internal_setup_topics(tmp);
00886 
00887    if (!ast_strlen_zero(name_fmt)) {
00888       char *slash, *slash2;
00889       /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
00890        * And they all use slightly different formats for their name string.
00891        * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
00892        * This means, that the stringfields must have a routine that takes the va_lists directly, and
00893        * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
00894        * This new function was written so this can be accomplished.
00895        */
00896       ast_channel_name_build_va(tmp, name_fmt, ap);
00897       tech = ast_strdupa(ast_channel_name(tmp));
00898       if ((slash = strchr(tech, '/'))) {
00899          if ((slash2 = strchr(slash + 1, '/'))) {
00900             tech2 = slash + 1;
00901             *slash2 = '\0';
00902          }
00903          *slash = '\0';
00904       }
00905    } else {
00906       /*
00907        * Start the string with '-' so it becomes an empty string
00908        * in the destructor.
00909        */
00910       ast_channel_name_set(tmp, "-**Unknown**");
00911    }
00912 
00913    if (amaflag != AST_AMA_NONE) {
00914       ast_channel_amaflags_set(tmp, amaflag);
00915    } else {
00916       ast_channel_amaflags_set(tmp, DEFAULT_AMA_FLAGS);
00917    }
00918 
00919    if (!ast_strlen_zero(acctcode)) {
00920       ast_channel_accountcode_set(tmp, acctcode);
00921    }
00922    ast_channel_language_set(tmp, ast_defaultlanguage);
00923 
00924    ast_channel_context_set(tmp, S_OR(context, "default"));
00925    ast_channel_exten_set(tmp, S_OR(exten, "s"));
00926    ast_channel_priority_set(tmp, 1);
00927 
00928    headp = ast_channel_varshead(tmp);
00929    AST_LIST_HEAD_INIT_NOLOCK(headp);
00930 
00931    ast_pbx_hangup_handler_init(tmp);
00932    AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
00933    AST_LIST_HEAD_INIT_NOLOCK(ast_channel_autochans(tmp));
00934 
00935    channel_tech = ast_get_channel_tech(tech);
00936    if (!channel_tech && !ast_strlen_zero(tech2)) {
00937       channel_tech = ast_get_channel_tech(tech2);
00938    }
00939    if (channel_tech) {
00940       ast_channel_tech_set(tmp, channel_tech);
00941    } else {
00942       ast_channel_tech_set(tmp, &null_tech);
00943    }
00944 
00945    ast_channel_internal_finalize(tmp);
00946 
00947    ast_atomic_fetchadd_int(&chancount, +1);
00948 
00949    /* You might scream "locking inversion" at seeing this but it is actually perfectly fine.
00950     * Since the channel was just created nothing can know about it yet or even acquire it.
00951     */
00952    ast_channel_lock(tmp);
00953 
00954    ao2_link(channels, tmp);
00955 
00956    if (endpoint) {
00957       ast_endpoint_add_channel(endpoint, tmp);
00958    }
00959 
00960    /*
00961     * And now, since the channel structure is built, and has its name, let
00962     * the world know of its existance
00963     */
00964    ast_channel_stage_snapshot_done(tmp);
00965    return tmp;
00966 }
00967 
00968 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
00969                const char *cid_name, const char *acctcode,
00970                const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
00971                const struct ast_channel *requestor, enum ama_flags amaflag,
00972                struct ast_endpoint *endpoint,
00973                const char *file, int line, const char *function,
00974                const char *name_fmt, ...)
00975 {
00976    va_list ap;
00977    struct ast_channel *result;
00978 
00979    va_start(ap, name_fmt);
00980    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
00981                assignedids, requestor, amaflag, endpoint, file, line, function, name_fmt, ap);
00982    va_end(ap);
00983 
00984    return result;
00985 }
00986 
00987 /* only do the minimum amount of work needed here to make a channel
00988  * structure that can be used to expand channel vars */
00989 #if defined(REF_DEBUG) || defined(__AST_DEBUG_MALLOC)
00990 struct ast_channel *__ast_dummy_channel_alloc(const char *file, int line, const char *function)
00991 #else
00992 struct ast_channel *ast_dummy_channel_alloc(void)
00993 #endif
00994 {
00995    struct ast_channel *tmp;
00996    struct varshead *headp;
00997 
00998    if (!(tmp = ast_channel_internal_alloc(ast_dummy_channel_destructor, NULL, NULL))) {
00999       /* Dummy channel structure allocation failure. */
01000       return NULL;
01001    }
01002 
01003    ast_pbx_hangup_handler_init(tmp);
01004    AST_LIST_HEAD_INIT_NOLOCK(ast_channel_datastores(tmp));
01005 
01006    /*
01007     * Init file descriptors to unopened state just in case
01008     * autoservice is called on the channel or something tries to
01009     * read a frame from it.
01010     */
01011    ast_channel_timingfd_set(tmp, -1);
01012    ast_channel_internal_alertpipe_clear(tmp);
01013    ast_channel_internal_fd_clear_all(tmp);
01014 #ifdef HAVE_EPOLL
01015    ast_channel_epfd_set(tmp, -1);
01016 #endif
01017 
01018    ast_channel_hold_state_set(tmp, AST_CONTROL_UNHOLD);
01019 
01020    ast_channel_internal_setup_topics(tmp);
01021 
01022    headp = ast_channel_varshead(tmp);
01023    AST_LIST_HEAD_INIT_NOLOCK(headp);
01024 
01025    return tmp;
01026 }
01027 
01028 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
01029 {
01030    struct ast_frame *f;
01031    struct ast_frame *cur;
01032    unsigned int new_frames = 0;
01033    unsigned int new_voice_frames = 0;
01034    unsigned int queued_frames = 0;
01035    unsigned int queued_voice_frames = 0;
01036    AST_LIST_HEAD_NOLOCK(,ast_frame) frames;
01037 
01038    ast_channel_lock(chan);
01039 
01040    /*
01041     * Check the last frame on the queue if we are queuing the new
01042     * frames after it.
01043     */
01044    cur = AST_LIST_LAST(ast_channel_readq(chan));
01045    if (cur && cur->frametype == AST_FRAME_CONTROL && !head && (!after || after == cur)) {
01046       switch (cur->subclass.integer) {
01047       case AST_CONTROL_END_OF_Q:
01048          if (fin->frametype == AST_FRAME_CONTROL
01049             && fin->subclass.integer == AST_CONTROL_HANGUP) {
01050             /*
01051              * Destroy the end-of-Q marker frame so we can queue the hangup
01052              * frame in its place.
01053              */
01054             AST_LIST_REMOVE(ast_channel_readq(chan), cur, frame_list);
01055             ast_frfree(cur);
01056 
01057             /*
01058              * This has degenerated to a normal queue append anyway.  Since
01059              * we just destroyed the last frame in the queue we must make
01060              * sure that "after" is NULL or bad things will happen.
01061              */
01062             after = NULL;
01063             break;
01064          }
01065          /* Fall through */
01066       case AST_CONTROL_HANGUP:
01067          /* Don't queue anything. */
01068          ast_channel_unlock(chan);
01069          return 0;
01070       default:
01071          break;
01072       }
01073    }
01074 
01075    /* Build copies of all the new frames and count them */
01076    AST_LIST_HEAD_INIT_NOLOCK(&frames);
01077    for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
01078       if (!(f = ast_frdup(cur))) {
01079          if (AST_LIST_FIRST(&frames)) {
01080             ast_frfree(AST_LIST_FIRST(&frames));
01081          }
01082          ast_channel_unlock(chan);
01083          return -1;
01084       }
01085 
01086       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01087       new_frames++;
01088       if (f->frametype == AST_FRAME_VOICE) {
01089          new_voice_frames++;
01090       }
01091    }
01092 
01093    /* Count how many frames exist on the queue */
01094    AST_LIST_TRAVERSE(ast_channel_readq(chan), cur, frame_list) {
01095       queued_frames++;
01096       if (cur->frametype == AST_FRAME_VOICE) {
01097          queued_voice_frames++;
01098       }
01099    }
01100 
01101    if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
01102       int count = 0;
01103       ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", ast_channel_name(chan));
01104       AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), cur, frame_list) {
01105          /* Save the most recent frame */
01106          if (!AST_LIST_NEXT(cur, frame_list)) {
01107             break;
01108          } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
01109             if (++count > 64) {
01110                break;
01111             }
01112             AST_LIST_REMOVE_CURRENT(frame_list);
01113             ast_frfree(cur);
01114          }
01115       }
01116       AST_LIST_TRAVERSE_SAFE_END;
01117    }
01118 
01119    if (after) {
01120       AST_LIST_INSERT_LIST_AFTER(ast_channel_readq(chan), &frames, after, frame_list);
01121    } else {
01122       if (head) {
01123          AST_LIST_APPEND_LIST(&frames, ast_channel_readq(chan), frame_list);
01124          AST_LIST_HEAD_INIT_NOLOCK(ast_channel_readq(chan));
01125       }
01126       AST_LIST_APPEND_LIST(ast_channel_readq(chan), &frames, frame_list);
01127    }
01128 
01129    if (ast_channel_alert_writable(chan)) {
01130       if (ast_channel_alert_write(chan)) {
01131          ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %u): %s!\n",
01132             ast_channel_name(chan), queued_frames, strerror(errno));
01133       }
01134    } else if (ast_channel_timingfd(chan) > -1) {
01135       ast_timer_enable_continuous(ast_channel_timer(chan));
01136    } else if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
01137       pthread_kill(ast_channel_blocker(chan), SIGURG);
01138    }
01139 
01140    ast_channel_unlock(chan);
01141 
01142    return 0;
01143 }
01144 
01145 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
01146 {
01147    return __ast_queue_frame(chan, fin, 0, NULL);
01148 }
01149 
01150 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
01151 {
01152    return __ast_queue_frame(chan, fin, 1, NULL);
01153 }
01154 
01155 /*! \brief Queue a hangup frame for channel */
01156 int ast_queue_hangup(struct ast_channel *chan)
01157 {
01158    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
01159    int res;
01160 
01161    /* Yeah, let's not change a lock-critical value without locking */
01162    ast_channel_lock(chan);
01163    ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
01164    ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), NULL);
01165 
01166    res = ast_queue_frame(chan, &f);
01167    ast_channel_unlock(chan);
01168    return res;
01169 }
01170 
01171 /*! \brief Queue a hangup frame for channel */
01172 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
01173 {
01174    RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
01175    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HANGUP };
01176    int res;
01177 
01178    if (cause >= 0) {
01179       f.data.uint32 = cause;
01180    }
01181 
01182    /* Yeah, let's not change a lock-critical value without locking */
01183    ast_channel_lock(chan);
01184    ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
01185    if (cause < 0) {
01186       f.data.uint32 = ast_channel_hangupcause(chan);
01187    }
01188    blob = ast_json_pack("{s: i}",
01189               "cause", cause);
01190    ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
01191 
01192    res = ast_queue_frame(chan, &f);
01193    ast_channel_unlock(chan);
01194    return res;
01195 }
01196 
01197 int ast_queue_hold(struct ast_channel *chan, const char *musicclass)
01198 {
01199    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_HOLD };
01200    struct ast_json *blob = NULL;
01201    int res;
01202 
01203    if (!ast_strlen_zero(musicclass)) {
01204       f.data.ptr = (void *) musicclass;
01205       f.datalen = strlen(musicclass) + 1;
01206 
01207       blob = ast_json_pack("{s: s}",
01208                  "musicclass", musicclass);
01209    }
01210 
01211    ast_channel_publish_cached_blob(chan, ast_channel_hold_type(), blob);
01212 
01213    res = ast_queue_frame(chan, &f);
01214 
01215    ast_json_unref(blob);
01216 
01217    return res;
01218 }
01219 
01220 int ast_queue_unhold(struct ast_channel *chan)
01221 {
01222    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = AST_CONTROL_UNHOLD };
01223    int res;
01224 
01225    ast_channel_publish_cached_blob(chan, ast_channel_unhold_type(), NULL);
01226 
01227    res = ast_queue_frame(chan, &f);
01228 
01229    return res;
01230 }
01231 
01232 /*! \brief Queue a control frame */
01233 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
01234 {
01235    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control };
01236    return ast_queue_frame(chan, &f);
01237 }
01238 
01239 /*! \brief Queue a control frame with payload */
01240 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
01241             const void *data, size_t datalen)
01242 {
01243    struct ast_frame f = { AST_FRAME_CONTROL, .subclass.integer = control, .data.ptr = (void *) data, .datalen = datalen };
01244    return ast_queue_frame(chan, &f);
01245 }
01246 
01247 /*! \brief Set defer DTMF flag on channel */
01248 int ast_channel_defer_dtmf(struct ast_channel *chan)
01249 {
01250    int pre = 0;
01251 
01252    if (chan) {
01253       pre = ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
01254       ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
01255    }
01256    return pre;
01257 }
01258 
01259 /*! \brief Unset defer DTMF flag on channel */
01260 void ast_channel_undefer_dtmf(struct ast_channel *chan)
01261 {
01262    if (chan)
01263       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF);
01264 }
01265 
01266 struct ast_channel *ast_channel_callback(ao2_callback_data_fn *cb_fn, void *arg,
01267       void *data, int ao2_flags)
01268 {
01269    return ao2_callback_data(channels, ao2_flags, cb_fn, arg, data);
01270 }
01271 
01272 static int ast_channel_by_name_cb(void *obj, void *arg, void *data, int flags)
01273 {
01274    struct ast_channel *chan = obj;
01275    const char *name = arg;
01276    size_t name_len = *(size_t *) data;
01277    int ret = CMP_MATCH;
01278 
01279    if (ast_strlen_zero(name)) {
01280       ast_log(LOG_ERROR, "BUG! Must supply a channel name or partial name to match!\n");
01281       return CMP_STOP;
01282    }
01283 
01284    ast_channel_lock(chan);
01285    if ((!name_len && strcasecmp(ast_channel_name(chan), name))
01286       || (name_len && strncasecmp(ast_channel_name(chan), name, name_len))) {
01287       ret = 0; /* name match failed, keep looking */
01288    }
01289    ast_channel_unlock(chan);
01290 
01291    return ret;
01292 }
01293 
01294 static int ast_channel_by_exten_cb(void *obj, void *arg, void *data, int flags)
01295 {
01296    struct ast_channel *chan = obj;
01297    char *context = arg;
01298    char *exten = data;
01299    int ret = CMP_MATCH;
01300 
01301    if (ast_strlen_zero(exten) || ast_strlen_zero(context)) {
01302       ast_log(LOG_ERROR, "BUG! Must have a context and extension to match!\n");
01303       return CMP_STOP;
01304    }
01305 
01306    ast_channel_lock(chan);
01307    if (strcasecmp(ast_channel_context(chan), context) && strcasecmp(ast_channel_macrocontext(chan), context)) {
01308       ret = 0; /* Context match failed, continue */
01309    } else if (strcasecmp(ast_channel_exten(chan), exten) && strcasecmp(ast_channel_macroexten(chan), exten)) {
01310       ret = 0; /* Extension match failed, continue */
01311    }
01312    ast_channel_unlock(chan);
01313 
01314    return ret;
01315 }
01316 
01317 static int ast_channel_by_uniqueid_cb(void *obj, void *arg, void *data, int flags)
01318 {
01319    struct ast_channel *chan = obj;
01320    char *uniqueid = arg;
01321    size_t id_len = *(size_t *) data;
01322    int ret = CMP_MATCH;
01323 
01324    if (ast_strlen_zero(uniqueid)) {
01325       ast_log(LOG_ERROR, "BUG! Must supply a uniqueid or partial uniqueid to match!\n");
01326       return CMP_STOP;
01327    }
01328 
01329    ast_channel_lock(chan);
01330    if ((!id_len && strcasecmp(ast_channel_uniqueid(chan), uniqueid))
01331       || (id_len && strncasecmp(ast_channel_uniqueid(chan), uniqueid, id_len))) {
01332       ret = 0; /* uniqueid match failed, keep looking */
01333    }
01334    ast_channel_unlock(chan);
01335 
01336    return ret;
01337 }
01338 
01339 struct ast_channel_iterator {
01340    /* storage for non-dynamically allocated iterator */
01341    struct ao2_iterator simple_iterator;
01342    /* pointer to the actual iterator (simple_iterator or a dynamically
01343     * allocated iterator)
01344     */
01345    struct ao2_iterator *active_iterator;
01346 };
01347 
01348 struct ast_channel_iterator *ast_channel_iterator_destroy(struct ast_channel_iterator *i)
01349 {
01350    ao2_iterator_destroy(i->active_iterator);
01351    ast_free(i);
01352 
01353    return NULL;
01354 }
01355 
01356 struct ast_channel_iterator *ast_channel_iterator_by_exten_new(const char *exten, const char *context)
01357 {
01358    struct ast_channel_iterator *i;
01359    char *l_exten = (char *) exten;
01360    char *l_context = (char *) context;
01361 
01362    if (!(i = ast_calloc(1, sizeof(*i)))) {
01363       return NULL;
01364    }
01365 
01366    i->active_iterator = (void *) ast_channel_callback(ast_channel_by_exten_cb,
01367       l_context, l_exten, OBJ_MULTIPLE);
01368    if (!i->active_iterator) {
01369       ast_free(i);
01370       return NULL;
01371    }
01372 
01373    return i;
01374 }
01375 
01376 struct ast_channel_iterator *ast_channel_iterator_by_name_new(const char *name, size_t name_len)
01377 {
01378    struct ast_channel_iterator *i;
01379    char *l_name = (char *) name;
01380 
01381    if (!(i = ast_calloc(1, sizeof(*i)))) {
01382       return NULL;
01383    }
01384 
01385    i->active_iterator = (void *) ast_channel_callback(ast_channel_by_name_cb,
01386       l_name, &name_len,
01387       OBJ_MULTIPLE | (name_len == 0 /* match the whole word, so optimize */ ? OBJ_KEY : 0));
01388    if (!i->active_iterator) {
01389       ast_free(i);
01390       return NULL;
01391    }
01392 
01393    return i;
01394 }
01395 
01396 struct ast_channel_iterator *ast_channel_iterator_all_new(void)
01397 {
01398    struct ast_channel_iterator *i;
01399 
01400    if (!(i = ast_calloc(1, sizeof(*i)))) {
01401       return NULL;
01402    }
01403 
01404    i->simple_iterator = ao2_iterator_init(channels, 0);
01405    i->active_iterator = &i->simple_iterator;
01406 
01407    return i;
01408 }
01409 
01410 struct ast_channel *ast_channel_iterator_next(struct ast_channel_iterator *i)
01411 {
01412    return ao2_iterator_next(i->active_iterator);
01413 }
01414 
01415 /* Legacy function, not currently used for lookups, but we need a cmp_fn */
01416 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
01417 {
01418    ast_log(LOG_ERROR, "BUG! Should never be called!\n");
01419    return CMP_STOP;
01420 }
01421 
01422 struct ast_channel *ast_channel_get_by_name_prefix(const char *name, size_t name_len)
01423 {
01424    struct ast_channel *chan;
01425    char *l_name = (char *) name;
01426 
01427    chan = ast_channel_callback(ast_channel_by_name_cb, l_name, &name_len,
01428       (name_len == 0) /* optimize if it is a complete name match */ ? OBJ_KEY : 0);
01429    if (chan) {
01430       return chan;
01431    }
01432 
01433    if (ast_strlen_zero(l_name)) {
01434       /* We didn't have a name to search for so quit. */
01435       return NULL;
01436    }
01437 
01438    /* Now try a search for uniqueid. */
01439    return ast_channel_callback(ast_channel_by_uniqueid_cb, l_name, &name_len, 0);
01440 }
01441 
01442 struct ast_channel *ast_channel_get_by_name(const char *name)
01443 {
01444    return ast_channel_get_by_name_prefix(name, 0);
01445 }
01446 
01447 struct ast_channel *ast_channel_get_by_exten(const char *exten, const char *context)
01448 {
01449    char *l_exten = (char *) exten;
01450    char *l_context = (char *) context;
01451 
01452    return ast_channel_callback(ast_channel_by_exten_cb, l_context, l_exten, 0);
01453 }
01454 
01455 int ast_is_deferrable_frame(const struct ast_frame *frame)
01456 {
01457    /* Do not add a default entry in this switch statement.  Each new
01458     * frame type should be addressed directly as to whether it should
01459     * be queued up or not.
01460     */
01461    switch (frame->frametype) {
01462    case AST_FRAME_BRIDGE_ACTION:
01463    case AST_FRAME_BRIDGE_ACTION_SYNC:
01464    case AST_FRAME_CONTROL:
01465    case AST_FRAME_TEXT:
01466    case AST_FRAME_IMAGE:
01467    case AST_FRAME_HTML:
01468       return 1;
01469 
01470    case AST_FRAME_DTMF_END:
01471    case AST_FRAME_DTMF_BEGIN:
01472    case AST_FRAME_VOICE:
01473    case AST_FRAME_VIDEO:
01474    case AST_FRAME_NULL:
01475    case AST_FRAME_IAX:
01476    case AST_FRAME_CNG:
01477    case AST_FRAME_MODEM:
01478       return 0;
01479    }
01480    return 0;
01481 }
01482 
01483 /*! \brief Wait, look for hangups and condition arg */
01484 int ast_safe_sleep_conditional(struct ast_channel *chan, int timeout_ms, int (*cond)(void*), void *data)
01485 {
01486    struct ast_frame *f;
01487    struct ast_silence_generator *silgen = NULL;
01488    int res = 0;
01489    struct timeval start;
01490    int ms;
01491    AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
01492 
01493    AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
01494 
01495    /* If no other generator is present, start silencegen while waiting */
01496    if (ast_opt_transmit_silence && !ast_channel_generatordata(chan)) {
01497       silgen = ast_channel_start_silence_generator(chan);
01498    }
01499 
01500    start = ast_tvnow();
01501    while ((ms = ast_remaining_ms(start, timeout_ms))) {
01502       struct ast_frame *dup_f = NULL;
01503 
01504       if (cond && ((*cond)(data) == 0)) {
01505          break;
01506       }
01507       ms = ast_waitfor(chan, ms);
01508       if (ms < 0) {
01509          res = -1;
01510          break;
01511       }
01512       if (ms > 0) {
01513          f = ast_read(chan);
01514          if (!f) {
01515             res = -1;
01516             break;
01517          }
01518 
01519          if (!ast_is_deferrable_frame(f)) {
01520             ast_frfree(f);
01521             continue;
01522          }
01523 
01524          if ((dup_f = ast_frisolate(f))) {
01525             if (dup_f != f) {
01526                ast_frfree(f);
01527             }
01528             AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
01529          }
01530       }
01531    }
01532 
01533    /* stop silgen if present */
01534    if (silgen) {
01535       ast_channel_stop_silence_generator(chan, silgen);
01536    }
01537 
01538    /* We need to free all the deferred frames, but we only need to
01539     * queue the deferred frames if there was no error and no
01540     * hangup was received
01541     */
01542    ast_channel_lock(chan);
01543    while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
01544       if (!res) {
01545          ast_queue_frame_head(chan, f);
01546       }
01547       ast_frfree(f);
01548    }
01549    ast_channel_unlock(chan);
01550 
01551    return res;
01552 }
01553 
01554 /*! \brief Wait, look for hangups */
01555 int ast_safe_sleep(struct ast_channel *chan, int ms)
01556 {
01557    return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
01558 }
01559 
01560 struct ast_channel *ast_channel_release(struct ast_channel *chan)
01561 {
01562    /* Safe, even if already unlinked. */
01563    ao2_unlink(channels, chan);
01564    return ast_channel_unref(chan);
01565 }
01566 
01567 void ast_party_name_init(struct ast_party_name *init)
01568 {
01569    init->str = NULL;
01570    init->char_set = AST_PARTY_CHAR_SET_ISO8859_1;
01571    init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
01572    init->valid = 0;
01573 }
01574 
01575 void ast_party_name_copy(struct ast_party_name *dest, const struct ast_party_name *src)
01576 {
01577    if (dest == src) {
01578       /* Don't copy to self */
01579       return;
01580    }
01581 
01582    ast_free(dest->str);
01583    dest->str = ast_strdup(src->str);
01584    dest->char_set = src->char_set;
01585    dest->presentation = src->presentation;
01586    dest->valid = src->valid;
01587 }
01588 
01589 void ast_party_name_set_init(struct ast_party_name *init, const struct ast_party_name *guide)
01590 {
01591    init->str = NULL;
01592    init->char_set = guide->char_set;
01593    init->presentation = guide->presentation;
01594    init->valid = guide->valid;
01595 }
01596 
01597 void ast_party_name_set(struct ast_party_name *dest, const struct ast_party_name *src)
01598 {
01599    if (dest == src) {
01600       /* Don't set to self */
01601       return;
01602    }
01603 
01604    if (src->str && src->str != dest->str) {
01605       ast_free(dest->str);
01606       dest->str = ast_strdup(src->str);
01607    }
01608 
01609    dest->char_set = src->char_set;
01610    dest->presentation = src->presentation;
01611    dest->valid = src->valid;
01612 }
01613 
01614 void ast_party_name_free(struct ast_party_name *doomed)
01615 {
01616    ast_free(doomed->str);
01617    doomed->str = NULL;
01618 }
01619 
01620 void ast_party_number_init(struct ast_party_number *init)
01621 {
01622    init->str = NULL;
01623    init->plan = 0;/* Unknown */
01624    init->presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
01625    init->valid = 0;
01626 }
01627 
01628 void ast_party_number_copy(struct ast_party_number *dest, const struct ast_party_number *src)
01629 {
01630    if (dest == src) {
01631       /* Don't copy to self */
01632       return;
01633    }
01634 
01635    ast_free(dest->str);
01636    dest->str = ast_strdup(src->str);
01637    dest->plan = src->plan;
01638    dest->presentation = src->presentation;
01639    dest->valid = src->valid;
01640 }
01641 
01642 void ast_party_number_set_init(struct ast_party_number *init, const struct ast_party_number *guide)
01643 {
01644    init->str = NULL;
01645    init->plan = guide->plan;
01646    init->presentation = guide->presentation;
01647    init->valid = guide->valid;
01648 }
01649 
01650 void ast_party_number_set(struct ast_party_number *dest, const struct ast_party_number *src)
01651 {
01652    if (dest == src) {
01653       /* Don't set to self */
01654       return;
01655    }
01656 
01657    if (src->str && src->str != dest->str) {
01658       ast_free(dest->str);
01659       dest->str = ast_strdup(src->str);
01660    }
01661 
01662    dest->plan = src->plan;
01663    dest->presentation = src->presentation;
01664    dest->valid = src->valid;
01665 }
01666 
01667 void ast_party_number_free(struct ast_party_number *doomed)
01668 {
01669    ast_free(doomed->str);
01670    doomed->str = NULL;
01671 }
01672 
01673 void ast_party_subaddress_init(struct ast_party_subaddress *init)
01674 {
01675    init->str = NULL;
01676    init->type = 0;
01677    init->odd_even_indicator = 0;
01678    init->valid = 0;
01679 }
01680 
01681 void ast_party_subaddress_copy(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
01682 {
01683    if (dest == src) {
01684       /* Don't copy to self */
01685       return;
01686    }
01687 
01688    ast_free(dest->str);
01689    dest->str = ast_strdup(src->str);
01690    dest->type = src->type;
01691    dest->odd_even_indicator = src->odd_even_indicator;
01692    dest->valid = src->valid;
01693 }
01694 
01695 void ast_party_subaddress_set_init(struct ast_party_subaddress *init, const struct ast_party_subaddress *guide)
01696 {
01697    init->str = NULL;
01698    init->type = guide->type;
01699    init->odd_even_indicator = guide->odd_even_indicator;
01700    init->valid = guide->valid;
01701 }
01702 
01703 void ast_party_subaddress_set(struct ast_party_subaddress *dest, const struct ast_party_subaddress *src)
01704 {
01705    if (dest == src) {
01706       /* Don't set to self */
01707       return;
01708    }
01709 
01710    if (src->str && src->str != dest->str) {
01711       ast_free(dest->str);
01712       dest->str = ast_strdup(src->str);
01713    }
01714 
01715    dest->type = src->type;
01716    dest->odd_even_indicator = src->odd_even_indicator;
01717    dest->valid = src->valid;
01718 }
01719 
01720 void ast_party_subaddress_free(struct ast_party_subaddress *doomed)
01721 {
01722    ast_free(doomed->str);
01723    doomed->str = NULL;
01724 }
01725 
01726 void ast_set_party_id_all(struct ast_set_party_id *update_id)
01727 {
01728    update_id->name = 1;
01729    update_id->number = 1;
01730    update_id->subaddress = 1;
01731 }
01732 
01733 void ast_party_id_init(struct ast_party_id *init)
01734 {
01735    ast_party_name_init(&init->name);
01736    ast_party_number_init(&init->number);
01737    ast_party_subaddress_init(&init->subaddress);
01738    init->tag = NULL;
01739 }
01740 
01741 void ast_party_id_copy(struct ast_party_id *dest, const struct ast_party_id *src)
01742 {
01743    if (dest == src) {
01744       /* Don't copy to self */
01745       return;
01746    }
01747 
01748    ast_party_name_copy(&dest->name, &src->name);
01749    ast_party_number_copy(&dest->number, &src->number);
01750    ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
01751 
01752    ast_free(dest->tag);
01753    dest->tag = ast_strdup(src->tag);
01754 }
01755 
01756 void ast_party_id_set_init(struct ast_party_id *init, const struct ast_party_id *guide)
01757 {
01758    ast_party_name_set_init(&init->name, &guide->name);
01759    ast_party_number_set_init(&init->number, &guide->number);
01760    ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
01761    init->tag = NULL;
01762 }
01763 
01764 void ast_party_id_set(struct ast_party_id *dest, const struct ast_party_id *src, const struct ast_set_party_id *update)
01765 {
01766    if (dest == src) {
01767       /* Don't set to self */
01768       return;
01769    }
01770 
01771    if (!update || update->name) {
01772       ast_party_name_set(&dest->name, &src->name);
01773    }
01774    if (!update || update->number) {
01775       ast_party_number_set(&dest->number, &src->number);
01776    }
01777    if (!update || update->subaddress) {
01778       ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
01779    }
01780 
01781    if (src->tag && src->tag != dest->tag) {
01782       ast_free(dest->tag);
01783       dest->tag = ast_strdup(src->tag);
01784    }
01785 }
01786 
01787 void ast_party_id_free(struct ast_party_id *doomed)
01788 {
01789    ast_party_name_free(&doomed->name);
01790    ast_party_number_free(&doomed->number);
01791    ast_party_subaddress_free(&doomed->subaddress);
01792 
01793    ast_free(doomed->tag);
01794    doomed->tag = NULL;
01795 }
01796 
01797 int ast_party_id_presentation(const struct ast_party_id *id)
01798 {
01799    int number_priority;
01800    int number_value;
01801    int number_screening;
01802    int name_priority;
01803    int name_value;
01804 
01805    /* Determine name presentation priority. */
01806    if (!id->name.valid) {
01807       name_value = AST_PRES_UNAVAILABLE;
01808       name_priority = 3;
01809    } else {
01810       name_value = id->name.presentation & AST_PRES_RESTRICTION;
01811       switch (name_value) {
01812       case AST_PRES_RESTRICTED:
01813          name_priority = 0;
01814          break;
01815       case AST_PRES_ALLOWED:
01816          name_priority = 1;
01817          break;
01818       case AST_PRES_UNAVAILABLE:
01819          name_priority = 2;
01820          break;
01821       default:
01822          name_value = AST_PRES_UNAVAILABLE;
01823          name_priority = 3;
01824          break;
01825       }
01826    }
01827 
01828    /* Determine number presentation priority. */
01829    if (!id->number.valid) {
01830       number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
01831       number_value = AST_PRES_UNAVAILABLE;
01832       number_priority = 3;
01833    } else {
01834       number_screening = id->number.presentation & AST_PRES_NUMBER_TYPE;
01835       number_value = id->number.presentation & AST_PRES_RESTRICTION;
01836       switch (number_value) {
01837       case AST_PRES_RESTRICTED:
01838          number_priority = 0;
01839          break;
01840       case AST_PRES_ALLOWED:
01841          number_priority = 1;
01842          break;
01843       case AST_PRES_UNAVAILABLE:
01844          number_priority = 2;
01845          break;
01846       default:
01847          number_screening = AST_PRES_USER_NUMBER_UNSCREENED;
01848          number_value = AST_PRES_UNAVAILABLE;
01849          number_priority = 3;
01850          break;
01851       }
01852    }
01853 
01854    /* Select the wining presentation value. */
01855    if (name_priority < number_priority) {
01856       number_value = name_value;
01857    }
01858    if (number_value == AST_PRES_UNAVAILABLE) {
01859       return AST_PRES_NUMBER_NOT_AVAILABLE;
01860    }
01861 
01862    return number_value | number_screening;
01863 }
01864 
01865 void ast_party_id_invalidate(struct ast_party_id *id)
01866 {
01867    id->name.valid = 0;
01868    id->number.valid = 0;
01869    id->subaddress.valid = 0;
01870 }
01871 
01872 void ast_party_id_reset(struct ast_party_id *id)
01873 {
01874    ast_party_id_free(id);
01875    ast_party_id_init(id);
01876 }
01877 
01878 struct ast_party_id ast_party_id_merge(struct ast_party_id *base, struct ast_party_id *overlay)
01879 {
01880    struct ast_party_id merged;
01881 
01882    merged = *base;
01883    if (overlay->name.valid) {
01884       merged.name = overlay->name;
01885    }
01886    if (overlay->number.valid) {
01887       merged.number = overlay->number;
01888    }
01889    if (overlay->subaddress.valid) {
01890       merged.subaddress = overlay->subaddress;
01891    }
01892    /* Note the actual structure is returned and not a pointer to it! */
01893    return merged;
01894 }
01895 
01896 void ast_party_id_merge_copy(struct ast_party_id *dest, struct ast_party_id *base, struct ast_party_id *overlay)
01897 {
01898    struct ast_party_id merged;
01899 
01900    merged = ast_party_id_merge(base, overlay);
01901    ast_party_id_copy(dest, &merged);
01902 }
01903 
01904 void ast_party_dialed_init(struct ast_party_dialed *init)
01905 {
01906    init->number.str = NULL;
01907    init->number.plan = 0;/* Unknown */
01908    ast_party_subaddress_init(&init->subaddress);
01909    init->transit_network_select = 0;
01910 }
01911 
01912 void ast_party_dialed_copy(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
01913 {
01914    if (dest == src) {
01915       /* Don't copy to self */
01916       return;
01917    }
01918 
01919    ast_free(dest->number.str);
01920    dest->number.str = ast_strdup(src->number.str);
01921    dest->number.plan = src->number.plan;
01922    ast_party_subaddress_copy(&dest->subaddress, &src->subaddress);
01923    dest->transit_network_select = src->transit_network_select;
01924 }
01925 
01926 void ast_party_dialed_set_init(struct ast_party_dialed *init, const struct ast_party_dialed *guide)
01927 {
01928    init->number.str = NULL;
01929    init->number.plan = guide->number.plan;
01930    ast_party_subaddress_set_init(&init->subaddress, &guide->subaddress);
01931    init->transit_network_select = guide->transit_network_select;
01932 }
01933 
01934 void ast_party_dialed_set(struct ast_party_dialed *dest, const struct ast_party_dialed *src)
01935 {
01936    if (src->number.str && src->number.str != dest->number.str) {
01937       ast_free(dest->number.str);
01938       dest->number.str = ast_strdup(src->number.str);
01939    }
01940    dest->number.plan = src->number.plan;
01941 
01942    ast_party_subaddress_set(&dest->subaddress, &src->subaddress);
01943 
01944    dest->transit_network_select = src->transit_network_select;
01945 }
01946 
01947 void ast_party_dialed_free(struct ast_party_dialed *doomed)
01948 {
01949    ast_free(doomed->number.str);
01950    doomed->number.str = NULL;
01951    ast_party_subaddress_free(&doomed->subaddress);
01952 }
01953 
01954 void ast_party_caller_init(struct ast_party_caller *init)
01955 {
01956    ast_party_id_init(&init->id);
01957    ast_party_id_init(&init->ani);
01958    ast_party_id_init(&init->priv);
01959    init->ani2 = 0;
01960 }
01961 
01962 void ast_party_caller_copy(struct ast_party_caller *dest, const struct ast_party_caller *src)
01963 {
01964    if (dest == src) {
01965       /* Don't copy to self */
01966       return;
01967    }
01968 
01969    ast_party_id_copy(&dest->id, &src->id);
01970    ast_party_id_copy(&dest->ani, &src->ani);
01971    ast_party_id_copy(&dest->priv, &src->priv);
01972    dest->ani2 = src->ani2;
01973 }
01974 
01975 void ast_party_caller_set_init(struct ast_party_caller *init, const struct ast_party_caller *guide)
01976 {
01977    ast_party_id_set_init(&init->id, &guide->id);
01978    ast_party_id_set_init(&init->ani, &guide->ani);
01979    ast_party_id_set_init(&init->priv, &guide->priv);
01980    init->ani2 = guide->ani2;
01981 }
01982 
01983 void ast_party_caller_set(struct ast_party_caller *dest, const struct ast_party_caller *src, const struct ast_set_party_caller *update)
01984 {
01985    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
01986    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
01987    ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
01988    dest->ani2 = src->ani2;
01989 }
01990 
01991 void ast_party_caller_free(struct ast_party_caller *doomed)
01992 {
01993    ast_party_id_free(&doomed->id);
01994    ast_party_id_free(&doomed->ani);
01995    ast_party_id_free(&doomed->priv);
01996 }
01997 
01998 void ast_party_connected_line_init(struct ast_party_connected_line *init)
01999 {
02000    ast_party_id_init(&init->id);
02001    ast_party_id_init(&init->ani);
02002    ast_party_id_init(&init->priv);
02003    init->ani2 = 0;
02004    init->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02005 }
02006 
02007 void ast_party_connected_line_copy(struct ast_party_connected_line *dest, const struct ast_party_connected_line *src)
02008 {
02009    if (dest == src) {
02010       /* Don't copy to self */
02011       return;
02012    }
02013 
02014    ast_party_id_copy(&dest->id, &src->id);
02015    ast_party_id_copy(&dest->ani, &src->ani);
02016    ast_party_id_copy(&dest->priv, &src->priv);
02017    dest->ani2 = src->ani2;
02018    dest->source = src->source;
02019 }
02020 
02021 void ast_party_connected_line_set_init(struct ast_party_connected_line *init, const struct ast_party_connected_line *guide)
02022 {
02023    ast_party_id_set_init(&init->id, &guide->id);
02024    ast_party_id_set_init(&init->ani, &guide->ani);
02025    ast_party_id_set_init(&init->priv, &guide->priv);
02026    init->ani2 = guide->ani2;
02027    init->source = guide->source;
02028 }
02029 
02030 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)
02031 {
02032    ast_party_id_set(&dest->id, &src->id, update ? &update->id : NULL);
02033    ast_party_id_set(&dest->ani, &src->ani, update ? &update->ani : NULL);
02034    ast_party_id_set(&dest->priv, &src->priv, update ? &update->priv : NULL);
02035    dest->ani2 = src->ani2;
02036    dest->source = src->source;
02037 }
02038 
02039 void ast_party_connected_line_collect_caller(struct ast_party_connected_line *connected, struct ast_party_caller *caller)
02040 {
02041    connected->id = caller->id;
02042    connected->ani = caller->ani;
02043    connected->priv = caller->priv;
02044    connected->ani2 = caller->ani2;
02045    connected->source = AST_CONNECTED_LINE_UPDATE_SOURCE_UNKNOWN;
02046 }
02047 
02048 void ast_party_connected_line_free(struct ast_party_connected_line *doomed)
02049 {
02050    ast_party_id_free(&doomed->id);
02051    ast_party_id_free(&doomed->ani);
02052    ast_party_id_free(&doomed->priv);
02053 }
02054 
02055 void ast_party_redirecting_reason_init(struct ast_party_redirecting_reason *init)
02056 {
02057    init->str = NULL;
02058    init->code = AST_REDIRECTING_REASON_UNKNOWN;
02059 }
02060 
02061 void ast_party_redirecting_reason_copy(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
02062 {
02063    if (dest == src) {
02064       return;
02065    }
02066 
02067    ast_free(dest->str);
02068    dest->str = ast_strdup(src->str);
02069    dest->code = src->code;
02070 }
02071 
02072 void ast_party_redirecting_reason_set_init(struct ast_party_redirecting_reason *init, const struct ast_party_redirecting_reason *guide)
02073 {
02074    init->str = NULL;
02075    init->code = guide->code;
02076 }
02077 
02078 void ast_party_redirecting_reason_set(struct ast_party_redirecting_reason *dest, const struct ast_party_redirecting_reason *src)
02079 {
02080    if (dest == src) {
02081       return;
02082    }
02083 
02084    if (src->str && src->str != dest->str) {
02085       ast_free(dest->str);
02086       dest->str = ast_strdup(src->str);
02087    }
02088 
02089    dest->code = src->code;
02090 }
02091 
02092 void ast_party_redirecting_reason_free(struct ast_party_redirecting_reason *doomed)
02093 {
02094    ast_free(doomed->str);
02095 }
02096 
02097 
02098 void ast_party_redirecting_init(struct ast_party_redirecting *init)
02099 {
02100    ast_party_id_init(&init->orig);
02101    ast_party_id_init(&init->from);
02102    ast_party_id_init(&init->to);
02103    ast_party_id_init(&init->priv_orig);
02104    ast_party_id_init(&init->priv_from);
02105    ast_party_id_init(&init->priv_to);
02106    ast_party_redirecting_reason_init(&init->reason);
02107    ast_party_redirecting_reason_init(&init->orig_reason);
02108    init->count = 0;
02109 }
02110 
02111 void ast_party_redirecting_copy(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src)
02112 {
02113    if (dest == src) {
02114       /* Don't copy to self */
02115       return;
02116    }
02117 
02118    ast_party_id_copy(&dest->orig, &src->orig);
02119    ast_party_id_copy(&dest->from, &src->from);
02120    ast_party_id_copy(&dest->to, &src->to);
02121    ast_party_id_copy(&dest->priv_orig, &src->priv_orig);
02122    ast_party_id_copy(&dest->priv_from, &src->priv_from);
02123    ast_party_id_copy(&dest->priv_to, &src->priv_to);
02124    ast_party_redirecting_reason_copy(&dest->reason, &src->reason);
02125    ast_party_redirecting_reason_copy(&dest->orig_reason, &src->orig_reason);
02126    dest->count = src->count;
02127 }
02128 
02129 void ast_party_redirecting_set_init(struct ast_party_redirecting *init, const struct ast_party_redirecting *guide)
02130 {
02131    ast_party_id_set_init(&init->orig, &guide->orig);
02132    ast_party_id_set_init(&init->from, &guide->from);
02133    ast_party_id_set_init(&init->to, &guide->to);
02134    ast_party_id_set_init(&init->priv_orig, &guide->priv_orig);
02135    ast_party_id_set_init(&init->priv_from, &guide->priv_from);
02136    ast_party_id_set_init(&init->priv_to, &guide->priv_to);
02137    ast_party_redirecting_reason_set_init(&init->reason, &guide->reason);
02138    ast_party_redirecting_reason_set_init(&init->orig_reason, &guide->orig_reason);
02139    init->count = guide->count;
02140 }
02141 
02142 void ast_party_redirecting_set(struct ast_party_redirecting *dest, const struct ast_party_redirecting *src, const struct ast_set_party_redirecting *update)
02143 {
02144    ast_party_id_set(&dest->orig, &src->orig, update ? &update->orig : NULL);
02145    ast_party_id_set(&dest->from, &src->from, update ? &update->from : NULL);
02146    ast_party_id_set(&dest->to, &src->to, update ? &update->to : NULL);
02147    ast_party_id_set(&dest->priv_orig, &src->priv_orig, update ? &update->priv_orig : NULL);
02148    ast_party_id_set(&dest->priv_from, &src->priv_from, update ? &update->priv_from : NULL);
02149    ast_party_id_set(&dest->priv_to, &src->priv_to, update ? &update->priv_to : NULL);
02150    ast_party_redirecting_reason_set(&dest->reason, &src->reason);
02151    ast_party_redirecting_reason_set(&dest->orig_reason, &src->orig_reason);
02152    dest->count = src->count;
02153 }
02154 
02155 void ast_party_redirecting_free(struct ast_party_redirecting *doomed)
02156 {
02157    ast_party_id_free(&doomed->orig);
02158    ast_party_id_free(&doomed->from);
02159    ast_party_id_free(&doomed->to);
02160    ast_party_id_free(&doomed->priv_orig);
02161    ast_party_id_free(&doomed->priv_from);
02162    ast_party_id_free(&doomed->priv_to);
02163    ast_party_redirecting_reason_free(&doomed->reason);
02164    ast_party_redirecting_reason_free(&doomed->orig_reason);
02165 }
02166 
02167 /*! \brief Free a channel structure */
02168 static void ast_channel_destructor(void *obj)
02169 {
02170    struct ast_channel *chan = obj;
02171 #ifdef HAVE_EPOLL
02172    int i;
02173 #endif
02174    struct ast_var_t *vardata;
02175    struct ast_frame *f;
02176    struct varshead *headp;
02177    struct ast_datastore *datastore;
02178    char device_name[AST_CHANNEL_NAME];
02179    ast_callid callid;
02180 
02181    /* Stop monitoring */
02182    if (ast_channel_monitor(chan)) {
02183       ast_channel_monitor(chan)->stop(chan, 0);
02184    }
02185 
02186    /* If there is native format music-on-hold state, free it */
02187    if (ast_channel_music_state(chan)) {
02188       ast_moh_cleanup(chan);
02189    }
02190 
02191    ast_pbx_hangup_handler_destroy(chan);
02192 
02193    /* Things that may possibly raise Stasis messages shouldn't occur after this point */
02194    ast_set_flag(ast_channel_flags(chan), AST_FLAG_DEAD);
02195 
02196    if (ast_channel_internal_is_finalized(chan)) {
02197       /* A channel snapshot should not be in the process of being staged now. */
02198       ast_assert(!ast_test_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE));
02199 
02200       ast_channel_lock(chan);
02201       ast_channel_publish_snapshot(chan);
02202       ast_channel_unlock(chan);
02203       publish_cache_clear(chan);
02204    }
02205 
02206    ast_channel_lock(chan);
02207 
02208    /* Get rid of each of the data stores on the channel */
02209    while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry)))
02210       /* Free the data store */
02211       ast_datastore_free(datastore);
02212 
02213    /* While the channel is locked, take the reference to its callid while we tear down the call. */
02214    callid = ast_channel_callid(chan);
02215    ast_channel_callid_cleanup(chan);
02216 
02217    ast_channel_unlock(chan);
02218 
02219    /* Lock and unlock the channel just to be sure nobody has it locked still
02220       due to a reference that was stored in a datastore. (i.e. app_chanspy) */
02221    ast_channel_lock(chan);
02222    ast_channel_unlock(chan);
02223 
02224    if (ast_channel_tech_pvt(chan)) {
02225       ast_log_callid(LOG_WARNING, callid, "Channel '%s' may not have been hung up properly\n", ast_channel_name(chan));
02226       ast_free(ast_channel_tech_pvt(chan));
02227    }
02228 
02229    if (ast_channel_sched(chan)) {
02230       ast_sched_context_destroy(ast_channel_sched(chan));
02231    }
02232 
02233    if (ast_channel_internal_is_finalized(chan)) {
02234       char *dashptr;
02235 
02236       ast_copy_string(device_name, ast_channel_name(chan), sizeof(device_name));
02237       if ((dashptr = strrchr(device_name, '-'))) {
02238          *dashptr = '\0';
02239       }
02240    } else {
02241       device_name[0] = '\0';
02242    }
02243 
02244    /* Free translators */
02245    if (ast_channel_readtrans(chan))
02246       ast_translator_free_path(ast_channel_readtrans(chan));
02247    if (ast_channel_writetrans(chan))
02248       ast_translator_free_path(ast_channel_writetrans(chan));
02249    if (ast_channel_pbx(chan))
02250       ast_log_callid(LOG_WARNING, callid, "PBX may not have been terminated properly on '%s'\n", ast_channel_name(chan));
02251 
02252    /* Free formats */
02253    ast_channel_set_oldwriteformat(chan, NULL);
02254    ast_channel_set_rawreadformat(chan, NULL);
02255    ast_channel_set_rawwriteformat(chan, NULL);
02256    ast_channel_set_readformat(chan, NULL);
02257    ast_channel_set_writeformat(chan, NULL);
02258 
02259    ast_party_dialed_free(ast_channel_dialed(chan));
02260    ast_party_caller_free(ast_channel_caller(chan));
02261    ast_party_connected_line_free(ast_channel_connected(chan));
02262    ast_party_connected_line_free(ast_channel_connected_indicated(chan));
02263    ast_party_redirecting_free(ast_channel_redirecting(chan));
02264 
02265    /* Close pipes if appropriate */
02266    ast_channel_internal_alertpipe_close(chan);
02267    if (ast_channel_timer(chan)) {
02268       ast_timer_close(ast_channel_timer(chan));
02269       ast_channel_timer_set(chan, NULL);
02270    }
02271 #ifdef HAVE_EPOLL
02272    for (i = 0; i < AST_MAX_FDS; i++) {
02273       if (ast_channel_internal_epfd_data(chan, i)) {
02274          ast_free(ast_channel_internal_epfd_data(chan, i));
02275       }
02276    }
02277    close(ast_channel_epfd(chan));
02278 #endif
02279    while ((f = AST_LIST_REMOVE_HEAD(ast_channel_readq(chan), frame_list)))
02280       ast_frfree(f);
02281 
02282    /* loop over the variables list, freeing all data and deleting list items */
02283    /* no need to lock the list, as the channel is already locked */
02284    headp = ast_channel_varshead(chan);
02285    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02286       ast_var_delete(vardata);
02287 
02288    ast_app_group_discard(chan);
02289 
02290    /* Destroy the jitterbuffer */
02291    ast_jb_destroy(chan);
02292 
02293    if (ast_channel_cdr(chan)) {
02294       ast_cdr_free(ast_channel_cdr(chan));
02295       ast_channel_cdr_set(chan, NULL);
02296    }
02297 
02298    if (ast_channel_zone(chan)) {
02299       ast_channel_zone_set(chan, ast_tone_zone_unref(ast_channel_zone(chan)));
02300    }
02301 
02302    ast_channel_internal_cleanup(chan);
02303 
02304    if (device_name[0]) {
02305       /*
02306        * We have a device name to notify of a new state.
02307        *
02308        * Queue an unknown state, because, while we know that this particular
02309        * instance is dead, we don't know the state of all other possible
02310        * instances.
02311        */
02312       ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE), device_name);
02313    }
02314 
02315    ast_channel_nativeformats_set(chan, NULL);
02316 
02317    ast_channel_named_callgroups_set(chan, NULL);
02318    ast_channel_named_pickupgroups_set(chan, NULL);
02319 
02320    ast_atomic_fetchadd_int(&chancount, -1);
02321 }
02322 
02323 /*! \brief Free a dummy channel structure */
02324 static void ast_dummy_channel_destructor(void *obj)
02325 {
02326    struct ast_channel *chan = obj;
02327    struct ast_datastore *datastore;
02328    struct ast_var_t *vardata;
02329    struct varshead *headp;
02330 
02331    ast_pbx_hangup_handler_destroy(chan);
02332 
02333    /* Get rid of each of the data stores on the channel */
02334    while ((datastore = AST_LIST_REMOVE_HEAD(ast_channel_datastores(chan), entry))) {
02335       /* Free the data store */
02336       ast_datastore_free(datastore);
02337    }
02338 
02339    ast_party_dialed_free(ast_channel_dialed(chan));
02340    ast_party_caller_free(ast_channel_caller(chan));
02341    ast_party_connected_line_free(ast_channel_connected(chan));
02342    ast_party_connected_line_free(ast_channel_connected_indicated(chan));
02343    ast_party_redirecting_free(ast_channel_redirecting(chan));
02344 
02345    /* loop over the variables list, freeing all data and deleting list items */
02346    /* no need to lock the list, as the channel is already locked */
02347    headp = ast_channel_varshead(chan);
02348    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
02349       ast_var_delete(vardata);
02350 
02351    if (ast_channel_cdr(chan)) {
02352       ast_cdr_free(ast_channel_cdr(chan));
02353       ast_channel_cdr_set(chan, NULL);
02354    }
02355 
02356    ast_channel_internal_cleanup(chan);
02357 }
02358 
02359 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
02360 {
02361    return ast_datastore_alloc(info, uid);
02362 }
02363 
02364 int ast_channel_datastore_free(struct ast_datastore *datastore)
02365 {
02366    return ast_datastore_free(datastore);
02367 }
02368 
02369 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
02370 {
02371    struct ast_datastore *datastore = NULL, *datastore2;
02372 
02373    AST_LIST_TRAVERSE(ast_channel_datastores(from), datastore, entry) {
02374       if (datastore->inheritance > 0) {
02375          datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
02376          if (datastore2) {
02377             datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
02378             datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
02379             AST_LIST_INSERT_TAIL(ast_channel_datastores(to), datastore2, entry);
02380          }
02381       }
02382    }
02383    return 0;
02384 }
02385 
02386 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
02387 {
02388    int res = 0;
02389 
02390    AST_LIST_INSERT_HEAD(ast_channel_datastores(chan), datastore, entry);
02391 
02392    return res;
02393 }
02394 
02395 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
02396 {
02397    return AST_LIST_REMOVE(ast_channel_datastores(chan), datastore, entry) ? 0 : -1;
02398 }
02399 
02400 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
02401 {
02402    struct ast_datastore *datastore = NULL;
02403 
02404    if (info == NULL)
02405       return NULL;
02406 
02407    AST_LIST_TRAVERSE(ast_channel_datastores(chan), datastore, entry) {
02408       if (datastore->info != info) {
02409          continue;
02410       }
02411 
02412       if (uid == NULL) {
02413          /* matched by type only */
02414          break;
02415       }
02416 
02417       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
02418          /* Matched by type AND uid */
02419          break;
02420       }
02421    }
02422 
02423    return datastore;
02424 }
02425 
02426 /*! Set the file descriptor on the channel */
02427 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
02428 {
02429 #ifdef HAVE_EPOLL
02430    struct epoll_event ev;
02431    struct ast_epoll_data *aed = NULL;
02432 
02433    if (ast_channel_fd_isset(chan, which)) {
02434       epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_DEL, ast_channel_fd(chan, which), &ev);
02435       aed = ast_channel_internal_epfd_data(chan, which);
02436    }
02437 
02438    /* If this new fd is valid, add it to the epoll */
02439    if (fd > -1) {
02440       if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
02441          return;
02442 
02443       ast_channel_internal_epfd_data_set(chan, which, aed);
02444       aed->chan = chan;
02445       aed->which = which;
02446 
02447       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02448       ev.data.ptr = aed;
02449       epoll_ctl(ast_channel_epfd(chan), EPOLL_CTL_ADD, fd, &ev);
02450    } else if (aed) {
02451       /* We don't have to keep around this epoll data structure now */
02452       ast_free(aed);
02453       ast_channel_epfd_data_set(chan, which, NULL);
02454    }
02455 #endif
02456    ast_channel_internal_fd_set(chan, which, fd);
02457    return;
02458 }
02459 
02460 /*! Add a channel to an optimized waitfor */
02461 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
02462 {
02463 #ifdef HAVE_EPOLL
02464    struct epoll_event ev;
02465    int i = 0;
02466 
02467    if (ast_channel_epfd(chan0) == -1)
02468       return;
02469 
02470    /* Iterate through the file descriptors on chan1, adding them to chan0 */
02471    for (i = 0; i < AST_MAX_FDS; i++) {
02472       if (!ast_channel_fd_isset(chan1, i)) {
02473          continue;
02474       }
02475       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
02476       ev.data.ptr = ast_channel_internal_epfd_data(chan1, i);
02477       epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_ADD, ast_channel_fd(chan1, i), &ev);
02478    }
02479 
02480 #endif
02481    return;
02482 }
02483 
02484 /*! Delete a channel from an optimized waitfor */
02485 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
02486 {
02487 #ifdef HAVE_EPOLL
02488    struct epoll_event ev;
02489    int i = 0;
02490 
02491    if (ast_channel_epfd(chan0) == -1)
02492       return;
02493 
02494    for (i = 0; i < AST_MAX_FDS; i++) {
02495       if (!ast_channel_fd_isset(chan1, i)) {
02496          continue;
02497       }
02498       epoll_ctl(ast_channel_epfd(chan0), EPOLL_CTL_DEL, ast_channel_fd(chan1, i), &ev);
02499    }
02500 
02501 #endif
02502    return;
02503 }
02504 
02505 void ast_channel_clear_softhangup(struct ast_channel *chan, int flag)
02506 {
02507    ast_channel_lock(chan);
02508 
02509    ast_channel_softhangup_internal_flag_clear(chan, flag);
02510 
02511    if (!ast_channel_softhangup_internal_flag(chan)) {
02512       struct ast_frame *fr;
02513 
02514       /* If we have completely cleared the softhangup flag,
02515        * then we need to fully abort the hangup process.  This requires
02516        * pulling the END_OF_Q frame out of the channel frame queue if it
02517        * still happens to be there. */
02518 
02519       fr = AST_LIST_LAST(ast_channel_readq(chan));
02520       if (fr && fr->frametype == AST_FRAME_CONTROL &&
02521             fr->subclass.integer == AST_CONTROL_END_OF_Q) {
02522          AST_LIST_REMOVE(ast_channel_readq(chan), fr, frame_list);
02523          ast_frfree(fr);
02524       }
02525    }
02526 
02527    ast_channel_unlock(chan);
02528 }
02529 
02530 /*! \brief Softly hangup a channel, don't lock */
02531 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
02532 {
02533    ast_debug(1, "Soft-Hanging (%#04x) up channel '%s'\n", (unsigned)cause, ast_channel_name(chan));
02534    /* Inform channel driver that we need to be hung up, if it cares */
02535    ast_channel_softhangup_internal_flag_add(chan, cause);
02536    ast_queue_frame(chan, &ast_null_frame);
02537    /* Interrupt any poll call or such */
02538    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING))
02539       pthread_kill(ast_channel_blocker(chan), SIGURG);
02540    return 0;
02541 }
02542 
02543 /*! \brief Softly hangup a channel, lock */
02544 int ast_softhangup(struct ast_channel *chan, int cause)
02545 {
02546    RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
02547    int res;
02548 
02549    ast_channel_lock(chan);
02550    res = ast_softhangup_nolock(chan, cause);
02551    blob = ast_json_pack("{s: i, s: b}",
02552               "cause", cause,
02553               "soft", 1);
02554    ast_channel_publish_blob(chan, ast_channel_hangup_request_type(), blob);
02555    ast_channel_unlock(chan);
02556 
02557    return res;
02558 }
02559 
02560 static void free_translation(struct ast_channel *clonechan)
02561 {
02562    if (ast_channel_writetrans(clonechan)) {
02563       ast_translator_free_path(ast_channel_writetrans(clonechan));
02564    }
02565    if (ast_channel_readtrans(clonechan)) {
02566       ast_translator_free_path(ast_channel_readtrans(clonechan));
02567    }
02568    ast_channel_writetrans_set(clonechan, NULL);
02569    ast_channel_readtrans_set(clonechan, NULL);
02570 }
02571 
02572 void ast_set_hangupsource(struct ast_channel *chan, const char *source, int force)
02573 {
02574    RAII_VAR(struct ast_channel *, bridge, ast_channel_bridge_peer(chan), ast_channel_cleanup);
02575 
02576    ast_channel_lock(chan);
02577    if (force || ast_strlen_zero(ast_channel_hangupsource(chan))) {
02578       ast_channel_hangupsource_set(chan, source);
02579    }
02580    ast_channel_unlock(chan);
02581 
02582    if (bridge) {
02583       ast_channel_lock(bridge);
02584       if (force || ast_strlen_zero(ast_channel_hangupsource(bridge))) {
02585          ast_channel_hangupsource_set(bridge, source);
02586       }
02587       ast_channel_unlock(bridge);
02588    }
02589 }
02590 
02591 int ast_channel_has_audio_frame_or_monitor(struct ast_channel *chan)
02592 {
02593    return ast_channel_monitor(chan)
02594       || !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
02595       || !ast_framehook_list_contains_no_active(ast_channel_framehooks(chan));
02596 }
02597 
02598 int ast_channel_has_hook_requiring_audio(struct ast_channel *chan)
02599 {
02600    return ast_channel_monitor(chan)
02601       || !ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))
02602       || !ast_framehook_list_contains_no_active_of_type(ast_channel_framehooks(chan), AST_FRAME_VOICE);
02603 }
02604 
02605 static void destroy_hooks(struct ast_channel *chan)
02606 {
02607    if (ast_channel_audiohooks(chan)) {
02608       ast_audiohook_detach_list(ast_channel_audiohooks(chan));
02609       ast_channel_audiohooks_set(chan, NULL);
02610    }
02611 
02612    ast_framehook_list_destroy(chan);
02613 }
02614 
02615 /*! \brief Hangup a channel */
02616 void ast_hangup(struct ast_channel *chan)
02617 {
02618    /* Be NULL safe for RAII_VAR() usage. */
02619    if (!chan) {
02620       return;
02621    }
02622 
02623    ast_autoservice_stop(chan);
02624 
02625    ast_channel_lock(chan);
02626 
02627    while (ast_channel_masq(chan) || ast_channel_masqr(chan))  {
02628       CHANNEL_DEADLOCK_AVOIDANCE(chan);
02629    }
02630 
02631    /* Mark as a zombie so a masquerade cannot be setup on this channel. */
02632    ast_set_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE);
02633 
02634    ast_channel_unlock(chan);
02635 
02636    /*
02637     * XXX if running the hangup handlers here causes problems
02638     * because the handlers take too long to execute, we could move
02639     * the meat of this function into another thread.  A thread
02640     * where channels go to die.
02641     *
02642     * If this is done, ast_autoservice_chan_hangup_peer() will no
02643     * longer be needed.
02644     */
02645    ast_pbx_hangup_handler_run(chan);
02646    ao2_unlink(channels, chan);
02647    ast_channel_lock(chan);
02648 
02649    destroy_hooks(chan);
02650 
02651    free_translation(chan);
02652    /* Close audio stream */
02653    if (ast_channel_stream(chan)) {
02654       ast_closestream(ast_channel_stream(chan));
02655       ast_channel_stream_set(chan, NULL);
02656    }
02657    /* Close video stream */
02658    if (ast_channel_vstream(chan)) {
02659       ast_closestream(ast_channel_vstream(chan));
02660       ast_channel_vstream_set(chan, NULL);
02661    }
02662    if (ast_channel_sched(chan)) {
02663       ast_sched_context_destroy(ast_channel_sched(chan));
02664       ast_channel_sched_set(chan, NULL);
02665    }
02666 
02667    if (ast_channel_generatordata(chan)) { /* Clear any tone stuff remaining */
02668       if (ast_channel_generator(chan) && ast_channel_generator(chan)->release) {
02669          ast_channel_generator(chan)->release(chan, ast_channel_generatordata(chan));
02670       }
02671    }
02672    ast_channel_generatordata_set(chan, NULL);
02673    ast_channel_generator_set(chan, NULL);
02674 
02675    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING)) {
02676       ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
02677          "is blocked by thread %ld in procedure %s!  Expect a failure\n",
02678          (long) pthread_self(), ast_channel_name(chan), (long)ast_channel_blocker(chan), ast_channel_blockproc(chan));
02679       ast_assert(ast_test_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING) == 0);
02680    }
02681 
02682    ast_debug(1, "Hanging up channel '%s'\n", ast_channel_name(chan));
02683    if (ast_channel_tech(chan)->hangup) {
02684       ast_channel_tech(chan)->hangup(chan);
02685    }
02686 
02687    ast_channel_unlock(chan);
02688 
02689    ast_cc_offer(chan);
02690 
02691    ast_channel_unref(chan);
02692 }
02693 
02694 int ast_raw_answer(struct ast_channel *chan)
02695 {
02696    int res = 0;
02697    struct timeval answertime;
02698 
02699    ast_channel_lock(chan);
02700 
02701    /* You can't answer an outbound call */
02702    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
02703       ast_channel_unlock(chan);
02704       return 0;
02705    }
02706 
02707    /* Stop if we're a zombie or need a soft hangup */
02708    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
02709       ast_channel_unlock(chan);
02710       return -1;
02711    }
02712 
02713    answertime = ast_tvnow();
02714    ast_channel_answertime_set(chan, &answertime);
02715 
02716    ast_channel_unlock(chan);
02717 
02718    switch (ast_channel_state(chan)) {
02719    case AST_STATE_RINGING:
02720    case AST_STATE_RING:
02721       ast_channel_lock(chan);
02722       if (ast_channel_tech(chan)->answer) {
02723          res = ast_channel_tech(chan)->answer(chan);
02724       }
02725       ast_setstate(chan, AST_STATE_UP);
02726       ast_channel_unlock(chan);
02727       break;
02728    case AST_STATE_UP:
02729       break;
02730    default:
02731       break;
02732    }
02733 
02734    ast_indicate(chan, -1);
02735 
02736    return res;
02737 }
02738 
02739 int __ast_answer(struct ast_channel *chan, unsigned int delay)
02740 {
02741    int res = 0;
02742    enum ast_channel_state old_state;
02743 
02744    old_state = ast_channel_state(chan);
02745    if ((res = ast_raw_answer(chan))) {
02746       return res;
02747    }
02748 
02749    switch (old_state) {
02750    case AST_STATE_RINGING:
02751    case AST_STATE_RING:
02752       /* wait for media to start flowing, but don't wait any longer
02753        * than 'delay' or 500 milliseconds, whichever is longer
02754        */
02755       do {
02756          AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
02757          struct ast_frame *cur;
02758          struct ast_frame *new_frame;
02759          int timeout_ms = MAX(delay, 500);
02760          unsigned int done = 0;
02761          struct timeval start;
02762 
02763          AST_LIST_HEAD_INIT_NOLOCK(&frames);
02764 
02765          start = ast_tvnow();
02766          for (;;) {
02767             int ms = ast_remaining_ms(start, timeout_ms);
02768             ms = ast_waitfor(chan, ms);
02769             if (ms < 0) {
02770                ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", ast_channel_name(chan), strerror(errno));
02771                res = -1;
02772                break;
02773             }
02774             if (ms == 0) {
02775                ast_debug(2, "Didn't receive a media frame from %s within %u ms of answering. Continuing anyway\n", ast_channel_name(chan), MAX(delay, 500));
02776                break;
02777             }
02778             cur = ast_read(chan);
02779             if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
02780                     (cur->subclass.integer == AST_CONTROL_HANGUP))) {
02781                if (cur) {
02782                   ast_frfree(cur);
02783                }
02784                res = -1;
02785                ast_debug(2, "Hangup of channel %s detected in answer routine\n", ast_channel_name(chan));
02786                break;
02787             }
02788 
02789             if ((new_frame = ast_frisolate(cur)) != cur) {
02790                ast_frfree(cur);
02791             }
02792 
02793             AST_LIST_INSERT_HEAD(&frames, new_frame, frame_list);
02794 
02795             /* if a specific delay period was requested, continue
02796              * until that delay has passed. don't stop just because
02797              * incoming media has arrived.
02798              */
02799             if (delay) {
02800                continue;
02801             }
02802 
02803             switch (new_frame->frametype) {
02804                /* all of these frametypes qualify as 'media' */
02805             case AST_FRAME_VOICE:
02806             case AST_FRAME_VIDEO:
02807             case AST_FRAME_TEXT:
02808             case AST_FRAME_DTMF_BEGIN:
02809             case AST_FRAME_DTMF_END:
02810             case AST_FRAME_IMAGE:
02811             case AST_FRAME_HTML:
02812             case AST_FRAME_MODEM:
02813                done = 1;
02814                break;
02815             case AST_FRAME_CONTROL:
02816             case AST_FRAME_IAX:
02817             case AST_FRAME_BRIDGE_ACTION:
02818             case AST_FRAME_BRIDGE_ACTION_SYNC:
02819             case AST_FRAME_NULL:
02820             case AST_FRAME_CNG:
02821                break;
02822             }
02823 
02824             if (done) {
02825                break;
02826             }
02827          }
02828 
02829          ast_channel_lock(chan);
02830          while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
02831             if (res == 0) {
02832                ast_queue_frame_head(chan, cur);
02833             }
02834             ast_frfree(cur);
02835          }
02836          ast_channel_unlock(chan);
02837       } while (0);
02838       break;
02839    default:
02840       break;
02841    }
02842 
02843    return res;
02844 }
02845 
02846 int ast_answer(struct ast_channel *chan)
02847 {
02848    return __ast_answer(chan, 0);
02849 }
02850 
02851 inline int ast_auto_answer(struct ast_channel *chan)
02852 {
02853    if (ast_channel_state(chan) == AST_STATE_UP) {
02854       /* Already answered */
02855       return 0;
02856    }
02857    return ast_answer(chan);
02858 }
02859 
02860 int ast_channel_get_duration(struct ast_channel *chan)
02861 {
02862    ast_assert(NULL != chan);
02863 
02864    if (ast_tvzero(ast_channel_creationtime(chan))) {
02865       return 0;
02866    }
02867    return (ast_tvdiff_ms(ast_tvnow(), ast_channel_creationtime(chan)) / 1000);
02868 }
02869 
02870 int ast_channel_get_up_time(struct ast_channel *chan)
02871 {
02872    ast_assert(NULL != chan);
02873 
02874    if (ast_tvzero(ast_channel_answertime(chan))) {
02875       return 0;
02876    }
02877    return (ast_tvdiff_ms(ast_tvnow(), ast_channel_answertime(chan)) / 1000);
02878 }
02879 
02880 static void deactivate_generator_nolock(struct ast_channel *chan)
02881 {
02882    if (ast_channel_generatordata(chan)) {
02883       struct ast_generator *generator = ast_channel_generator(chan);
02884 
02885       if (generator && generator->release) {
02886          generator->release(chan, ast_channel_generatordata(chan));
02887       }
02888       ast_channel_generatordata_set(chan, NULL);
02889       ast_channel_generator_set(chan, NULL);
02890       ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
02891       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT);
02892       ast_settimeout(chan, 0, NULL, NULL);
02893    }
02894 }
02895 
02896 void ast_deactivate_generator(struct ast_channel *chan)
02897 {
02898    ast_channel_lock(chan);
02899    deactivate_generator_nolock(chan);
02900    ast_channel_unlock(chan);
02901 }
02902 
02903 static void generator_write_format_change(struct ast_channel *chan)
02904 {
02905    struct ast_generator *generator;
02906 
02907    ast_channel_lock(chan);
02908    generator = ast_channel_generator(chan);
02909    if (generator && generator->write_format_change) {
02910       generator->write_format_change(chan, ast_channel_generatordata(chan));
02911    }
02912    ast_channel_unlock(chan);
02913 }
02914 
02915 static int generator_force(const void *data)
02916 {
02917    /* Called if generator doesn't have data */
02918    void *tmp;
02919    int res;
02920    int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
02921    struct ast_channel *chan = (struct ast_channel *)data;
02922 
02923    ast_channel_lock(chan);
02924    tmp = ast_channel_generatordata(chan);
02925    ast_channel_generatordata_set(chan, NULL);
02926    if (ast_channel_generator(chan))
02927       generate = ast_channel_generator(chan)->generate;
02928    ast_channel_unlock(chan);
02929 
02930    if (!tmp || !generate) {
02931       return 0;
02932    }
02933 
02934    res = generate(chan, tmp, 0, ast_format_get_sample_rate(ast_channel_writeformat(chan)) / 50);
02935 
02936    ast_channel_lock(chan);
02937    if (ast_channel_generator(chan) && generate == ast_channel_generator(chan)->generate) {
02938       ast_channel_generatordata_set(chan, tmp);
02939    }
02940    ast_channel_unlock(chan);
02941 
02942    if (res) {
02943       ast_debug(1, "Auto-deactivating generator\n");
02944       ast_deactivate_generator(chan);
02945    }
02946 
02947    return 0;
02948 }
02949 
02950 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
02951 {
02952    int res = 0;
02953    void *generatordata = NULL;
02954 
02955    ast_channel_lock(chan);
02956    if (ast_channel_generatordata(chan)) {
02957       struct ast_generator *generator_old = ast_channel_generator(chan);
02958 
02959       if (generator_old && generator_old->release) {
02960          generator_old->release(chan, ast_channel_generatordata(chan));
02961       }
02962    }
02963    if (gen->alloc && !(generatordata = gen->alloc(chan, params))) {
02964       res = -1;
02965    }
02966    ast_channel_generatordata_set(chan, generatordata);
02967    if (!res) {
02968       ast_settimeout(chan, 50, generator_force, chan);
02969       ast_channel_generator_set(chan, gen);
02970    }
02971    ast_channel_unlock(chan);
02972 
02973    ast_prod(chan);
02974 
02975    return res;
02976 }
02977 
02978 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02979 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
02980 {
02981    int winner = -1;
02982    ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
02983    return winner;
02984 }
02985 
02986 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02987 #ifdef HAVE_EPOLL
02988 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
02989                int *exception, int *outfd, int *ms)
02990 #else
02991 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
02992                int *exception, int *outfd, int *ms)
02993 #endif
02994 {
02995    struct timeval start = { 0 , 0 };
02996    struct pollfd *pfds = NULL;
02997    int res;
02998    long rms;
02999    int x, y, max;
03000    int sz;
03001    struct timeval now = { 0, 0 };
03002    struct timeval whentohangup = { 0, 0 }, diff;
03003    struct ast_channel *winner = NULL;
03004    struct fdmap {
03005       int chan;
03006       int fdno;
03007    } *fdmap = NULL;
03008 
03009    if (outfd) {
03010       *outfd = -99999;
03011    }
03012    if (exception) {
03013       *exception = 0;
03014    }
03015 
03016    if ((sz = n * AST_MAX_FDS + nfds)) {
03017       pfds = ast_alloca(sizeof(*pfds) * sz);
03018       fdmap = ast_alloca(sizeof(*fdmap) * sz);
03019    } else {
03020       /* nothing to allocate and no FDs to check */
03021       return NULL;
03022    }
03023 
03024    for (x = 0; x < n; x++) {
03025       ast_channel_lock(c[x]);
03026       if (!ast_tvzero(*ast_channel_whentohangup(c[x]))) {
03027          if (ast_tvzero(whentohangup))
03028             now = ast_tvnow();
03029          diff = ast_tvsub(*ast_channel_whentohangup(c[x]), now);
03030          if (diff.tv_sec < 0 || ast_tvzero(diff)) {
03031             ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
03032             /* Should already be hungup */
03033             ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
03034             ast_channel_unlock(c[x]);
03035             return c[x];
03036          }
03037          if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
03038             whentohangup = diff;
03039       }
03040       ast_channel_unlock(c[x]);
03041    }
03042    /* Wait full interval */
03043    rms = *ms;
03044    /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
03045    if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
03046       rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
03047       if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
03048          rms =  *ms;
03049       }
03050    } else if (!ast_tvzero(whentohangup) && rms < 0) {
03051       /* Tiny corner case... call would need to last >24 days */
03052       rms = INT_MAX;
03053    }
03054    /*
03055     * Build the pollfd array, putting the channels' fds first,
03056     * followed by individual fds. Order is important because
03057     * individual fd's must have priority over channel fds.
03058     */
03059    max = 0;
03060    for (x = 0; x < n; x++) {
03061       for (y = 0; y < AST_MAX_FDS; y++) {
03062          fdmap[max].fdno = y;  /* fd y is linked to this pfds */
03063          fdmap[max].chan = x;  /* channel x is linked to this pfds */
03064          max += ast_add_fd(&pfds[max], ast_channel_fd(c[x], y));
03065       }
03066       CHECK_BLOCKING(c[x]);
03067    }
03068    /* Add the individual fds */
03069    for (x = 0; x < nfds; x++) {
03070       fdmap[max].chan = -1;
03071       max += ast_add_fd(&pfds[max], fds[x]);
03072    }
03073 
03074    if (*ms > 0) {
03075       start = ast_tvnow();
03076    }
03077 
03078    if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
03079       do {
03080          int kbrms = rms;
03081          if (kbrms > 600000) {
03082             kbrms = 600000;
03083          }
03084          res = ast_poll(pfds, max, kbrms);
03085          if (!res) {
03086             rms -= kbrms;
03087          }
03088       } while (!res && (rms > 0));
03089    } else {
03090       res = ast_poll(pfds, max, rms);
03091    }
03092    for (x = 0; x < n; x++) {
03093       ast_clear_flag(ast_channel_flags(c[x]), AST_FLAG_BLOCKING);
03094    }
03095    if (res < 0) { /* Simulate a timeout if we were interrupted */
03096       if (errno != EINTR) {
03097          *ms = -1;
03098       }
03099       return NULL;
03100    }
03101    if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
03102       now = ast_tvnow();
03103       for (x = 0; x < n; x++) {
03104          if (!ast_tvzero(*ast_channel_whentohangup(c[x])) && ast_tvcmp(*ast_channel_whentohangup(c[x]), now) <= 0) {
03105             ast_test_suite_event_notify("HANGUP_TIME", "Channel: %s", ast_channel_name(c[x]));
03106             ast_channel_softhangup_internal_flag_add(c[x], AST_SOFTHANGUP_TIMEOUT);
03107             if (winner == NULL) {
03108                winner = c[x];
03109             }
03110          }
03111       }
03112    }
03113    if (res == 0) { /* no fd ready, reset timeout and done */
03114       *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
03115       return winner;
03116    }
03117    /*
03118     * Then check if any channel or fd has a pending event.
03119     * Remember to check channels first and fds last, as they
03120     * must have priority on setting 'winner'
03121     */
03122    for (x = 0; x < max; x++) {
03123       res = pfds[x].revents;
03124       if (res == 0) {
03125          continue;
03126       }
03127       if (fdmap[x].chan >= 0) {  /* this is a channel */
03128          winner = c[fdmap[x].chan]; /* override previous winners */
03129          if (res & POLLPRI) {
03130             ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
03131          } else {
03132             ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
03133          }
03134          ast_channel_fdno_set(winner, fdmap[x].fdno);
03135       } else {       /* this is an fd */
03136          if (outfd) {
03137             *outfd = pfds[x].fd;
03138          }
03139          if (exception) {
03140             *exception = (res & POLLPRI) ? -1 : 0;
03141          }
03142          winner = NULL;
03143       }
03144    }
03145    if (*ms > 0) {
03146       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03147       if (*ms < 0) {
03148          *ms = 0;
03149       }
03150    }
03151    return winner;
03152 }
03153 
03154 #ifdef HAVE_EPOLL
03155 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
03156 {
03157    struct timeval start = { 0 , 0 };
03158    int res = 0;
03159    struct epoll_event ev[1];
03160    long diff, rms = *ms;
03161    struct ast_channel *winner = NULL;
03162    struct ast_epoll_data *aed = NULL;
03163 
03164    ast_channel_lock(chan);
03165    /* Figure out their timeout */
03166    if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
03167       if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(chan), ast_tvnow())) < 0) {
03168          /* They should already be hungup! */
03169          ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
03170          ast_channel_unlock(chan);
03171          return NULL;
03172       }
03173       /* If this value is smaller then the current one... make it priority */
03174       if (rms > diff) {
03175          rms = diff;
03176       }
03177    }
03178 
03179    ast_channel_unlock(chan);
03180 
03181    /* Time to make this channel block... */
03182    CHECK_BLOCKING(chan);
03183 
03184    if (*ms > 0) {
03185       start = ast_tvnow();
03186    }
03187 
03188    /* We don't have to add any file descriptors... they are already added, we just have to wait! */
03189    res = epoll_wait(ast_channel_epfd(chan), ev, 1, rms);
03190 
03191    /* Stop blocking */
03192    ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
03193 
03194    /* Simulate a timeout if we were interrupted */
03195    if (res < 0) {
03196       if (errno != EINTR) {
03197          *ms = -1;
03198       }
03199       return NULL;
03200    }
03201 
03202    /* If this channel has a timeout see if it expired */
03203    if (!ast_tvzero(*ast_channel_whentohangup(chan))) {
03204       if (ast_tvdiff_ms(ast_tvnow(), *ast_channel_whentohangup(chan)) >= 0) {
03205          ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_TIMEOUT);
03206          winner = chan;
03207       }
03208    }
03209 
03210    /* No fd ready, reset timeout and be done for now */
03211    if (!res) {
03212       *ms = 0;
03213       return winner;
03214    }
03215 
03216    /* See what events are pending */
03217    aed = ev[0].data.ptr;
03218    ast_channel_fdno_set(chan, aed->which);
03219    if (ev[0].events & EPOLLPRI) {
03220       ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
03221    } else {
03222       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
03223    }
03224 
03225    if (*ms > 0) {
03226       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03227       if (*ms < 0) {
03228          *ms = 0;
03229       }
03230    }
03231 
03232    return chan;
03233 }
03234 
03235 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
03236 {
03237    struct timeval start = { 0 , 0 };
03238    int res = 0, i;
03239    struct epoll_event ev[25] = { { 0, } };
03240    struct timeval now = { 0, 0 };
03241    long whentohangup = 0, diff = 0, rms = *ms;
03242    struct ast_channel *winner = NULL;
03243 
03244    for (i = 0; i < n; i++) {
03245       ast_channel_lock(c[i]);
03246       if (!ast_tvzero(*ast_channel_whentohangup(c[i]))) {
03247          if (whentohangup == 0) {
03248             now = ast_tvnow();
03249          }
03250          if ((diff = ast_tvdiff_ms(*ast_channel_whentohangup(c[i]), now)) < 0) {
03251             ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
03252             ast_channel_unlock(c[i]);
03253             return c[i];
03254          }
03255          if (!whentohangup || whentohangup > diff) {
03256             whentohangup = diff;
03257          }
03258       }
03259       ast_channel_unlock(c[i]);
03260       CHECK_BLOCKING(c[i]);
03261    }
03262 
03263    rms = *ms;
03264    if (whentohangup) {
03265       rms = whentohangup;
03266       if (*ms >= 0 && *ms < rms) {
03267          rms = *ms;
03268       }
03269    }
03270 
03271    if (*ms > 0) {
03272       start = ast_tvnow();
03273    }
03274 
03275    res = epoll_wait(ast_channel_epfd(c[0]), ev, 25, rms);
03276 
03277    for (i = 0; i < n; i++) {
03278       ast_clear_flag(ast_channel_flags(c[i]), AST_FLAG_BLOCKING);
03279    }
03280 
03281    if (res < 0) {
03282       if (errno != EINTR) {
03283          *ms = -1;
03284       }
03285       return NULL;
03286    }
03287 
03288    if (whentohangup) {
03289       now = ast_tvnow();
03290       for (i = 0; i < n; i++) {
03291          if (!ast_tvzero(*ast_channel_whentohangup(c[i])) && ast_tvdiff_ms(now, *ast_channel_whentohangup(c[i])) >= 0) {
03292             ast_channel_softhangup_internal_flag_add(c[i], AST_SOFTHANGUP_TIMEOUT);
03293             if (!winner) {
03294                winner = c[i];
03295             }
03296          }
03297       }
03298    }
03299 
03300    if (!res) {
03301       *ms = 0;
03302       return winner;
03303    }
03304 
03305    for (i = 0; i < res; i++) {
03306       struct ast_epoll_data *aed = ev[i].data.ptr;
03307 
03308       if (!ev[i].events || !aed) {
03309          continue;
03310       }
03311 
03312       winner = aed->chan;
03313       if (ev[i].events & EPOLLPRI) {
03314          ast_set_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
03315       } else {
03316          ast_clear_flag(ast_channel_flags(winner), AST_FLAG_EXCEPTION);
03317       }
03318       ast_channel_fdno_set(winner, aed->which);
03319    }
03320 
03321    if (*ms > 0) {
03322       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
03323       if (*ms < 0) {
03324          *ms = 0;
03325       }
03326    }
03327 
03328    return winner;
03329 }
03330 
03331 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
03332                int *exception, int *outfd, int *ms)
03333 {
03334    /* Clear all provided values in one place. */
03335    if (outfd) {
03336       *outfd = -99999;
03337    }
03338    if (exception) {
03339       *exception = 0;
03340    }
03341 
03342    /* If no epoll file descriptor is available resort to classic nandfds */
03343    if (!n || nfds || ast_channel_epfd(c[0]) == -1) {
03344       return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
03345    } else if (!nfds && n == 1) {
03346       return ast_waitfor_nandfds_simple(c[0], ms);
03347    } else {
03348       return ast_waitfor_nandfds_complex(c, n, ms);
03349    }
03350 }
03351 #endif
03352 
03353 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
03354 {
03355    return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
03356 }
03357 
03358 int ast_waitfor(struct ast_channel *c, int ms)
03359 {
03360    if (ms < 0) {
03361       do {
03362          ms = 100000;
03363          ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
03364       } while (!ms);
03365    } else {
03366       ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
03367    }
03368    return ms;
03369 }
03370 
03371 int ast_waitfordigit(struct ast_channel *c, int ms)
03372 {
03373    return ast_waitfordigit_full(c, ms, -1, -1);
03374 }
03375 
03376 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
03377 {
03378    return ast_settimeout_full(c, rate, func, data, 0);
03379 }
03380 
03381 int ast_settimeout_full(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data, unsigned int is_ao2_obj)
03382 {
03383    int res;
03384    unsigned int real_rate = rate, max_rate;
03385 
03386    ast_channel_lock(c);
03387 
03388    if (ast_channel_timingfd(c) == -1) {
03389       ast_channel_unlock(c);
03390       return -1;
03391    }
03392 
03393    if (!func) {
03394       rate = 0;
03395       data = NULL;
03396    }
03397 
03398    if (rate && rate > (max_rate = ast_timer_get_max_rate(ast_channel_timer(c)))) {
03399       real_rate = max_rate;
03400    }
03401 
03402    ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
03403 
03404    res = ast_timer_set_rate(ast_channel_timer(c), real_rate);
03405 
03406    if (ast_channel_timingdata(c) && ast_test_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ)) {
03407       ao2_ref(ast_channel_timingdata(c), -1);
03408    }
03409 
03410    ast_channel_timingfunc_set(c, func);
03411    ast_channel_timingdata_set(c, data);
03412 
03413    if (data && is_ao2_obj) {
03414       ao2_ref(data, 1);
03415       ast_set_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ);
03416    } else {
03417       ast_clear_flag(ast_channel_flags(c), AST_FLAG_TIMINGDATA_IS_AO2_OBJ);
03418    }
03419 
03420    if (func == NULL && rate == 0 && ast_channel_fdno(c) == AST_TIMING_FD) {
03421       /* Clearing the timing func and setting the rate to 0
03422        * means that we don't want to be reading from the timingfd
03423        * any more. Setting c->fdno to -1 means we won't have any
03424        * errant reads from the timingfd, meaning we won't potentially
03425        * miss any important frames.
03426        */
03427       ast_channel_fdno_set(c, -1);
03428    }
03429 
03430    ast_channel_unlock(c);
03431 
03432    return res;
03433 }
03434 
03435 int ast_waitfordigit_full(struct ast_channel *c, int timeout_ms, int audiofd, int cmdfd)
03436 {
03437    struct timeval start = ast_tvnow();
03438    int ms;
03439 
03440    /* Stop if we're a zombie or need a soft hangup */
03441    if (ast_test_flag(ast_channel_flags(c), AST_FLAG_ZOMBIE) || ast_check_hangup(c))
03442       return -1;
03443 
03444    /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
03445    ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03446 
03447    /* Wait for a digit, no more than timeout_ms milliseconds total.
03448     * Or, wait indefinitely if timeout_ms is <0.
03449     */
03450    while ((ms = ast_remaining_ms(start, timeout_ms))) {
03451       struct ast_channel *rchan;
03452       int outfd = -1;
03453 
03454       errno = 0;
03455       /* While ast_waitfor_nandfds tries to help by reducing the timeout by how much was waited,
03456        * it is unhelpful if it waited less than a millisecond.
03457        */
03458       rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
03459 
03460       if (!rchan && outfd < 0 && ms) {
03461          if (errno == 0 || errno == EINTR)
03462             continue;
03463          ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
03464          ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03465          return -1;
03466       } else if (outfd > -1) {
03467          /* The FD we were watching has something waiting */
03468          ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
03469          ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03470          return 1;
03471       } else if (rchan) {
03472          int res;
03473          struct ast_frame *f = ast_read(c);
03474          if (!f)
03475             return -1;
03476 
03477          switch (f->frametype) {
03478          case AST_FRAME_DTMF_BEGIN:
03479             break;
03480          case AST_FRAME_DTMF_END:
03481             res = f->subclass.integer;
03482             ast_frfree(f);
03483             ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03484             return res;
03485          case AST_FRAME_CONTROL:
03486             switch (f->subclass.integer) {
03487             case AST_CONTROL_HANGUP:
03488                ast_frfree(f);
03489                ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03490                return -1;
03491             case AST_CONTROL_STREAM_STOP:
03492             case AST_CONTROL_STREAM_SUSPEND:
03493             case AST_CONTROL_STREAM_RESTART:
03494             case AST_CONTROL_STREAM_REVERSE:
03495             case AST_CONTROL_STREAM_FORWARD:
03496                /* Fall-through and treat as if it were a DTMF signal. Items
03497                 * that perform stream control will handle this. */
03498                res = f->subclass.integer;
03499                ast_frfree(f);
03500                ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03501                return res;
03502             case AST_CONTROL_PVT_CAUSE_CODE:
03503             case AST_CONTROL_RINGING:
03504             case AST_CONTROL_ANSWER:
03505             case AST_CONTROL_SRCUPDATE:
03506             case AST_CONTROL_SRCCHANGE:
03507             case AST_CONTROL_CONNECTED_LINE:
03508             case AST_CONTROL_REDIRECTING:
03509             case AST_CONTROL_UPDATE_RTP_PEER:
03510             case AST_CONTROL_HOLD:
03511             case AST_CONTROL_UNHOLD:
03512             case -1:
03513                /* Unimportant */
03514                break;
03515             default:
03516                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass.integer);
03517                break;
03518             }
03519             break;
03520          case AST_FRAME_VOICE:
03521             /* Write audio if appropriate */
03522             if (audiofd > -1) {
03523                if (write(audiofd, f->data.ptr, f->datalen) < 0) {
03524                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
03525                }
03526             }
03527          default:
03528             /* Ignore */
03529             break;
03530          }
03531          ast_frfree(f);
03532       }
03533    }
03534 
03535    ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
03536 
03537    return 0; /* Time is up */
03538 }
03539 
03540 enum DtmfDirection {
03541    DTMF_RECEIVED,
03542    DTMF_SENT
03543 };
03544 
03545 static const char *dtmf_direction_to_string(enum DtmfDirection direction)
03546 {
03547    switch (direction) {
03548    case DTMF_RECEIVED:
03549       return "Received";
03550    case DTMF_SENT:
03551       return "Sent";
03552    }
03553 
03554    return "?";
03555 }
03556 
03557 static void send_dtmf_begin_event(struct ast_channel *chan,
03558    enum DtmfDirection direction, const char digit)
03559 {
03560    RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
03561    char digit_str[] = { digit, '\0' };
03562 
03563    blob = ast_json_pack("{ s: s, s: s }",
03564       "digit", digit_str,
03565       "direction", dtmf_direction_to_string(direction));
03566    if (!blob) {
03567       return;
03568    }
03569 
03570    ast_channel_publish_cached_blob(chan, ast_channel_dtmf_begin_type(), blob);
03571 }
03572 
03573 static void send_dtmf_end_event(struct ast_channel *chan,
03574    enum DtmfDirection direction, const char digit, long duration_ms)
03575 {
03576    RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
03577    char digit_str[] = { digit, '\0' };
03578 
03579    blob = ast_json_pack("{ s: s, s: s, s: i }",
03580       "digit", digit_str,
03581       "direction", dtmf_direction_to_string(direction),
03582       "duration_ms", duration_ms);
03583    if (!blob) {
03584       return;
03585    }
03586 
03587    ast_channel_publish_cached_blob(chan, ast_channel_dtmf_end_type(), blob);
03588 }
03589 
03590 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
03591 {
03592    struct ast_generator *generator;
03593    void *gendata;
03594    int res;
03595    int samples;
03596 
03597    generator = ast_channel_generator(chan);
03598    if (!generator
03599       || !generator->generate
03600       || f->frametype != AST_FRAME_VOICE
03601       || !ast_channel_generatordata(chan)
03602       || ast_channel_timingfunc(chan)) {
03603       return;
03604    }
03605 
03606    /*
03607     * We must generate frames in phase locked mode since
03608     * we have no internal timer available.
03609     */
03610    if (ast_format_cmp(f->subclass.format, ast_channel_writeformat(chan)) == AST_FORMAT_CMP_NOT_EQUAL) {
03611       float factor;
03612       factor = ((float) ast_format_get_sample_rate(ast_channel_writeformat(chan))) / ((float) ast_format_get_sample_rate(f->subclass.format));
03613       samples = (int) (((float) f->samples) * factor);
03614    } else {
03615       samples = f->samples;
03616    }
03617 
03618    gendata = ast_channel_generatordata(chan);
03619    ast_channel_generatordata_set(chan, NULL);     /* reset, to let writes go through */
03620 
03621    /*
03622     * This unlock is here based on two assumptions that hold true at
03623     * this point in the code. 1) this function is only called from
03624     * within __ast_read() and 2) all generators call ast_write() in
03625     * their generate callback.
03626     *
03627     * The reason this is added is so that when ast_write is called,
03628     * the lock that occurs there will not recursively lock the
03629     * channel.  Doing this will allow deadlock avoidance to work in
03630     * deeper functions.
03631     */
03632    ast_channel_unlock(chan);
03633    res = generator->generate(chan, gendata, f->datalen, samples);
03634    ast_channel_lock(chan);
03635    if (generator == ast_channel_generator(chan)) {
03636       ast_channel_generatordata_set(chan, gendata);
03637       if (res) {
03638          ast_debug(1, "Auto-deactivating generator\n");
03639          ast_deactivate_generator(chan);
03640       }
03641    }
03642 }
03643 
03644 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
03645 {
03646    struct ast_frame *fr = ast_channel_dtmff(chan);
03647 
03648    fr->frametype = AST_FRAME_DTMF_END;
03649    fr->subclass.integer = f->subclass.integer;
03650    fr->len = f->len;
03651 
03652    /* The only time this function will be called is for a frame that just came
03653     * out of the channel driver.  So, we want to stick it on the tail of the
03654     * readq. */
03655 
03656    ast_queue_frame(chan, fr);
03657 }
03658 
03659 /*!
03660  * \brief Determine whether or not we should ignore DTMF in the readq
03661  */
03662 static inline int should_skip_dtmf(struct ast_channel *chan)
03663 {
03664    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
03665       /* We're in the middle of emulating a digit, or DTMF has been
03666        * explicitly deferred.  Skip this digit, then. */
03667       return 1;
03668    }
03669 
03670    if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
03671          ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
03672       /* We're not in the middle of a digit, but it hasn't been long enough
03673        * since the last digit, so we'll have to skip DTMF for now. */
03674       return 1;
03675    }
03676 
03677    return 0;
03678 }
03679 
03680 /*!
03681  * \brief calculates the number of samples to jump forward with in a monitor stream.
03682 
03683  * \note When using ast_seekstream() with the read and write streams of a monitor,
03684  * the number of samples to seek forward must be of the same sample rate as the stream
03685  * or else the jump will not be calculated correctly.
03686  *
03687  * \retval number of samples to seek forward after rate conversion.
03688  */
03689 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
03690 {
03691    int diff = sample_rate - seek_rate;
03692 
03693    if (diff > 0) {
03694       samples = samples / (float) (sample_rate / seek_rate);
03695    } else if (diff < 0) {
03696       samples = samples * (float) (seek_rate / sample_rate);
03697    }
03698 
03699    return samples;
03700 }
03701 
03702 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
03703 {
03704    struct ast_frame *f = NULL;   /* the return value */
03705    int prestate;
03706    int cause = 0;
03707 
03708    /* this function is very long so make sure there is only one return
03709     * point at the end (there are only two exceptions to this).
03710     */
03711    ast_channel_lock(chan);
03712 
03713    /* Stop if we're a zombie or need a soft hangup */
03714    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03715       if (ast_channel_generator(chan))
03716          ast_deactivate_generator(chan);
03717 
03718       /*
03719        * It is possible for chan->_softhangup to be set and there
03720        * still be control frames that need to be read.  Instead of
03721        * just going to 'done' in the case of ast_check_hangup(), we
03722        * need to queue the end-of-Q frame so that it can mark the end
03723        * of the read queue.  If there are frames to be read,
03724        * ast_queue_control() will be called repeatedly, but will only
03725        * queue the first end-of-Q frame.
03726        */
03727       if (ast_channel_softhangup_internal_flag(chan)) {
03728          ast_queue_control(chan, AST_CONTROL_END_OF_Q);
03729       } else {
03730          goto done;
03731       }
03732    } else {
03733 #ifdef AST_DEVMODE
03734       /*
03735        * The ast_waitfor() code records which of the channel's file
03736        * descriptors reported that data is available.  In theory,
03737        * ast_read() should only be called after ast_waitfor() reports
03738        * that a channel has data available for reading.  However,
03739        * there still may be some edge cases throughout the code where
03740        * ast_read() is called improperly.  This can potentially cause
03741        * problems, so if this is a developer build, make a lot of
03742        * noise if this happens so that it can be addressed.
03743        *
03744        * One of the potential problems is blocking on a dead channel.
03745        */
03746       if (ast_channel_fdno(chan) == -1) {
03747          ast_log(LOG_ERROR,
03748             "ast_read() on chan '%s' called with no recorded file descriptor.\n",
03749             ast_channel_name(chan));
03750       }
03751 #endif
03752    }
03753 
03754    prestate = ast_channel_state(chan);
03755 
03756    if (ast_channel_timingfd(chan) > -1 && ast_channel_fdno(chan) == AST_TIMING_FD) {
03757       enum ast_timer_event res;
03758 
03759       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
03760 
03761       res = ast_timer_get_event(ast_channel_timer(chan));
03762 
03763       switch (res) {
03764       case AST_TIMING_EVENT_EXPIRED:
03765          if (ast_timer_ack(ast_channel_timer(chan), 1) < 0) {
03766             ast_log(LOG_ERROR, "Failed to acknoweldge timer in ast_read\n");
03767             goto done;
03768          }
03769 
03770          if (ast_channel_timingfunc(chan)) {
03771             /* save a copy of func/data before unlocking the channel */
03772             ast_timing_func_t func = ast_channel_timingfunc(chan);
03773             void *data = ast_channel_timingdata(chan);
03774             int got_ref = 0;
03775             if (data && ast_test_flag(ast_channel_flags(chan), AST_FLAG_TIMINGDATA_IS_AO2_OBJ)) {
03776                ao2_ref(data, 1);
03777                got_ref = 1;
03778             }
03779             ast_channel_fdno_set(chan, -1);
03780             ast_channel_unlock(chan);
03781             func(data);
03782             if (got_ref) {
03783                ao2_ref(data, -1);
03784             }
03785          } else {
03786             ast_timer_set_rate(ast_channel_timer(chan), 0);
03787             ast_channel_fdno_set(chan, -1);
03788             ast_channel_unlock(chan);
03789          }
03790 
03791          /* cannot 'goto done' because the channel is already unlocked */
03792          return &ast_null_frame;
03793 
03794       case AST_TIMING_EVENT_CONTINUOUS:
03795          if (AST_LIST_EMPTY(ast_channel_readq(chan)) ||
03796             !AST_LIST_NEXT(AST_LIST_FIRST(ast_channel_readq(chan)), frame_list)) {
03797             ast_timer_disable_continuous(ast_channel_timer(chan));
03798          }
03799          break;
03800       }
03801 
03802    } else if (ast_channel_fd_isset(chan, AST_GENERATOR_FD) && ast_channel_fdno(chan) == AST_GENERATOR_FD) {
03803       /* if the AST_GENERATOR_FD is set, call the generator with args
03804        * set to -1 so it can do whatever it needs to.
03805        */
03806       void *tmp = ast_channel_generatordata(chan);
03807       ast_channel_generatordata_set(chan, NULL);     /* reset to let ast_write get through */
03808       ast_channel_generator(chan)->generate(chan, tmp, -1, -1);
03809       ast_channel_generatordata_set(chan, tmp);
03810       f = &ast_null_frame;
03811       ast_channel_fdno_set(chan, -1);
03812       goto done;
03813    } else if (ast_channel_fd_isset(chan, AST_JITTERBUFFER_FD) && ast_channel_fdno(chan) == AST_JITTERBUFFER_FD) {
03814       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
03815    }
03816 
03817    /* Read and ignore anything on the alertpipe, but read only
03818       one sizeof(blah) per frame that we send from it */
03819    if (ast_channel_internal_alert_read(chan) == AST_ALERT_READ_FATAL) {
03820       f = &ast_null_frame;
03821       goto done;
03822    }
03823 
03824    /* Check for pending read queue */
03825    if (!AST_LIST_EMPTY(ast_channel_readq(chan))) {
03826       int skip_dtmf = should_skip_dtmf(chan);
03827 
03828       AST_LIST_TRAVERSE_SAFE_BEGIN(ast_channel_readq(chan), f, frame_list) {
03829          /* We have to be picky about which frame we pull off of the readq because
03830           * there are cases where we want to leave DTMF frames on the queue until
03831           * some later time. */
03832 
03833          if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
03834             continue;
03835          }
03836 
03837          AST_LIST_REMOVE_CURRENT(frame_list);
03838          break;
03839       }
03840       AST_LIST_TRAVERSE_SAFE_END;
03841 
03842       if (!f) {
03843          /* There were no acceptable frames on the readq. */
03844          f = &ast_null_frame;
03845          ast_channel_alert_write(chan);
03846       }
03847 
03848       /* Interpret hangup and end-of-Q frames to return NULL */
03849       /* XXX why not the same for frames from the channel ? */
03850       if (f->frametype == AST_FRAME_CONTROL) {
03851          switch (f->subclass.integer) {
03852          case AST_CONTROL_HANGUP:
03853             ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
03854             cause = f->data.uint32;
03855             /* Fall through */
03856          case AST_CONTROL_END_OF_Q:
03857             ast_frfree(f);
03858             f = NULL;
03859             break;
03860          default:
03861             break;
03862          }
03863       }
03864    } else {
03865       ast_channel_blocker_set(chan, pthread_self());
03866       if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION)) {
03867          if (ast_channel_tech(chan)->exception)
03868             f = ast_channel_tech(chan)->exception(chan);
03869          else {
03870             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", ast_channel_name(chan));
03871             f = &ast_null_frame;
03872          }
03873          /* Clear the exception flag */
03874          ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
03875       } else if (ast_channel_tech(chan) && ast_channel_tech(chan)->read)
03876          f = ast_channel_tech(chan)->read(chan);
03877       else
03878          ast_log(LOG_WARNING, "No read routine on channel %s\n", ast_channel_name(chan));
03879    }
03880 
03881    /* Perform the framehook read event here. After the frame enters the framehook list
03882     * there is no telling what will happen, <insert mad scientist laugh here>!!! */
03883    f = ast_framehook_list_read_event(ast_channel_framehooks(chan), f);
03884 
03885    /*
03886     * Reset the recorded file descriptor that triggered this read so that we can
03887     * easily detect when ast_read() is called without properly using ast_waitfor().
03888     */
03889    ast_channel_fdno_set(chan, -1);
03890 
03891    if (f) {
03892       struct ast_frame *readq_tail = AST_LIST_LAST(ast_channel_readq(chan));
03893       struct ast_control_read_action_payload *read_action_payload;
03894       struct ast_party_connected_line connected;
03895 
03896       /* if the channel driver returned more than one frame, stuff the excess
03897          into the readq for the next ast_read call
03898       */
03899       if (AST_LIST_NEXT(f, frame_list)) {
03900          ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
03901          ast_frfree(AST_LIST_NEXT(f, frame_list));
03902          AST_LIST_NEXT(f, frame_list) = NULL;
03903       }
03904 
03905       switch (f->frametype) {
03906       case AST_FRAME_CONTROL:
03907          if (f->subclass.integer == AST_CONTROL_ANSWER) {
03908             if (!ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING)) {
03909                ast_debug(1, "Ignoring answer on an inbound call!\n");
03910                ast_frfree(f);
03911                f = &ast_null_frame;
03912             } else if (prestate == AST_STATE_UP && ast_channel_is_bridged(chan)) {
03913                ast_debug(1, "Dropping duplicate answer!\n");
03914                ast_frfree(f);
03915                f = &ast_null_frame;
03916             } else {
03917                ast_setstate(chan, AST_STATE_UP);
03918             }
03919          } else if (f->subclass.integer == AST_CONTROL_READ_ACTION) {
03920             read_action_payload = f->data.ptr;
03921             switch (read_action_payload->action) {
03922             case AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO:
03923                ast_party_connected_line_init(&connected);
03924                ast_party_connected_line_copy(&connected, ast_channel_connected(chan));
03925                if (ast_connected_line_parse_data(read_action_payload->payload,
03926                   read_action_payload->payload_size, &connected)) {
03927                   ast_party_connected_line_free(&connected);
03928                   break;
03929                }
03930                ast_channel_unlock(chan);
03931                if (ast_channel_connected_line_sub(NULL, chan, &connected, 0) &&
03932                   ast_channel_connected_line_macro(NULL, chan, &connected, 1, 0)) {
03933                   ast_indicate_data(chan, AST_CONTROL_CONNECTED_LINE,
03934                      read_action_payload->payload,
03935                      read_action_payload->payload_size);
03936                }
03937                ast_party_connected_line_free(&connected);
03938                ast_channel_lock(chan);
03939                break;
03940             }
03941             ast_frfree(f);
03942             f = &ast_null_frame;
03943          }
03944          break;
03945       case AST_FRAME_DTMF_END:
03946          send_dtmf_end_event(chan, DTMF_RECEIVED, f->subclass.integer, f->len);
03947          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass.integer, ast_channel_name(chan), f->len);
03948          /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
03949          if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF) || ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
03950             queue_dtmf_readq(chan, f);
03951             ast_frfree(f);
03952             f = &ast_null_frame;
03953          } else if (!ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
03954             if (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
03955                 ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) {
03956                /* If it hasn't been long enough, defer this digit */
03957                queue_dtmf_readq(chan, f);
03958                ast_frfree(f);
03959                f = &ast_null_frame;
03960             } else {
03961                /* There was no begin, turn this into a begin and send the end later */
03962                struct timeval tv = ast_tvnow();
03963                f->frametype = AST_FRAME_DTMF_BEGIN;
03964                ast_set_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
03965                ast_channel_dtmf_digit_to_emulate_set(chan, f->subclass.integer);
03966                ast_channel_dtmf_tv_set(chan, &tv);
03967                if (f->len) {
03968                   if (f->len > option_dtmfminduration)
03969                      ast_channel_emulate_dtmf_duration_set(chan, f->len);
03970                   else
03971                      ast_channel_emulate_dtmf_duration_set(chan, option_dtmfminduration);
03972                } else
03973                   ast_channel_emulate_dtmf_duration_set(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
03974                ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass.integer, ast_channel_emulate_dtmf_duration(chan), ast_channel_name(chan));
03975             }
03976             if (ast_channel_audiohooks(chan)) {
03977                struct ast_frame *old_frame = f;
03978                /*!
03979                 * \todo XXX It is possible to write a digit to the audiohook twice
03980                 * if the digit was originally read while the channel was in autoservice. */
03981                f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
03982                if (old_frame != f)
03983                   ast_frfree(old_frame);
03984             }
03985          } else {
03986             struct timeval now = ast_tvnow();
03987             if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
03988                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
03989                ast_clear_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF);
03990                if (!f->len)
03991                   f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
03992 
03993                /* detect tones that were received on
03994                 * the wire with durations shorter than
03995                 * option_dtmfminduration and set f->len
03996                 * to the actual duration of the DTMF
03997                 * frames on the wire.  This will cause
03998                 * dtmf emulation to be triggered later
03999                 * on.
04000                 */
04001                if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) < option_dtmfminduration) {
04002                   f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
04003                   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, ast_channel_name(chan));
04004                }
04005             } else if (!f->len) {
04006                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
04007                f->len = option_dtmfminduration;
04008             }
04009             if (f->len < option_dtmfminduration && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_END_DTMF_ONLY)) {
04010                ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %u, emulating on %s\n", f->subclass.integer, f->len, option_dtmfminduration, ast_channel_name(chan));
04011                ast_set_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
04012                ast_channel_dtmf_digit_to_emulate_set(chan, f->subclass.integer);
04013                ast_channel_emulate_dtmf_duration_set(chan, option_dtmfminduration - f->len);
04014                ast_frfree(f);
04015                f = &ast_null_frame;
04016             } else {
04017                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
04018                if (f->len < option_dtmfminduration) {
04019                   f->len = option_dtmfminduration;
04020                }
04021                ast_channel_dtmf_tv_set(chan, &now);
04022             }
04023             if (ast_channel_audiohooks(chan)) {
04024                struct ast_frame *old_frame = f;
04025                f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
04026                if (old_frame != f)
04027                   ast_frfree(old_frame);
04028             }
04029          }
04030          break;
04031       case AST_FRAME_DTMF_BEGIN:
04032          send_dtmf_begin_event(chan, DTMF_RECEIVED, f->subclass.integer);
04033          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass.integer, ast_channel_name(chan));
04034          if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) ||
04035              (!ast_tvzero(*ast_channel_dtmf_tv(chan)) &&
04036                ast_tvdiff_ms(ast_tvnow(), *ast_channel_dtmf_tv(chan)) < AST_MIN_DTMF_GAP) ) {
04037             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
04038             ast_frfree(f);
04039             f = &ast_null_frame;
04040          } else {
04041             struct timeval now = ast_tvnow();
04042             ast_set_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF);
04043             ast_channel_dtmf_tv_set(chan, &now);
04044             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass.integer, ast_channel_name(chan));
04045          }
04046          break;
04047       case AST_FRAME_NULL:
04048          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
04049           * is reached , because we want to make sure we pass at least one
04050           * voice frame through before starting the next digit, to ensure a gap
04051           * between DTMF digits. */
04052          if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF)) {
04053             struct timeval now = ast_tvnow();
04054             if (!ast_channel_emulate_dtmf_duration(chan)) {
04055                ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
04056                ast_channel_dtmf_digit_to_emulate_set(chan, 0);
04057             } else if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
04058                ast_channel_emulate_dtmf_duration_set(chan, 0);
04059                ast_frfree(f);
04060                f = ast_channel_dtmff(chan);
04061                f->frametype = AST_FRAME_DTMF_END;
04062                f->subclass.integer = ast_channel_dtmf_digit_to_emulate(chan);
04063                f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
04064                ast_channel_dtmf_tv_set(chan, &now);
04065                ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
04066                ast_channel_dtmf_digit_to_emulate_set(chan, 0);
04067                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
04068                if (ast_channel_audiohooks(chan)) {
04069                   struct ast_frame *old_frame = f;
04070                   f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
04071                   if (old_frame != f) {
04072                      ast_frfree(old_frame);
04073                   }
04074                }
04075             }
04076          }
04077          break;
04078       case AST_FRAME_VOICE:
04079          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
04080           * is reached , because we want to make sure we pass at least one
04081           * voice frame through before starting the next digit, to ensure a gap
04082           * between DTMF digits. */
04083          if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF) && !ast_channel_emulate_dtmf_duration(chan)) {
04084             ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF);
04085             ast_channel_dtmf_digit_to_emulate_set(chan, 0);
04086          }
04087 
04088          if (dropaudio || ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
04089             if (dropaudio)
04090                ast_read_generator_actions(chan, f);
04091             ast_frfree(f);
04092             f = &ast_null_frame;
04093          }
04094 
04095          if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_EMULATE_DTMF) && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_IN_DTMF)) {
04096             struct timeval now = ast_tvnow();
04097             if (ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan)) >= ast_channel_emulate_dtmf_duration(chan)) {
04098                ast_channel_emulate_dtmf_duration_set(chan, 0);
04099                ast_frfree(f);
04100                f = ast_channel_dtmff(chan);
04101                f->frametype = AST_FRAME_DTMF_END;
04102                f->subclass.integer = ast_channel_dtmf_digit_to_emulate(chan);
04103                f->len = ast_tvdiff_ms(now, *ast_channel_dtmf_tv(chan));
04104                ast_channel_dtmf_tv_set(chan, &now);
04105                if (ast_channel_audiohooks(chan)) {
04106                   struct ast_frame *old_frame = f;
04107                   f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
04108                   if (old_frame != f)
04109                      ast_frfree(old_frame);
04110                }
04111                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass.integer, ast_channel_name(chan));
04112             } else {
04113                /* Drop voice frames while we're still in the middle of the digit */
04114                ast_frfree(f);
04115                f = &ast_null_frame;
04116             }
04117             break;
04118          }
04119          if (f->frametype != AST_FRAME_VOICE) {
04120             break;
04121          }
04122          if (ast_format_cmp(f->subclass.format, ast_channel_rawreadformat(chan)) != AST_FORMAT_CMP_EQUAL
04123             && ast_format_cmp(f->subclass.format, ast_channel_readformat(chan)) != AST_FORMAT_CMP_EQUAL) {
04124             struct ast_format *core_format;
04125 
04126             /*
04127              * Note: This frame may not be one of the current native
04128              * formats.  We may have gotten it out of the read queue from
04129              * a previous multi-frame translation, from a framehook
04130              * injected frame, or the device we're talking to isn't
04131              * respecting negotiated formats.  Regardless we will accept
04132              * all frames.
04133              *
04134              * Update the read translation path to handle the new format
04135              * that just came in.  If the core wants slinear we need to
04136              * setup a new translation path because the core is usually
04137              * doing something with the audio itself and may not handle
04138              * any other format.  e.g., Softmix bridge, holding bridge
04139              * announcer channel, recording, AMD...  Otherwise, we'll
04140              * setup to pass the frame as is to the core.  In this case
04141              * the core doesn't care.  The channel is likely in
04142              * autoservice, safesleep, or the channel is in a bridge.
04143              * Let the bridge technology deal with format compatibility
04144              * between the channels in the bridge.
04145              *
04146              * Beware of the transcode_via_slin and genericplc options as
04147              * they force any transcoding to go through slin on a bridge.
04148              * Unfortunately transcode_via_slin is enabled by default and
04149              * genericplc is enabled in the codecs.conf.sample file.
04150              *
04151              * XXX Only updating translation to slinear frames has some
04152              * corner cases if slinear is one of the native formats and
04153              * there are different sample rates involved.  We might wind
04154              * up with conflicting translation paths between channels
04155              * where the read translation path on this channel reduces
04156              * the sample rate followed by a write translation path on
04157              * the peer channel that increases the sample rate.
04158              */
04159             core_format = ast_channel_readformat(chan);
04160             if (!ast_format_cache_is_slinear(core_format)) {
04161                core_format = f->subclass.format;
04162             }
04163             if (ast_set_read_format_path(chan, f->subclass.format, core_format)) {
04164                /* Drop frame.  We couldn't make it compatible with the core. */
04165                ast_frfree(f);
04166                f = &ast_null_frame;
04167                break;
04168             }
04169          }
04170          /* Send frame to audiohooks if present */
04171          if (ast_channel_audiohooks(chan)) {
04172             struct ast_frame *old_frame = f;
04173 
04174             f = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_READ, f);
04175             if (old_frame != f) {
04176                ast_frfree(old_frame);
04177             }
04178          }
04179          if (ast_channel_monitor(chan) && ast_channel_monitor(chan)->read_stream) {
04180             /* XXX what does this do ? */
04181 #ifndef MONITOR_CONSTANT_DELAY
04182             int jump = ast_channel_outsmpl(chan) - ast_channel_insmpl(chan) - 4 * f->samples;
04183             if (jump >= 0) {
04184                jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
04185                   ast_format_get_sample_rate(f->subclass.format),
04186                   ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
04187                if (ast_seekstream(ast_channel_monitor(chan)->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                }
04190                ast_channel_insmpl_set(chan, ast_channel_insmpl(chan) + (ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)) + f->samples);
04191             } else {
04192                ast_channel_insmpl_set(chan, ast_channel_insmpl(chan) + f->samples);
04193             }
04194 #else
04195             int jump = calc_monitor_jump((ast_channel_outsmpl(chan) - ast_channel_insmpl(chan)),
04196                ast_format_get_sample_rate(f->subclass.codec),
04197                ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
04198             if (jump - MONITOR_DELAY >= 0) {
04199                if (ast_seekstream(ast_channel_monitor(chan)->read_stream, jump - f->samples, SEEK_FORCECUR) == -1) {
04200                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
04201                }
04202                ast_channel_insmpl(chan) += ast_channel_outsmpl(chan) - ast_channel_insmpl(chan);
04203             } else {
04204                ast_channel_insmpl(chan) += f->samples;
04205             }
04206 #endif
04207             if (ast_channel_monitor(chan)->state == AST_MONITOR_RUNNING) {
04208                if (ast_writestream(ast_channel_monitor(chan)->read_stream, f) < 0)
04209                   ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
04210             }
04211          }
04212 
04213          if (ast_channel_readtrans(chan)
04214             && ast_format_cmp(f->subclass.format, ast_channel_rawreadformat(chan)) == AST_FORMAT_CMP_EQUAL) {
04215             f = ast_translate(ast_channel_readtrans(chan), f, 1);
04216             if (!f) {
04217                f = &ast_null_frame;
04218             }
04219          }
04220 
04221          /*
04222           * It is possible for the translation process on the channel to have
04223           * produced multiple frames from the single input frame we passed it; if
04224           * this happens, queue the additional frames *before* the frames we may
04225           * have queued earlier. if the readq was empty, put them at the head of
04226           * the queue, and if it was not, put them just after the frame that was
04227           * at the end of the queue.
04228           */
04229          if (AST_LIST_NEXT(f, frame_list)) {
04230             if (!readq_tail) {
04231                ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
04232             } else {
04233                __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
04234             }
04235             ast_frfree(AST_LIST_NEXT(f, frame_list));
04236             AST_LIST_NEXT(f, frame_list) = NULL;
04237          }
04238 
04239          /*
04240           * Run generator sitting on the line if timing device not available
04241           * and synchronous generation of outgoing frames is necessary
04242           */
04243          ast_read_generator_actions(chan, f);
04244          break;
04245       default:
04246          /* Just pass it on! */
04247          break;
04248       }
04249    } else {
04250       /* Make sure we always return NULL in the future */
04251       if (!ast_channel_softhangup_internal_flag(chan)) {
04252          ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
04253       }
04254       if (cause)
04255          ast_channel_hangupcause_set(chan, cause);
04256       if (ast_channel_generator(chan))
04257          ast_deactivate_generator(chan);
04258       /* We no longer End the CDR here */
04259    }
04260 
04261    /* High bit prints debugging */
04262    if (ast_channel_fin(chan) & DEBUGCHAN_FLAG)
04263       ast_frame_dump(ast_channel_name(chan), f, "<<");
04264    ast_channel_fin_set(chan, FRAMECOUNT_INC(ast_channel_fin(chan)));
04265 
04266 done:
04267    if (ast_channel_music_state(chan) && ast_channel_generator(chan) && ast_channel_generator(chan)->digit && f && f->frametype == AST_FRAME_DTMF_END)
04268       ast_channel_generator(chan)->digit(chan, f->subclass.integer);
04269 
04270    if (ast_channel_audiohooks(chan) && ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))) {
04271       /* The list gets recreated if audiohooks are added again later */
04272       ast_audiohook_detach_list(ast_channel_audiohooks(chan));
04273       ast_channel_audiohooks_set(chan, NULL);
04274    }
04275    ast_channel_unlock(chan);
04276    return f;
04277 }
04278 
04279 struct ast_frame *ast_read(struct ast_channel *chan)
04280 {
04281    return __ast_read(chan, 0);
04282 }
04283 
04284 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
04285 {
04286    return __ast_read(chan, 1);
04287 }
04288 
04289 int ast_indicate(struct ast_channel *chan, int condition)
04290 {
04291    return ast_indicate_data(chan, condition, NULL, 0);
04292 }
04293 
04294 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
04295 {
04296    /* Don't include a default case here so that we get compiler warnings
04297     * when a new type is added. */
04298 
04299    switch (condition) {
04300    case AST_CONTROL_PROGRESS:
04301    case AST_CONTROL_PROCEEDING:
04302    case AST_CONTROL_VIDUPDATE:
04303    case AST_CONTROL_SRCUPDATE:
04304    case AST_CONTROL_SRCCHANGE:
04305    case AST_CONTROL_RADIO_KEY:
04306    case AST_CONTROL_RADIO_UNKEY:
04307    case AST_CONTROL_OPTION:
04308    case AST_CONTROL_WINK:
04309    case AST_CONTROL_FLASH:
04310    case AST_CONTROL_OFFHOOK:
04311    case AST_CONTROL_TAKEOFFHOOK:
04312    case AST_CONTROL_ANSWER:
04313    case AST_CONTROL_HANGUP:
04314    case AST_CONTROL_CONNECTED_LINE:
04315    case AST_CONTROL_REDIRECTING:
04316    case AST_CONTROL_TRANSFER:
04317    case AST_CONTROL_T38_PARAMETERS:
04318    case _XXX_AST_CONTROL_T38:
04319    case AST_CONTROL_CC:
04320    case AST_CONTROL_READ_ACTION:
04321    case AST_CONTROL_AOC:
04322    case AST_CONTROL_END_OF_Q:
04323    case AST_CONTROL_MCID:
04324    case AST_CONTROL_UPDATE_RTP_PEER:
04325    case AST_CONTROL_PVT_CAUSE_CODE:
04326    case AST_CONTROL_MASQUERADE_NOTIFY:
04327    case AST_CONTROL_STREAM_STOP:
04328    case AST_CONTROL_STREAM_SUSPEND:
04329    case AST_CONTROL_STREAM_REVERSE:
04330    case AST_CONTROL_STREAM_FORWARD:
04331    case AST_CONTROL_STREAM_RESTART:
04332    case AST_CONTROL_RECORD_CANCEL:
04333    case AST_CONTROL_RECORD_STOP:
04334    case AST_CONTROL_RECORD_SUSPEND:
04335    case AST_CONTROL_RECORD_MUTE:
04336       break;
04337 
04338    case AST_CONTROL_INCOMPLETE:
04339    case AST_CONTROL_CONGESTION:
04340    case AST_CONTROL_BUSY:
04341    case AST_CONTROL_RINGING:
04342    case AST_CONTROL_RING:
04343    case AST_CONTROL_HOLD:
04344       /* You can hear these */
04345       return 1;
04346 
04347    case AST_CONTROL_UNHOLD:
04348       /* This is a special case.  You stop hearing this. */
04349       break;
04350    }
04351 
04352    return 0;
04353 }
04354 
04355 void ast_channel_hangupcause_hash_set(struct ast_channel *chan, const struct ast_control_pvt_cause_code *cause_code, int datalen)
04356 {
04357    char causevar[256];
04358 
04359    if (ast_channel_dialed_causes_add(chan, cause_code, datalen)) {
04360       ast_log(LOG_WARNING, "Unable to store hangup cause for %s on %s\n", cause_code->chan_name, ast_channel_name(chan));
04361    }
04362 
04363    if (cause_code->emulate_sip_cause) {
04364       snprintf(causevar, sizeof(causevar), "HASH(SIP_CAUSE,%s)", cause_code->chan_name);
04365       ast_func_write(chan, causevar, cause_code->code);
04366    }
04367 }
04368 
04369 enum ama_flags ast_channel_string2amaflag(const char *flag)
04370 {
04371    if (!strcasecmp(flag, "default"))
04372       return DEFAULT_AMA_FLAGS;
04373    if (!strcasecmp(flag, "omit"))
04374       return AST_AMA_OMIT;
04375    if (!strcasecmp(flag, "billing"))
04376       return AST_AMA_BILLING;
04377    if (!strcasecmp(flag, "documentation"))
04378       return AST_AMA_DOCUMENTATION;
04379    return AST_AMA_NONE;
04380 }
04381 
04382 const char *ast_channel_amaflags2string(enum ama_flags flag)
04383 {
04384    switch (flag) {
04385    case AST_AMA_OMIT:
04386       return "OMIT";
04387    case AST_AMA_BILLING:
04388       return "BILLING";
04389    case AST_AMA_DOCUMENTATION:
04390       return "DOCUMENTATION";
04391    default:
04392       return "Unknown";
04393    }
04394 }
04395 
04396 /*!
04397  * \internal
04398  * \brief Preprocess connected line update.
04399  * \since 12.0.0
04400  *
04401  * \param chan channel to change the indication
04402  * \param data pointer to payload data
04403  * \param datalen size of payload data
04404  *
04405  * \note This function assumes chan is locked.
04406  *
04407  * \retval 0 keep going.
04408  * \retval -1 quit now.
04409  */
04410 static int indicate_connected_line(struct ast_channel *chan, const void *data, size_t datalen)
04411 {
04412    struct ast_party_connected_line *chan_connected = ast_channel_connected(chan);
04413    struct ast_party_connected_line *chan_indicated = ast_channel_connected_indicated(chan);
04414    struct ast_party_connected_line connected;
04415    unsigned char current[1024];
04416    unsigned char proposed[1024];
04417    int current_size;
04418    int proposed_size;
04419    int res;
04420 
04421    ast_party_connected_line_set_init(&connected, chan_connected);
04422    res = ast_connected_line_parse_data(data, datalen, &connected);
04423    if (!res) {
04424       ast_channel_set_connected_line(chan, &connected, NULL);
04425    }
04426    ast_party_connected_line_free(&connected);
04427    if (res) {
04428       return -1;
04429    }
04430 
04431    current_size = ast_connected_line_build_data(current, sizeof(current),
04432       chan_indicated, NULL);
04433    proposed_size = ast_connected_line_build_data(proposed, sizeof(proposed),
04434       chan_connected, NULL);
04435    if (current_size == -1 || proposed_size == -1) {
04436       return -1;
04437    }
04438 
04439    if (current_size == proposed_size && !memcmp(current, proposed, current_size)) {
04440       ast_debug(1, "%s: Dropping redundant connected line update \"%s\" <%s>.\n",
04441          ast_channel_name(chan),
04442          S_COR(chan_connected->id.name.valid, chan_connected->id.name.str, ""),
04443          S_COR(chan_connected->id.number.valid, chan_connected->id.number.str, ""));
04444       return -1;
04445    }
04446 
04447    ast_party_connected_line_copy(chan_indicated, chan_connected);
04448    return 0;
04449 }
04450 
04451 /*!
04452  * \internal
04453  * \brief Preprocess redirecting update.
04454  * \since 12.0.0
04455  *
04456  * \param chan channel to change the indication
04457  * \param data pointer to payload data
04458  * \param datalen size of payload data
04459  *
04460  * \note This function assumes chan is locked.
04461  *
04462  * \retval 0 keep going.
04463  * \retval -1 quit now.
04464  */
04465 static int indicate_redirecting(struct ast_channel *chan, const void *data, size_t datalen)
04466 {
04467    struct ast_party_redirecting redirecting;
04468    int res;
04469 
04470    ast_party_redirecting_set_init(&redirecting, ast_channel_redirecting(chan));
04471    res = ast_redirecting_parse_data(data, datalen, &redirecting);
04472    if (!res) {
04473       ast_channel_set_redirecting(chan, &redirecting, NULL);
04474    }
04475    ast_party_redirecting_free(&redirecting);
04476    return res ? -1 : 0;
04477 }
04478 
04479 int ast_indicate_data(struct ast_channel *chan, int _condition,
04480       const void *data, size_t datalen)
04481 {
04482    /* By using an enum, we'll get compiler warnings for values not handled
04483     * in switch statements. */
04484    enum ast_control_frame_type condition = _condition;
04485    struct ast_tone_zone_sound *ts = NULL;
04486    int res;
04487    /* this frame is used by framehooks. if it is set, we must free it at the end of this function */
04488    struct ast_frame *awesome_frame = NULL;
04489 
04490    ast_channel_lock(chan);
04491 
04492    /* Don't bother if the channel is about to go away, anyway. */
04493    if ((ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
04494          || ast_check_hangup(chan))
04495       && condition != AST_CONTROL_MASQUERADE_NOTIFY) {
04496       res = -1;
04497       goto indicate_cleanup;
04498    }
04499 
04500    if (!ast_framehook_list_is_empty(ast_channel_framehooks(chan))) {
04501       /* Do framehooks now, do it, go, go now */
04502       struct ast_frame frame = {
04503          .frametype = AST_FRAME_CONTROL,
04504          .subclass.integer = condition,
04505          .data.ptr = (void *) data, /* this cast from const is only okay because we do the ast_frdup below */
04506          .datalen = datalen
04507       };
04508 
04509       /* we have now committed to freeing this frame */
04510       awesome_frame = ast_frdup(&frame);
04511 
04512       /* who knows what we will get back! the anticipation is killing me. */
04513       if (!(awesome_frame = ast_framehook_list_write_event(ast_channel_framehooks(chan), awesome_frame))
04514          || awesome_frame->frametype != AST_FRAME_CONTROL) {
04515          res = 0;
04516          goto indicate_cleanup;
04517       }
04518 
04519       condition = awesome_frame->subclass.integer;
04520       data = awesome_frame->data.ptr;
04521       datalen = awesome_frame->datalen;
04522    }
04523 
04524    switch (condition) {
04525    case AST_CONTROL_CONNECTED_LINE:
04526       if (indicate_connected_line(chan, data, datalen)) {
04527          res = 0;
04528          goto indicate_cleanup;
04529       }
04530       break;
04531    case AST_CONTROL_REDIRECTING:
04532       if (indicate_redirecting(chan, data, datalen)) {
04533          res = 0;
04534          goto indicate_cleanup;
04535       }
04536       break;
04537    case AST_CONTROL_HOLD:
04538    case AST_CONTROL_UNHOLD:
04539       ast_channel_hold_state_set(chan, condition);
04540       break;
04541    default:
04542       break;
04543    }
04544 
04545    if (is_visible_indication(condition)) {
04546       /* A new visible indication is requested. */
04547       ast_channel_visible_indication_set(chan, condition);
04548    } else if (condition == AST_CONTROL_UNHOLD || _condition < 0) {
04549       /* Visible indication is cleared/stopped. */
04550       ast_channel_visible_indication_set(chan, 0);
04551    }
04552 
04553    if (ast_channel_tech(chan)->indicate) {
04554       /* See if the channel driver can handle this condition. */
04555       res = ast_channel_tech(chan)->indicate(chan, condition, data, datalen);
04556    } else {
04557       res = -1;
04558    }
04559 
04560    if (!res) {
04561       /* The channel driver successfully handled this indication */
04562       res = 0;
04563       goto indicate_cleanup;
04564    }
04565 
04566    /* The channel driver does not support this indication, let's fake
04567     * it by doing our own tone generation if applicable. */
04568 
04569    /*!\note If we compare the enumeration type, which does not have any
04570     * negative constants, the compiler may optimize this code away.
04571     * Therefore, we must perform an integer comparison here. */
04572    if (_condition < 0) {
04573       /* Stop any tones that are playing */
04574       ast_playtones_stop(chan);
04575       res = 0;
04576       goto indicate_cleanup;
04577    }
04578 
04579    /* Handle conditions that we have tones for. */
04580    switch (condition) {
04581    case _XXX_AST_CONTROL_T38:
04582       /* deprecated T.38 control frame */
04583       res = -1;
04584       goto indicate_cleanup;
04585    case AST_CONTROL_T38_PARAMETERS:
04586       /* there is no way to provide 'default' behavior for these
04587        * control frames, so we need to return failure, but there
04588        * is also no value in the log message below being emitted
04589        * since failure to handle these frames is not an 'error'
04590        * so just return right now. in addition, we want to return
04591        * whatever value the channel driver returned, in case it
04592        * has some meaning.*/
04593       goto indicate_cleanup;
04594    case AST_CONTROL_RINGING:
04595       ts = ast_get_indication_tone(ast_channel_zone(chan), "ring");
04596       /* It is common practice for channel drivers to return -1 if trying
04597        * to indicate ringing on a channel which is up. The idea is to let the
04598        * core generate the ringing inband. However, we don't want the
04599        * warning message about not being able to handle the specific indication
04600        * to print nor do we want ast_indicate_data to return an "error" for this
04601        * condition
04602        */
04603       if (ast_channel_state(chan) == AST_STATE_UP) {
04604          res = 0;
04605       }
04606       break;
04607    case AST_CONTROL_BUSY:
04608       ts = ast_get_indication_tone(ast_channel_zone(chan), "busy");
04609       break;
04610    case AST_CONTROL_INCOMPLETE:
04611    case AST_CONTROL_CONGESTION:
04612       ts = ast_get_indication_tone(ast_channel_zone(chan), "congestion");
04613       break;
04614    case AST_CONTROL_PVT_CAUSE_CODE:
04615       ast_channel_hangupcause_hash_set(chan, data, datalen);
04616       res = 0;
04617       break;
04618    case AST_CONTROL_PROGRESS:
04619    case AST_CONTROL_PROCEEDING:
04620    case AST_CONTROL_VIDUPDATE:
04621    case AST_CONTROL_SRCUPDATE:
04622    case AST_CONTROL_SRCCHANGE:
04623    case AST_CONTROL_RADIO_KEY:
04624    case AST_CONTROL_RADIO_UNKEY:
04625    case AST_CONTROL_OPTION:
04626    case AST_CONTROL_WINK:
04627    case AST_CONTROL_FLASH:
04628    case AST_CONTROL_OFFHOOK:
04629    case AST_CONTROL_TAKEOFFHOOK:
04630    case AST_CONTROL_ANSWER:
04631    case AST_CONTROL_HANGUP:
04632    case AST_CONTROL_RING:
04633    case AST_CONTROL_HOLD:
04634    case AST_CONTROL_UNHOLD:
04635    case AST_CONTROL_TRANSFER:
04636    case AST_CONTROL_CONNECTED_LINE:
04637    case AST_CONTROL_REDIRECTING:
04638    case AST_CONTROL_CC:
04639    case AST_CONTROL_READ_ACTION:
04640    case AST_CONTROL_AOC:
04641    case AST_CONTROL_END_OF_Q:
04642    case AST_CONTROL_MCID:
04643    case AST_CONTROL_MASQUERADE_NOTIFY:
04644    case AST_CONTROL_UPDATE_RTP_PEER:
04645    case AST_CONTROL_STREAM_STOP:
04646    case AST_CONTROL_STREAM_SUSPEND:
04647    case AST_CONTROL_STREAM_REVERSE:
04648    case AST_CONTROL_STREAM_FORWARD:
04649    case AST_CONTROL_STREAM_RESTART:
04650    case AST_CONTROL_RECORD_CANCEL:
04651    case AST_CONTROL_RECORD_STOP:
04652    case AST_CONTROL_RECORD_SUSPEND:
04653    case AST_CONTROL_RECORD_MUTE:
04654       /* Nothing left to do for these. */
04655       res = 0;
04656       break;
04657    }
04658 
04659    if (ts) {
04660       /* We have a tone to play, yay. */
04661       ast_debug(1, "Driver for channel '%s' does not support indication %u, emulating it\n", ast_channel_name(chan), condition);
04662       res = ast_playtones_start(chan, 0, ts->data, 1);
04663       ts = ast_tone_zone_sound_unref(ts);
04664    }
04665 
04666    if (res) {
04667       /* not handled */
04668       ast_log(LOG_WARNING, "Unable to handle indication %u for '%s'\n", condition, ast_channel_name(chan));
04669    }
04670 
04671 indicate_cleanup:
04672    ast_channel_unlock(chan);
04673    if (awesome_frame) {
04674       ast_frfree(awesome_frame);
04675    }
04676 
04677    return res;
04678 }
04679 
04680 int ast_recvchar(struct ast_channel *chan, int timeout)
04681 {
04682    int c;
04683    char *buf = ast_recvtext(chan, timeout);
04684    if (buf == NULL)
04685       return -1;  /* error or timeout */
04686    c = *(unsigned char *)buf;
04687    ast_free(buf);
04688    return c;
04689 }
04690 
04691 char *ast_recvtext(struct ast_channel *chan, int timeout)
04692 {
04693    int res;
04694    char *buf = NULL;
04695    struct timeval start = ast_tvnow();
04696    int ms;
04697 
04698    while ((ms = ast_remaining_ms(start, timeout))) {
04699       struct ast_frame *f;
04700 
04701       if (ast_check_hangup(chan)) {
04702          break;
04703       }
04704       res = ast_waitfor(chan, ms);
04705       if (res <= 0)  {/* timeout or error */
04706          break;
04707       }
04708       f = ast_read(chan);
04709       if (f == NULL) {
04710          break; /* no frame */
04711       }
04712       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
04713          ast_frfree(f);
04714          break;
04715       } else if (f->frametype == AST_FRAME_TEXT) {    /* what we want */
04716          buf = ast_strndup((char *) f->data.ptr, f->datalen);  /* dup and break */
04717          ast_frfree(f);
04718          break;
04719       }
04720       ast_frfree(f);
04721    }
04722    return buf;
04723 }
04724 
04725 int ast_sendtext(struct ast_channel *chan, const char *text)
04726 {
04727    int res = 0;
04728 
04729    ast_channel_lock(chan);
04730    /* Stop if we're a zombie or need a soft hangup */
04731    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
04732       ast_channel_unlock(chan);
04733       return -1;
04734    }
04735 
04736    if (ast_strlen_zero(text)) {
04737       ast_channel_unlock(chan);
04738       return 0;
04739    }
04740 
04741    CHECK_BLOCKING(chan);
04742    if (ast_channel_tech(chan)->write_text && (ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_MEDIA_TYPE_TEXT))) {
04743       struct ast_frame f;
04744 
04745       f.frametype = AST_FRAME_TEXT;
04746       f.src = "DIALPLAN";
04747       f.mallocd = AST_MALLOCD_DATA;
04748       f.datalen = strlen(text);
04749       f.data.ptr = ast_strdup(text);
04750       f.offset = 0;
04751       f.seqno = 0;
04752 
04753       f.subclass.format = ast_format_t140;
04754       res = ast_channel_tech(chan)->write_text(chan, &f);
04755    } else if (ast_channel_tech(chan)->send_text) {
04756       res = ast_channel_tech(chan)->send_text(chan, text);
04757    }
04758    ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
04759    ast_channel_unlock(chan);
04760    return res;
04761 }
04762 
04763 int ast_senddigit_begin(struct ast_channel *chan, char digit)
04764 {
04765    /* Device does not support DTMF tones, lets fake
04766     * it by doing our own generation. */
04767    static const char * const dtmf_tones[] = {
04768       "941+1336", /* 0 */
04769       "697+1209", /* 1 */
04770       "697+1336", /* 2 */
04771       "697+1477", /* 3 */
04772       "770+1209", /* 4 */
04773       "770+1336", /* 5 */
04774       "770+1477", /* 6 */
04775       "852+1209", /* 7 */
04776       "852+1336", /* 8 */
04777       "852+1477", /* 9 */
04778       "697+1633", /* A */
04779       "770+1633", /* B */
04780       "852+1633", /* C */
04781       "941+1633", /* D */
04782       "941+1209", /* * */
04783       "941+1477"  /* # */
04784    };
04785 
04786    if (!ast_channel_tech(chan)->send_digit_begin)
04787       return 0;
04788 
04789    ast_channel_lock(chan);
04790    ast_channel_sending_dtmf_digit_set(chan, digit);
04791    ast_channel_sending_dtmf_tv_set(chan, ast_tvnow());
04792    ast_channel_unlock(chan);
04793 
04794    if (!ast_channel_tech(chan)->send_digit_begin(chan, digit))
04795       return 0;
04796 
04797    if (digit >= '0' && digit <='9')
04798       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
04799    else if (digit >= 'A' && digit <= 'D')
04800       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
04801    else if (digit == '*')
04802       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
04803    else if (digit == '#')
04804       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
04805    else {
04806       /* not handled */
04807       ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, ast_channel_name(chan));
04808    }
04809 
04810    return 0;
04811 }
04812 
04813 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
04814 {
04815    int res = -1;
04816 
04817    if (ast_channel_tech(chan)->send_digit_end)
04818       res = ast_channel_tech(chan)->send_digit_end(chan, digit, duration);
04819 
04820    ast_channel_lock(chan);
04821    if (ast_channel_sending_dtmf_digit(chan) == digit) {
04822       ast_channel_sending_dtmf_digit_set(chan, 0);
04823    }
04824    ast_channel_unlock(chan);
04825 
04826    if (res && ast_channel_generator(chan))
04827       ast_playtones_stop(chan);
04828 
04829    return 0;
04830 }
04831 
04832 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
04833 {
04834    if (ast_channel_tech(chan)->send_digit_begin) {
04835       ast_senddigit_begin(chan, digit);
04836       ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04837    }
04838 
04839    return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
04840 }
04841 
04842 int ast_prod(struct ast_channel *chan)
04843 {
04844    struct ast_frame a = { AST_FRAME_VOICE };
04845    char nothing[128];
04846 
04847    /* Send an empty audio frame to get things moving */
04848    if (ast_channel_state(chan) != AST_STATE_UP) {
04849       ast_debug(1, "Prodding channel '%s'\n", ast_channel_name(chan));
04850       a.subclass.format = ast_channel_rawwriteformat(chan);
04851       a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
04852       a.src = "ast_prod"; /* this better match check in ast_write */
04853       if (ast_write(chan, &a))
04854          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", ast_channel_name(chan));
04855    }
04856    return 0;
04857 }
04858 
04859 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
04860 {
04861    int res;
04862    if (!ast_channel_tech(chan)->write_video)
04863       return 0;
04864    res = ast_write(chan, fr);
04865    if (!res)
04866       res = 1;
04867    return res;
04868 }
04869 
04870 struct plc_ds {
04871    /* A buffer in which to store SLIN PLC
04872     * samples generated by the generic PLC
04873     * functionality in plc.c
04874     */
04875    int16_t *samples_buf;
04876    /* The current number of samples in the
04877     * samples_buf
04878     */
04879    size_t num_samples;
04880    plc_state_t plc_state;
04881 };
04882 
04883 static void plc_ds_destroy(void *data)
04884 {
04885    struct plc_ds *plc = data;
04886    ast_free(plc->samples_buf);
04887    ast_free(plc);
04888 }
04889 
04890 static const struct ast_datastore_info plc_ds_info = {
04891    .type = "plc",
04892    .destroy = plc_ds_destroy,
04893 };
04894 
04895 static void adjust_frame_for_plc(struct ast_channel *chan, struct ast_frame *frame, struct ast_datastore *datastore)
04896 {
04897    int num_new_samples = frame->samples;
04898    struct plc_ds *plc = datastore->data;
04899 
04900    /* As a general note, let me explain the somewhat odd calculations used when taking
04901     * the frame offset into account here. According to documentation in frame.h, the frame's
04902     * offset field indicates the number of bytes that the audio is offset. The plc->samples_buf
04903     * is not an array of bytes, but rather an array of 16-bit integers since it holds SLIN
04904     * samples. So I had two choices to make here with the offset.
04905     *
04906     * 1. Make the offset AST_FRIENDLY_OFFSET bytes. The main downside for this is that
04907     *    I can't just add AST_FRIENDLY_OFFSET to the plc->samples_buf and have the pointer
04908     *    arithmetic come out right. I would have to do some odd casting or division for this to
04909     *    work as I wanted.
04910     * 2. Make the offset AST_FRIENDLY_OFFSET * 2 bytes. This allows the pointer arithmetic
04911     *    to work out better with the plc->samples_buf. The downside here is that the buffer's
04912     *    allocation contains an extra 64 bytes of unused space.
04913     *
04914     * I decided to go with option 2. This is why in the calloc statement and the statement that
04915     * sets the frame's offset, AST_FRIENDLY_OFFSET is multiplied by 2.
04916     */
04917 
04918    /* If this audio frame has no samples to fill in, ignore it */
04919    if (!num_new_samples) {
04920       return;
04921    }
04922 
04923    /* First, we need to be sure that our buffer is large enough to accomodate
04924     * the samples we need to fill in. This will likely only occur on the first
04925     * frame we write.
04926     */
04927    if (plc->num_samples < num_new_samples) {
04928       ast_free(plc->samples_buf);
04929       plc->samples_buf = ast_calloc(1, (num_new_samples * sizeof(*plc->samples_buf)) + (AST_FRIENDLY_OFFSET * 2));
04930       if (!plc->samples_buf) {
04931          ast_channel_datastore_remove(chan, datastore);
04932          ast_datastore_free(datastore);
04933          return;
04934       }
04935       plc->num_samples = num_new_samples;
04936    }
04937 
04938    if (frame->datalen == 0) {
04939       plc_fillin(&plc->plc_state, plc->samples_buf + AST_FRIENDLY_OFFSET, frame->samples);
04940       frame->data.ptr = plc->samples_buf + AST_FRIENDLY_OFFSET;
04941       frame->datalen = num_new_samples * 2;
04942       frame->offset = AST_FRIENDLY_OFFSET * 2;
04943    } else {
04944       plc_rx(&plc->plc_state, frame->data.ptr, frame->samples);
04945    }
04946 }
04947 
04948 static void apply_plc(struct ast_channel *chan, struct ast_frame *frame)
04949 {
04950    struct ast_datastore *datastore;
04951    struct plc_ds *plc;
04952 
04953    datastore = ast_channel_datastore_find(chan, &plc_ds_info, NULL);
04954    if (datastore) {
04955       plc = datastore->data;
04956       adjust_frame_for_plc(chan, frame, datastore);
04957       return;
04958    }
04959 
04960    datastore = ast_datastore_alloc(&plc_ds_info, NULL);
04961    if (!datastore) {
04962       return;
04963    }
04964    plc = ast_calloc(1, sizeof(*plc));
04965    if (!plc) {
04966       ast_datastore_free(datastore);
04967       return;
04968    }
04969    datastore->data = plc;
04970    ast_channel_datastore_add(chan, datastore);
04971    adjust_frame_for_plc(chan, frame, datastore);
04972 }
04973 
04974 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
04975 {
04976    int res = -1;
04977    struct ast_frame *f = NULL;
04978    int count = 0;
04979 
04980    /*Deadlock avoidance*/
04981    while(ast_channel_trylock(chan)) {
04982       /*cannot goto done since the channel is not locked*/
04983       if(count++ > 10) {
04984          ast_debug(1, "Deadlock avoided for write to channel '%s'\n", ast_channel_name(chan));
04985          return 0;
04986       }
04987       usleep(1);
04988    }
04989    /* Stop if we're a zombie or need a soft hangup */
04990    if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
04991       goto done;
04992 
04993    /* Perform the framehook write event here. After the frame enters the framehook list
04994     * there is no telling what will happen, how awesome is that!!! */
04995    if (!(fr = ast_framehook_list_write_event(ast_channel_framehooks(chan), fr))) {
04996       res = 0;
04997       goto done;
04998    }
04999 
05000    if (ast_channel_generatordata(chan) && (!fr->src || strcasecmp(fr->src, "ast_prod"))) {
05001       if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_WRITE_INT)) {
05002             ast_deactivate_generator(chan);
05003       } else {
05004          if (fr->frametype == AST_FRAME_DTMF_END) {
05005             /* There is a generator running while we're in the middle of a digit.
05006              * It's probably inband DTMF, so go ahead and pass it so it can
05007              * stop the generator */
05008             ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
05009             ast_channel_unlock(chan);
05010             res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
05011             ast_channel_lock(chan);
05012             CHECK_BLOCKING(chan);
05013          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass.integer == AST_CONTROL_UNHOLD) {
05014             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
05015             res = (ast_channel_tech(chan)->indicate == NULL) ? 0 :
05016                ast_channel_tech(chan)->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
05017          }
05018          res = 0; /* XXX explain, why 0 ? */
05019          goto done;
05020       }
05021    }
05022    /* High bit prints debugging */
05023    if (ast_channel_fout(chan) & DEBUGCHAN_FLAG)
05024       ast_frame_dump(ast_channel_name(chan), fr, ">>");
05025    CHECK_BLOCKING(chan);
05026    switch (fr->frametype) {
05027    case AST_FRAME_CONTROL:
05028       res = (ast_channel_tech(chan)->indicate == NULL) ? 0 :
05029          ast_channel_tech(chan)->indicate(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
05030       break;
05031    case AST_FRAME_DTMF_BEGIN:
05032       if (ast_channel_audiohooks(chan)) {
05033          struct ast_frame *old_frame = fr;
05034          fr = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, fr);
05035          if (old_frame != fr)
05036             f = fr;
05037       }
05038       send_dtmf_begin_event(chan, DTMF_SENT, fr->subclass.integer);
05039       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
05040       ast_channel_unlock(chan);
05041       res = ast_senddigit_begin(chan, fr->subclass.integer);
05042       ast_channel_lock(chan);
05043       CHECK_BLOCKING(chan);
05044       break;
05045    case AST_FRAME_DTMF_END:
05046       if (ast_channel_audiohooks(chan)) {
05047          struct ast_frame *new_frame = fr;
05048 
05049          new_frame = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, fr);
05050          if (new_frame != fr) {
05051             ast_frfree(new_frame);
05052          }
05053       }
05054       send_dtmf_end_event(chan, DTMF_SENT, fr->subclass.integer, fr->len);
05055       ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
05056       ast_channel_unlock(chan);
05057       res = ast_senddigit_end(chan, fr->subclass.integer, fr->len);
05058       ast_channel_lock(chan);
05059       CHECK_BLOCKING(chan);
05060       break;
05061    case AST_FRAME_TEXT:
05062       if (ast_format_cmp(fr->subclass.format, ast_format_t140) == AST_FORMAT_CMP_EQUAL) {
05063          res = (ast_channel_tech(chan)->write_text == NULL) ? 0 :
05064             ast_channel_tech(chan)->write_text(chan, fr);
05065       } else {
05066          res = (ast_channel_tech(chan)->send_text == NULL) ? 0 :
05067             ast_channel_tech(chan)->send_text(chan, (char *) fr->data.ptr);
05068       }
05069       break;
05070    case AST_FRAME_HTML:
05071       res = (ast_channel_tech(chan)->send_html == NULL) ? 0 :
05072          ast_channel_tech(chan)->send_html(chan, fr->subclass.integer, (char *) fr->data.ptr, fr->datalen);
05073       break;
05074    case AST_FRAME_VIDEO:
05075       /* XXX Handle translation of video codecs one day XXX */
05076       res = (ast_channel_tech(chan)->write_video == NULL) ? 0 :
05077          ast_channel_tech(chan)->write_video(chan, fr);
05078       break;
05079    case AST_FRAME_MODEM:
05080       res = (ast_channel_tech(chan)->write == NULL) ? 0 :
05081          ast_channel_tech(chan)->write(chan, fr);
05082       break;
05083    case AST_FRAME_VOICE:
05084       if (ast_channel_tech(chan)->write == NULL)
05085          break;   /*! \todo XXX should return 0 maybe ? */
05086 
05087       if (ast_opt_generic_plc && ast_format_cmp(fr->subclass.format, ast_format_slin) == AST_FORMAT_CMP_EQUAL) {
05088          apply_plc(chan, fr);
05089       }
05090 
05091       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
05092       if (ast_format_cmp(fr->subclass.format, ast_channel_rawwriteformat(chan)) == AST_FORMAT_CMP_EQUAL) {
05093          f = fr;
05094       } else {
05095          if (ast_format_cmp(ast_channel_writeformat(chan), fr->subclass.format) != AST_FORMAT_CMP_EQUAL) {
05096             struct ast_str *codec_buf = ast_str_alloca(256);
05097 
05098             /*
05099              * We are not setup to write this frame.  Things may have changed
05100              * on the peer side of the world and we try to adjust the format to
05101              * make it compatible again.  However, bad things can happen if we
05102              * cannot setup a new translation path.  Problems range from no
05103              * audio, one-way audio, to garbled audio.  The best we can do is
05104              * request the call to hangup since we could not make it compatible.
05105              *
05106              * Being continuously spammed by this message likely indicates a
05107              * problem with the peer because it cannot make up its mind about
05108              * which format to use.
05109              */
05110             ast_debug(1, "Channel %s changing write format from %s to %s, native formats %s\n",
05111                ast_channel_name(chan),
05112                ast_format_get_name(ast_channel_writeformat(chan)),
05113                ast_format_get_name(fr->subclass.format),
05114                ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf));
05115             if (ast_set_write_format(chan, fr->subclass.format)) {
05116                /* Could not handle the new write format.  Induce a hangup. */
05117                break;
05118             }
05119          }
05120          f = ast_channel_writetrans(chan) ? ast_translate(ast_channel_writetrans(chan), fr, 0) : fr;
05121       }
05122 
05123       if (!f) {
05124          res = 0;
05125          break;
05126       }
05127 
05128       if (ast_channel_audiohooks(chan)) {
05129          struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
05130          int freeoldlist = 0;
05131 
05132          if (f != fr) {
05133             freeoldlist = 1;
05134          }
05135 
05136          /* Since ast_audiohook_write may return a new frame, and the cur frame is
05137           * an item in a list of frames, create a new list adding each cur frame back to it
05138           * regardless if the cur frame changes or not. */
05139          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
05140             new_frame = ast_audiohook_write_list(chan, ast_channel_audiohooks(chan), AST_AUDIOHOOK_DIRECTION_WRITE, cur);
05141 
05142             /* if this frame is different than cur, preserve the end of the list,
05143              * free the old frames, and set cur to be the new frame */
05144             if (new_frame != cur) {
05145 
05146                /* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
05147                 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
05148                 * times it may override the previous frame we got from it unless we dup it */
05149                if ((dup = ast_frisolate(new_frame))) {
05150                   AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
05151                   if (freeoldlist) {
05152                      AST_LIST_NEXT(cur, frame_list) = NULL;
05153                      ast_frfree(cur);
05154                   }
05155                   if (new_frame != dup) {
05156                      ast_frfree(new_frame);
05157                   }
05158                   cur = dup;
05159                }
05160             }
05161 
05162             /* now, regardless if cur is new or not, add it to the new list,
05163              * if the new list has not started, cur will become the first item. */
05164             if (prev) {
05165                AST_LIST_NEXT(prev, frame_list) = cur;
05166             } else {
05167                f = cur; /* set f to be the beginning of our new list */
05168             }
05169             prev = cur;
05170          }
05171       }
05172 
05173       /* If Monitor is running on this channel, then we have to write frames out there too */
05174       /* the translator on chan->writetrans may have returned multiple frames
05175          from the single frame we passed in; if so, feed each one of them to the
05176          monitor */
05177       if (ast_channel_monitor(chan) && ast_channel_monitor(chan)->write_stream) {
05178          struct ast_frame *cur;
05179 
05180          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
05181          /* XXX must explain this code */
05182 #ifndef MONITOR_CONSTANT_DELAY
05183             int jump = ast_channel_insmpl(chan) - ast_channel_outsmpl(chan) - 4 * cur->samples;
05184             if (jump >= 0) {
05185                jump = calc_monitor_jump((ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)),
05186                                         ast_format_get_sample_rate(f->subclass.format),
05187                                         ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
05188                if (ast_seekstream(ast_channel_monitor(chan)->write_stream, jump, SEEK_FORCECUR) == -1) {
05189                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
05190                }
05191                ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + (ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)) + cur->samples);
05192             } else {
05193                ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + cur->samples);
05194             }
05195 #else
05196             int jump = calc_monitor_jump((ast_channel_insmpl(chan) - ast_channel_outsmpl(chan)),
05197                                          ast_format_get_sample_rate(f->subclass.codec),
05198                                          ast_format_get_sample_rate(ast_channel_monitor(chan)->read_stream->fmt->format));
05199             if (jump - MONITOR_DELAY >= 0) {
05200                if (ast_seekstream(ast_channel_monitor(chan)->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1) {
05201                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
05202                }
05203                ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + ast_channel_insmpl(chan) - ast_channel_outsmpl(chan));
05204             } else {
05205                ast_channel_outsmpl_set(chan, ast_channel_outsmpl(chan) + cur->samples);
05206             }
05207 #endif
05208             if (ast_channel_monitor(chan)->state == AST_MONITOR_RUNNING) {
05209                if (ast_writestream(ast_channel_monitor(chan)->write_stream, cur) < 0)
05210                   ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
05211             }
05212          }
05213       }
05214 
05215       /* the translator on chan->writetrans may have returned multiple frames
05216          from the single frame we passed in; if so, feed each one of them to the
05217          channel, freeing each one after it has been written */
05218       if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
05219          struct ast_frame *cur, *next = NULL;
05220          unsigned int skip = 0;
05221 
05222          cur = f;
05223          while (cur) {
05224             next = AST_LIST_NEXT(cur, frame_list);
05225             AST_LIST_NEXT(cur, frame_list) = NULL;
05226             if (!skip) {
05227                if ((res = ast_channel_tech(chan)->write(chan, cur)) < 0) {
05228                   ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
05229                   skip = 1;
05230                } else if (next) {
05231                   /* don't do this for the last frame in the list,
05232                      as the code outside the loop will do it once
05233                   */
05234                   ast_channel_fout_set(chan, FRAMECOUNT_INC(ast_channel_fout(chan)));
05235                }
05236             }
05237             ast_frfree(cur);
05238             cur = next;
05239          }
05240 
05241          /* reset f so the code below doesn't attempt to free it */
05242          f = NULL;
05243       } else {
05244          res = ast_channel_tech(chan)->write(chan, f);
05245       }
05246       break;
05247    case AST_FRAME_NULL:
05248    case AST_FRAME_IAX:
05249       /* Ignore these */
05250       res = 0;
05251       break;
05252    default:
05253       /* At this point, fr is the incoming frame and f is NULL.  Channels do
05254        * not expect to get NULL as a frame pointer and will segfault.  Hence,
05255        * we output the original frame passed in. */
05256       res = ast_channel_tech(chan)->write(chan, fr);
05257       break;
05258    }
05259 
05260    if (f && f != fr)
05261       ast_frfree(f);
05262    ast_clear_flag(ast_channel_flags(chan), AST_FLAG_BLOCKING);
05263 
05264    /* Consider a write failure to force a soft hangup */
05265    if (res < 0) {
05266       ast_channel_softhangup_internal_flag_add(chan, AST_SOFTHANGUP_DEV);
05267    } else {
05268       ast_channel_fout_set(chan, FRAMECOUNT_INC(ast_channel_fout(chan)));
05269    }
05270 done:
05271    if (ast_channel_audiohooks(chan) && ast_audiohook_write_list_empty(ast_channel_audiohooks(chan))) {
05272       /* The list gets recreated if audiohooks are added again later */
05273       ast_audiohook_detach_list(ast_channel_audiohooks(chan));
05274       ast_channel_audiohooks_set(chan, NULL);
05275    }
05276    ast_channel_unlock(chan);
05277    return res;
05278 }
05279 
05280 int ast_set_read_format_path(struct ast_channel *chan, struct ast_format *raw_format, struct ast_format *core_format)
05281 {
05282    struct ast_trans_pvt *trans_old;
05283    struct ast_trans_pvt *trans_new;
05284 
05285    if (ast_format_cmp(ast_channel_rawreadformat(chan), raw_format) == AST_FORMAT_CMP_EQUAL
05286       && ast_format_cmp(ast_channel_readformat(chan), core_format) == AST_FORMAT_CMP_EQUAL) {
05287       /* Nothing to setup */
05288       return 0;
05289    }
05290 
05291    ast_debug(1, "Channel %s setting read format path: %s -> %s\n",
05292       ast_channel_name(chan),
05293       ast_format_get_name(raw_format),
05294       ast_format_get_name(core_format));
05295 
05296    /* Setup new translation path. */
05297    if (ast_format_cmp(raw_format, core_format) != AST_FORMAT_CMP_EQUAL) {
05298       trans_new = ast_translator_build_path(core_format, raw_format);
05299       if (!trans_new) {
05300          return -1;
05301       }
05302    } else {
05303       /* No translation needed. */
05304       trans_new = NULL;
05305    }
05306    trans_old = ast_channel_readtrans(chan);
05307    if (trans_old) {
05308       ast_translator_free_path(trans_old);
05309    }
05310    ast_channel_readtrans_set(chan, trans_new);
05311    ast_channel_set_rawreadformat(chan, raw_format);
05312    ast_channel_set_readformat(chan, core_format);
05313    return 0;
05314 }
05315 
05316 struct set_format_access {
05317    const char *direction;
05318    struct ast_trans_pvt *(*get_trans)(const struct ast_channel *chan);
05319    void (*set_trans)(struct ast_channel *chan, struct ast_trans_pvt *value);
05320    struct ast_format *(*get_format)(struct ast_channel *chan);
05321    void (*set_format)(struct ast_channel *chan, struct ast_format *format);
05322    struct ast_format *(*get_rawformat)(struct ast_channel *chan);
05323    void (*set_rawformat)(struct ast_channel *chan, struct ast_format *format);
05324    int setoption;
05325 };
05326 
05327 static const struct set_format_access set_format_access_read = {
05328    .direction = "read",
05329    .get_trans = ast_channel_readtrans,
05330    .set_trans = ast_channel_readtrans_set,
05331    .get_format = ast_channel_readformat,
05332    .set_format = ast_channel_set_readformat,
05333    .get_rawformat = ast_channel_rawreadformat,
05334    .set_rawformat = ast_channel_set_rawreadformat,
05335    .setoption = AST_OPTION_FORMAT_READ,
05336 };
05337 
05338 static const struct set_format_access set_format_access_write = {
05339    .direction = "write",
05340    .get_trans = ast_channel_writetrans,
05341    .set_trans = ast_channel_writetrans_set,
05342    .get_format = ast_channel_writeformat,
05343    .set_format = ast_channel_set_writeformat,
05344    .get_rawformat = ast_channel_rawwriteformat,
05345    .set_rawformat = ast_channel_set_rawwriteformat,
05346    .setoption = AST_OPTION_FORMAT_WRITE,
05347 };
05348 
05349 static int set_format(struct ast_channel *chan, struct ast_format_cap *cap_set, const int direction)
05350 {
05351    struct ast_trans_pvt *trans_pvt;
05352    struct ast_format_cap *cap_native;
05353    const struct set_format_access *access;
05354    struct ast_format *rawformat;
05355    struct ast_format *format;
05356    RAII_VAR(struct ast_format *, best_set_fmt, NULL, ao2_cleanup);
05357    RAII_VAR(struct ast_format *, best_native_fmt, NULL, ao2_cleanup);
05358    int res;
05359 
05360    if (!direction) {
05361       /* reading */
05362       access = &set_format_access_read;
05363    } else {
05364       /* writing */
05365       access = &set_format_access_write;
05366    }
05367 
05368    best_set_fmt = ast_format_cap_get_best_by_type(cap_set, AST_MEDIA_TYPE_AUDIO);
05369    if (!best_set_fmt) {
05370       /*
05371        * Not setting any audio formats?
05372        * Assume a call without any sounds (video, text)
05373        */
05374       return 0;
05375    }
05376 
05377    /* See if the underlying channel driver is capable of performing transcoding for us */
05378    res = ast_channel_setoption(chan, access->setoption,
05379       &best_set_fmt, sizeof(best_set_fmt), 0);
05380    if (!res) {
05381       ast_debug(1, "Channel driver natively set channel %s to %s format %s\n",
05382          ast_channel_name(chan), access->direction, ast_format_get_name(best_set_fmt));
05383 
05384       ast_channel_lock(chan);
05385       cap_native = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
05386       if (!cap_native
05387          || ast_format_cap_append(cap_native, best_set_fmt, 0)) {
05388          ast_channel_unlock(chan);
05389          ao2_cleanup(cap_native);
05390          return -1;
05391       }
05392       ast_channel_nativeformats_set(chan, cap_native);
05393       ao2_cleanup(cap_native);
05394       access->set_format(chan, best_set_fmt);
05395       access->set_rawformat(chan, best_set_fmt);
05396 
05397       trans_pvt = access->get_trans(chan);
05398       if (trans_pvt) {
05399          ast_translator_free_path(trans_pvt);
05400          access->set_trans(chan, NULL);
05401       }
05402       ast_channel_unlock(chan);
05403 
05404       /* If there is a generator on the channel, it needs to know about this
05405        * change if it is the write format. */
05406       if (direction && ast_channel_generatordata(chan)) {
05407          generator_write_format_change(chan);
05408       }
05409 
05410       return 0;
05411    }
05412 
05413    ast_channel_lock(chan);
05414 
05415    format = access->get_format(chan);
05416    rawformat = access->get_rawformat(chan);
05417    ast_assert(format != NULL);
05418    ast_assert(rawformat != NULL);
05419 
05420    cap_native = ast_channel_nativeformats(chan);
05421    if (ast_format_cap_empty(cap_native)) {
05422       ast_channel_unlock(chan);
05423       ast_log(LOG_ERROR, "Unable to set format because channel %s supports no formats\n",
05424             ast_channel_name(chan));
05425       return -1;
05426    }
05427 
05428    /* Find a translation path from the native format to one of the desired formats */
05429    if (!direction) {
05430       /* reading */
05431       res = ast_translator_best_choice(cap_set, cap_native, &best_set_fmt, &best_native_fmt);
05432    } else {
05433       /* writing */
05434       res = ast_translator_best_choice(cap_native, cap_set, &best_native_fmt, &best_set_fmt);
05435    }
05436    if (res < 0) {
05437       struct ast_str *codec_native = ast_str_alloca(256);
05438       struct ast_str *codec_set = ast_str_alloca(256);
05439 
05440       ast_format_cap_get_names(cap_native, &codec_native);
05441       ast_channel_unlock(chan);
05442       ast_format_cap_get_names(cap_set, &codec_set);
05443 
05444       ast_log(LOG_WARNING, "Unable to find a codec translation path: %s -> %s\n",
05445          ast_str_buffer(direction ? codec_set : codec_native),
05446          ast_str_buffer(direction ? codec_native : codec_set));
05447       return -1;
05448    }
05449 
05450    /* Now we have a good choice for both. */
05451    if ((ast_format_cmp(rawformat, best_native_fmt) != AST_FORMAT_CMP_NOT_EQUAL) &&
05452       (ast_format_cmp(format, best_set_fmt) != AST_FORMAT_CMP_NOT_EQUAL) &&
05453       ((ast_format_cmp(rawformat, format) != AST_FORMAT_CMP_NOT_EQUAL) || access->get_trans(chan))) {
05454       /* the channel is already in these formats, so nothing to do */
05455       ast_channel_unlock(chan);
05456       return 0;
05457    }
05458 
05459    /* Free any translation we have right now */
05460    trans_pvt = access->get_trans(chan);
05461    if (trans_pvt) {
05462       ast_translator_free_path(trans_pvt);
05463       access->set_trans(chan, NULL);
05464    }
05465 
05466    /* Build a translation path from the raw format to the desired format */
05467    if (ast_format_cmp(best_set_fmt, best_native_fmt) != AST_FORMAT_CMP_NOT_EQUAL) {
05468       /*
05469        * If we were able to swap the native format to the format that
05470        * has been requested, then there is no need to try to build
05471        * a translation path.
05472        */
05473       res = 0;
05474    } else {
05475       if (!direction) {
05476          /* reading */
05477          trans_pvt = ast_translator_build_path(best_set_fmt, best_native_fmt);
05478       } else {
05479          /* writing */
05480          trans_pvt = ast_translator_build_path(best_native_fmt, best_set_fmt);
05481       }
05482       access->set_trans(chan, trans_pvt);
05483       res = trans_pvt ? 0 : -1;
05484    }
05485 
05486    if (!res) {
05487       access->set_format(chan, best_set_fmt);
05488       access->set_rawformat(chan, best_native_fmt);
05489 
05490       ast_debug(1, "Channel %s setting %s format path: %s -> %s\n",
05491          ast_channel_name(chan),
05492          access->direction,
05493          ast_format_get_name(direction ? best_set_fmt : best_native_fmt),
05494          ast_format_get_name(direction ? best_native_fmt : best_set_fmt));
05495    }
05496 
05497    ast_channel_unlock(chan);
05498 
05499    /* If there is a generator on the channel, it needs to know about this
05500     * change if it is the write format. */
05501    if (direction && ast_channel_generatordata(chan)) {
05502       generator_write_format_change(chan);
05503    }
05504 
05505    return res;
05506 }
05507 
05508 int ast_set_read_format(struct ast_channel *chan, struct ast_format *format)
05509 {
05510    struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
05511    int res;
05512 
05513    ast_assert(format != NULL);
05514 
05515    if (!cap) {
05516       return -1;
05517    }
05518    ast_format_cap_append(cap, format, 0);
05519 
05520    res = set_format(chan, cap, 0);
05521 
05522    ao2_cleanup(cap);
05523    return res;
05524 }
05525 
05526 int ast_set_read_format_from_cap(struct ast_channel *chan, struct ast_format_cap *cap)
05527 {
05528    return set_format(chan, cap, 0);
05529 }
05530 
05531 int ast_set_write_format(struct ast_channel *chan, struct ast_format *format)
05532 {
05533    struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
05534    int res;
05535 
05536    ast_assert(format != NULL);
05537 
05538    if (!cap) {
05539       return -1;
05540    }
05541    ast_format_cap_append(cap, format, 0);
05542 
05543    res = set_format(chan, cap, 1);
05544 
05545    ao2_cleanup(cap);
05546    return res;
05547 }
05548 
05549 int ast_set_write_format_from_cap(struct ast_channel *chan, struct ast_format_cap *cap)
05550 {
05551    return set_format(chan, cap, 1);
05552 }
05553 
05554 const char *ast_channel_reason2str(int reason)
05555 {
05556    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
05557    {
05558    case 0:
05559       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
05560    case AST_CONTROL_HANGUP:
05561       return "Hangup";
05562    case AST_CONTROL_RING:
05563       return "Local Ring";
05564    case AST_CONTROL_RINGING:
05565       return "Remote end Ringing";
05566    case AST_CONTROL_ANSWER:
05567       return "Remote end has Answered";
05568    case AST_CONTROL_BUSY:
05569       return "Remote end is Busy";
05570    case AST_CONTROL_CONGESTION:
05571       return "Congestion (circuits busy)";
05572    default:
05573       return "Unknown Reason!!";
05574    }
05575 }
05576 
05577 static void handle_cause(int cause, int *outstate)
05578 {
05579    if (outstate) {
05580       /* compute error and return */
05581       if (cause == AST_CAUSE_BUSY)
05582          *outstate = AST_CONTROL_BUSY;
05583       else if (cause == AST_CAUSE_CONGESTION)
05584          *outstate = AST_CONTROL_CONGESTION;
05585       else
05586          *outstate = 0;
05587    }
05588 }
05589 
05590 /*!
05591  * \internal
05592  * \brief Helper function to inherit info from parent channel.
05593  *
05594  * \param new_chan Channel inheriting information.
05595  * \param parent Channel new_chan inherits information.
05596  * \param orig Channel being replaced by the call forward channel.
05597  *
05598  * \return Nothing
05599  */
05600 static void call_forward_inherit(struct ast_channel *new_chan, struct ast_channel *parent, struct ast_channel *orig)
05601 {
05602    if (!ast_test_flag(ast_channel_flags(parent), AST_FLAG_ZOMBIE) && !ast_check_hangup(parent)) {
05603       struct ast_party_redirecting redirecting;
05604 
05605       /*
05606        * The parent is not a ZOMBIE or hungup so update it with the
05607        * original channel's redirecting information.
05608        */
05609       ast_party_redirecting_init(&redirecting);
05610       ast_channel_lock(orig);
05611       ast_party_redirecting_copy(&redirecting, ast_channel_redirecting(orig));
05612       ast_channel_unlock(orig);
05613       if (ast_channel_redirecting_sub(orig, parent, &redirecting, 0) &&
05614          ast_channel_redirecting_macro(orig, parent, &redirecting, 1, 0)) {
05615          ast_channel_update_redirecting(parent, &redirecting, NULL);
05616       }
05617       ast_party_redirecting_free(&redirecting);
05618    }
05619 
05620    /* Safely inherit variables and datastores from the parent channel. */
05621    ast_channel_lock_both(parent, new_chan);
05622    ast_channel_inherit_variables(parent, new_chan);
05623    ast_channel_datastore_inherit(parent, new_chan);
05624    ast_channel_unlock(new_chan);
05625    ast_channel_unlock(parent);
05626 }
05627 
05628 struct ast_channel *ast_call_forward(struct ast_channel *caller, struct ast_channel *orig, int *timeout, struct ast_format_cap *cap, struct outgoing_helper *oh, int *outstate)
05629 {
05630    char tmpchan[256];
05631    struct ast_channel *new_chan = NULL;
05632    char *data, *type;
05633    int cause = 0;
05634    int res;
05635 
05636    /* gather data and request the new forward channel */
05637    ast_copy_string(tmpchan, ast_channel_call_forward(orig), sizeof(tmpchan));
05638    if ((data = strchr(tmpchan, '/'))) {
05639       *data++ = '\0';
05640       type = tmpchan;
05641    } else {
05642       const char *forward_context;
05643       ast_channel_lock(orig);
05644       forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
05645       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", ast_channel_call_forward(orig), S_OR(forward_context, ast_channel_context(orig)));
05646       ast_channel_unlock(orig);
05647       data = tmpchan;
05648       type = "Local";
05649    }
05650    if (!(new_chan = ast_request(type, cap, NULL, orig, data, &cause))) {
05651       ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
05652       handle_cause(cause, outstate);
05653       ast_hangup(orig);
05654       return NULL;
05655    }
05656 
05657    /* Copy/inherit important information into new channel */
05658    if (oh) {
05659       if (oh->vars) {
05660          ast_channel_lock(new_chan);
05661          ast_set_variables(new_chan, oh->vars);
05662          ast_channel_unlock(new_chan);
05663       }
05664       if (oh->parent_channel) {
05665          call_forward_inherit(new_chan, oh->parent_channel, orig);
05666       }
05667       if (!ast_strlen_zero(oh->account)) {
05668          ast_channel_lock(new_chan);
05669          ast_channel_stage_snapshot(new_chan);
05670          ast_channel_accountcode_set(new_chan, oh->account);
05671          ast_channel_peeraccount_set(new_chan, oh->account);
05672          ast_channel_stage_snapshot_done(new_chan);
05673          ast_channel_unlock(new_chan);
05674       }
05675    } else if (caller) { /* no outgoing helper so use caller if available */
05676       call_forward_inherit(new_chan, caller, orig);
05677    }
05678    ast_set_flag(ast_channel_flags(new_chan), AST_FLAG_ORIGINATED);
05679 
05680    ast_channel_lock_both(orig, new_chan);
05681    ast_party_connected_line_copy(ast_channel_connected(new_chan), ast_channel_connected(orig));
05682    ast_party_redirecting_copy(ast_channel_redirecting(new_chan), ast_channel_redirecting(orig));
05683    ast_channel_req_accountcodes(new_chan, orig, AST_CHANNEL_REQUESTOR_REPLACEMENT);
05684    ast_channel_unlock(new_chan);
05685    ast_channel_unlock(orig);
05686 
05687    /* call new channel */
05688    res = ast_call(new_chan, data, 0);
05689    if (timeout) {
05690       *timeout = res;
05691    }
05692    if (res) {
05693       ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
05694       ast_hangup(orig);
05695       ast_hangup(new_chan);
05696       return NULL;
05697    }
05698    ast_hangup(orig);
05699 
05700    return new_chan;
05701 }
05702 
05703 struct ast_channel *__ast_request_and_dial(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
05704 {
05705    int dummy_outstate;
05706    int cause = 0;
05707    struct ast_channel *chan;
05708    int res = 0;
05709    int last_subclass = 0;
05710    struct ast_party_connected_line connected;
05711 
05712    if (outstate)
05713       *outstate = 0;
05714    else
05715       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
05716 
05717    chan = ast_request(type, cap, assignedids, requestor, addr, &cause);
05718    if (!chan) {
05719       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, addr);
05720       handle_cause(cause, outstate);
05721       return NULL;
05722    }
05723 
05724    if (oh) {
05725       if (oh->vars) {
05726          ast_channel_lock(chan);
05727          ast_set_variables(chan, oh->vars);
05728          ast_channel_unlock(chan);
05729       }
05730       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
05731          /*
05732           * Use the oh values instead of the function parameters for the
05733           * outgoing CallerID.
05734           */
05735          cid_num = oh->cid_num;
05736          cid_name = oh->cid_name;
05737       }
05738       if (oh->parent_channel) {
05739          /* Safely inherit variables and datastores from the parent channel. */
05740          ast_channel_lock_both(oh->parent_channel, chan);
05741          ast_channel_inherit_variables(oh->parent_channel, chan);
05742          ast_channel_datastore_inherit(oh->parent_channel, chan);
05743          ast_channel_unlock(oh->parent_channel);
05744          ast_channel_unlock(chan);
05745       }
05746       if (!ast_strlen_zero(oh->account)) {
05747          ast_channel_lock(chan);
05748          ast_channel_stage_snapshot(chan);
05749          ast_channel_accountcode_set(chan, oh->account);
05750          ast_channel_peeraccount_set(chan, oh->account);
05751          ast_channel_stage_snapshot_done(chan);
05752          ast_channel_unlock(chan);
05753       }
05754    }
05755 
05756    /*
05757     * I seems strange to set the CallerID on an outgoing call leg
05758     * to whom we are calling, but this function's callers are doing
05759     * various Originate methods.  This call leg goes to the local
05760     * user.  Once the local user answers, the dialplan needs to be
05761     * able to access the CallerID from the CALLERID function as if
05762     * the local user had placed this call.
05763     */
05764    ast_set_callerid(chan, cid_num, cid_name, cid_num);
05765 
05766    ast_set_flag(ast_channel_flags(chan), AST_FLAG_ORIGINATED);
05767    ast_party_connected_line_set_init(&connected, ast_channel_connected(chan));
05768    if (cid_num) {
05769       connected.id.number.valid = 1;
05770       connected.id.number.str = (char *) cid_num;
05771       connected.id.number.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05772    }
05773    if (cid_name) {
05774       connected.id.name.valid = 1;
05775       connected.id.name.str = (char *) cid_name;
05776       connected.id.name.presentation = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
05777    }
05778    ast_channel_set_connected_line(chan, &connected, NULL);
05779    if (requestor) {
05780       ast_channel_lock_both(chan, (struct ast_channel *) requestor);
05781       ast_channel_req_accountcodes(chan, requestor, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
05782       ast_channel_unlock(chan);
05783       ast_channel_unlock((struct ast_channel *) requestor);
05784    }
05785 
05786    if (ast_call(chan, addr, 0)) {   /* ast_call failed... */
05787       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, addr);
05788    } else {
05789       struct timeval start = ast_tvnow();
05790       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
05791       while (timeout && ast_channel_state(chan) != AST_STATE_UP) {
05792          struct ast_frame *f;
05793          int ms = ast_remaining_ms(start, timeout);
05794 
05795          res = ast_waitfor(chan, ms);
05796          if (res == 0) { /* timeout, treat it like ringing */
05797             *outstate = AST_CONTROL_RINGING;
05798             break;
05799          }
05800          if (res < 0) /* error or done */
05801             break;
05802          if (!ast_strlen_zero(ast_channel_call_forward(chan))) {
05803             if (!(chan = ast_call_forward(NULL, chan, NULL, cap, oh, outstate))) {
05804                return NULL;
05805             }
05806             continue;
05807          }
05808 
05809          f = ast_read(chan);
05810          if (!f) {
05811             *outstate = AST_CONTROL_HANGUP;
05812             res = 0;
05813             break;
05814          }
05815          if (f->frametype == AST_FRAME_CONTROL) {
05816             switch (f->subclass.integer) {
05817             case AST_CONTROL_RINGING:  /* record but keep going */
05818                *outstate = f->subclass.integer;
05819                break;
05820 
05821             case AST_CONTROL_BUSY:
05822                *outstate = f->subclass.integer;
05823                timeout = 0;
05824                break;
05825 
05826             case AST_CONTROL_INCOMPLETE:
05827                *outstate = AST_CONTROL_CONGESTION;
05828                timeout = 0;
05829                break;
05830 
05831             case AST_CONTROL_CONGESTION:
05832                *outstate = f->subclass.integer;
05833                timeout = 0;
05834                break;
05835 
05836             case AST_CONTROL_ANSWER:
05837                *outstate = f->subclass.integer;
05838                timeout = 0;      /* trick to force exit from the while() */
05839                break;
05840 
05841             case AST_CONTROL_PVT_CAUSE_CODE:
05842                ast_channel_hangupcause_hash_set(chan, f->data.ptr, f->datalen);
05843                break;
05844 
05845             case AST_CONTROL_PROGRESS:
05846                if (oh && oh->connect_on_early_media) {
05847                   *outstate = f->subclass.integer;
05848                   timeout = 0;      /* trick to force exit from the while() */
05849                   break;
05850                }
05851                /* Fallthrough */
05852             /* Ignore these */
05853             case AST_CONTROL_PROCEEDING:
05854             case AST_CONTROL_HOLD:
05855             case AST_CONTROL_UNHOLD:
05856             case AST_CONTROL_VIDUPDATE:
05857             case AST_CONTROL_SRCUPDATE:
05858             case AST_CONTROL_SRCCHANGE:
05859             case AST_CONTROL_CONNECTED_LINE:
05860             case AST_CONTROL_REDIRECTING:
05861             case AST_CONTROL_CC:
05862             case -1:       /* Ignore -- just stopping indications */
05863                break;
05864 
05865             default:
05866                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass.integer);
05867             }
05868             last_subclass = f->subclass.integer;
05869          }
05870          ast_frfree(f);
05871       }
05872    }
05873 
05874    /* Final fixups */
05875    if (oh) {
05876       if (!ast_strlen_zero(oh->context))
05877          ast_channel_context_set(chan, oh->context);
05878       if (!ast_strlen_zero(oh->exten))
05879          ast_channel_exten_set(chan, oh->exten);
05880       if (oh->priority)
05881          ast_channel_priority_set(chan, oh->priority);
05882    }
05883    if (ast_channel_state(chan) == AST_STATE_UP)
05884       *outstate = AST_CONTROL_ANSWER;
05885 
05886    if (res <= 0) {
05887       ast_channel_lock(chan);
05888       if (AST_CONTROL_RINGING == last_subclass) {
05889          ast_channel_hangupcause_set(chan, AST_CAUSE_NO_ANSWER);
05890       }
05891       ast_channel_unlock(chan);
05892       ast_hangup(chan);
05893       chan = NULL;
05894    }
05895    return chan;
05896 }
05897 
05898 struct ast_channel *ast_request_and_dial(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int timeout, int *outstate, const char *cidnum, const char *cidname)
05899 {
05900    return __ast_request_and_dial(type, cap, assignedids, requestor, addr, timeout, outstate, cidnum, cidname, NULL);
05901 }
05902 
05903 static int set_security_requirements(const struct ast_channel *requestor, struct ast_channel *out)
05904 {
05905    int ops[2][2] = {
05906       {AST_OPTION_SECURE_SIGNALING, 0},
05907       {AST_OPTION_SECURE_MEDIA, 0},
05908    };
05909    int i;
05910    struct ast_channel *r = (struct ast_channel *) requestor; /* UGLY */
05911    struct ast_datastore *ds;
05912 
05913    if (!requestor || !out) {
05914       return 0;
05915    }
05916 
05917    ast_channel_lock(r);
05918    if ((ds = ast_channel_datastore_find(r, &secure_call_info, NULL))) {
05919       struct ast_secure_call_store *encrypt = ds->data;
05920       ops[0][1] = encrypt->signaling;
05921       ops[1][1] = encrypt->media;
05922    } else {
05923       ast_channel_unlock(r);
05924       return 0;
05925    }
05926    ast_channel_unlock(r);
05927 
05928    for (i = 0; i < 2; i++) {
05929       if (ops[i][1]) {
05930          if (ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0)) {
05931             /* We require a security feature, but the channel won't provide it */
05932             return -1;
05933          }
05934       } else {
05935          /* We don't care if we can't clear the option on a channel that doesn't support it */
05936          ast_channel_setoption(out, ops[i][0], &ops[i][1], sizeof(ops[i][1]), 0);
05937       }
05938    }
05939 
05940    return 0;
05941 }
05942 
05943 struct ast_channel *ast_request(const char *type, struct ast_format_cap *request_cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *addr, int *cause)
05944 {
05945    struct chanlist *chan;
05946    struct ast_channel *c;
05947    int res;
05948    int foo;
05949 
05950    if (!cause)
05951       cause = &foo;
05952    *cause = AST_CAUSE_NOTDEFINED;
05953 
05954    if (AST_RWLIST_RDLOCK(&backends)) {
05955       ast_log(LOG_WARNING, "Unable to lock technology backend list\n");
05956       return NULL;
05957    }
05958 
05959    AST_RWLIST_TRAVERSE(&backends, chan, list) {
05960       struct ast_format_cap *tmp_cap;
05961       RAII_VAR(struct ast_format *, tmp_fmt, NULL, ao2_cleanup);
05962       RAII_VAR(struct ast_format *, best_audio_fmt, NULL, ao2_cleanup);
05963       struct ast_format_cap *joint_cap;
05964 
05965       if (strcasecmp(type, chan->tech->type))
05966          continue;
05967 
05968       /* find the best audio format to use */
05969       tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
05970       if (tmp_cap) {
05971          ast_format_cap_append_from_cap(tmp_cap, request_cap, AST_MEDIA_TYPE_AUDIO);
05972          /* We have audio - is it possible to connect the various calls to each other?
05973             (Avoid this check for calls without audio, like text+video calls)
05974          */
05975          res = ast_translator_best_choice(tmp_cap, chan->tech->capabilities, &tmp_fmt, &best_audio_fmt);
05976          ao2_ref(tmp_cap, -1);
05977          if (res < 0) {
05978             struct ast_str *tech_codecs = ast_str_alloca(64);
05979             struct ast_str *request_codecs = ast_str_alloca(64);
05980 
05981             ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %s) to %s\n", type,
05982                ast_format_cap_get_names(chan->tech->capabilities, &tech_codecs),
05983                ast_format_cap_get_names(request_cap, &request_codecs));
05984             *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05985             AST_RWLIST_UNLOCK(&backends);
05986             return NULL;
05987          }
05988       }
05989       AST_RWLIST_UNLOCK(&backends);
05990       if (!chan->tech->requester)
05991          return NULL;
05992 
05993       /* XXX Only the audio format calculated as being the best for translation
05994        * purposes is used for the request. This is because we don't have the ability
05995        * to signal to the initiator which one of their codecs that was offered is
05996        * the one that was selected, particularly in a chain of Local channels.
05997        */
05998       joint_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
05999       if (!joint_cap) {
06000          return NULL;
06001       }
06002       ast_format_cap_append_from_cap(joint_cap, request_cap, AST_MEDIA_TYPE_UNKNOWN);
06003       ast_format_cap_remove_by_type(joint_cap, AST_MEDIA_TYPE_AUDIO);
06004       ast_format_cap_append(joint_cap, best_audio_fmt, 0);
06005 
06006       if (!(c = chan->tech->requester(type, joint_cap, assignedids, requestor, addr, cause))) {
06007          ao2_ref(joint_cap, -1);
06008          return NULL;
06009       }
06010 
06011       if (requestor) {
06012          ast_callid callid;
06013 
06014          ast_channel_lock_both(c, (struct ast_channel *) requestor);
06015 
06016          /* Set the newly created channel's callid to the same as the requestor. */
06017          callid = ast_channel_callid(requestor);
06018          if (callid) {
06019             ast_channel_callid_set(c, callid);
06020          }
06021 
06022          ast_channel_unlock(c);
06023          ast_channel_unlock((struct ast_channel *) requestor);
06024       }
06025 
06026       ao2_ref(joint_cap, -1);
06027 
06028       if (set_security_requirements(requestor, c)) {
06029          ast_log(LOG_WARNING, "Setting security requirements failed\n");
06030          c = ast_channel_release(c);
06031          *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06032          return NULL;
06033       }
06034 
06035       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
06036       return c;
06037    }
06038 
06039    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
06040    *cause = AST_CAUSE_NOSUCHDRIVER;
06041    AST_RWLIST_UNLOCK(&backends);
06042