Mon Sep 20 2010 00:22:22

Asterisk developer's documentation


channel.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Channel Management
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 261098 $")
00029 
00030 #include "asterisk/_private.h"
00031 
00032 #include <sys/time.h>
00033 #include <signal.h>
00034 #include <math.h>
00035 
00036 #include "asterisk/paths.h"   /* use ast_config_AST_SYSTEM_NAME */
00037 
00038 #include "asterisk/pbx.h"
00039 #include "asterisk/frame.h"
00040 #include "asterisk/mod_format.h"
00041 #include "asterisk/sched.h"
00042 #include "asterisk/channel.h"
00043 #include "asterisk/musiconhold.h"
00044 #include "asterisk/say.h"
00045 #include "asterisk/file.h"
00046 #include "asterisk/cli.h"
00047 #include "asterisk/translate.h"
00048 #include "asterisk/manager.h"
00049 #include "asterisk/chanvars.h"
00050 #include "asterisk/linkedlists.h"
00051 #include "asterisk/indications.h"
00052 #include "asterisk/monitor.h"
00053 #include "asterisk/causes.h"
00054 #include "asterisk/callerid.h"
00055 #include "asterisk/utils.h"
00056 #include "asterisk/lock.h"
00057 #include "asterisk/app.h"
00058 #include "asterisk/transcap.h"
00059 #include "asterisk/devicestate.h"
00060 #include "asterisk/sha1.h"
00061 #include "asterisk/threadstorage.h"
00062 #include "asterisk/slinfactory.h"
00063 #include "asterisk/audiohook.h"
00064 #include "asterisk/timing.h"
00065 
00066 #ifdef HAVE_EPOLL
00067 #include <sys/epoll.h>
00068 #endif
00069 
00070 struct ast_epoll_data {
00071    struct ast_channel *chan;
00072    int which;
00073 };
00074 
00075 /* uncomment if you have problems with 'monitoring' synchronized files */
00076 #if 0
00077 #define MONITOR_CONSTANT_DELAY
00078 #define MONITOR_DELAY   150 * 8     /*!< 150 ms of MONITORING DELAY */
00079 #endif
00080 
00081 /*! \brief Prevent new channel allocation if shutting down. */
00082 static int shutting_down;
00083 
00084 static int uniqueint;
00085 
00086 unsigned long global_fin, global_fout;
00087 
00088 AST_THREADSTORAGE(state2str_threadbuf);
00089 #define STATE2STR_BUFSIZE   32
00090 
00091 /*! Default amount of time to use when emulating a digit as a begin and end 
00092  *  100ms */
00093 #define AST_DEFAULT_EMULATE_DTMF_DURATION 100
00094 
00095 /*! Minimum allowed digit length - 80ms */
00096 #define AST_MIN_DTMF_DURATION 80
00097 
00098 /*! Minimum amount of time between the end of the last digit and the beginning 
00099  *  of a new one - 45ms */
00100 #define AST_MIN_DTMF_GAP 45
00101 
00102 /*! \brief List of channel drivers */
00103 struct chanlist {
00104    const struct ast_channel_tech *tech;
00105    AST_LIST_ENTRY(chanlist) list;
00106 };
00107 
00108 #ifdef CHANNEL_TRACE
00109 /*! \brief Structure to hold channel context backtrace data */
00110 struct ast_chan_trace_data {
00111    int enabled;
00112    AST_LIST_HEAD_NOLOCK(, ast_chan_trace) trace;
00113 };
00114 
00115 /*! \brief Structure to save contexts where an ast_chan has been into */
00116 struct ast_chan_trace {
00117    char context[AST_MAX_CONTEXT];
00118    char exten[AST_MAX_EXTENSION];
00119    int priority;
00120    AST_LIST_ENTRY(ast_chan_trace) entry;
00121 };
00122 #endif
00123 
00124 /*! \brief the list of registered channel types */
00125 static AST_LIST_HEAD_NOLOCK_STATIC(backends, chanlist);
00126 
00127 /*! \brief the list of channels we have. Note that the lock for this list is used for
00128    both the channels list and the backends list.  */
00129 static AST_RWLIST_HEAD_STATIC(channels, ast_channel);
00130 
00131 /*! \brief map AST_CAUSE's to readable string representations 
00132  *
00133  * \ref causes.h
00134 */
00135 static const struct {
00136    int cause;
00137    const char *name;
00138    const char *desc;
00139 } causes[] = {
00140    { AST_CAUSE_UNALLOCATED, "UNALLOCATED", "Unallocated (unassigned) number" },
00141    { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "NO_ROUTE_TRANSIT_NET", "No route to specified transmit network" },
00142    { AST_CAUSE_NO_ROUTE_DESTINATION, "NO_ROUTE_DESTINATION", "No route to destination" },
00143    { AST_CAUSE_CHANNEL_UNACCEPTABLE, "CHANNEL_UNACCEPTABLE", "Channel unacceptable" },
00144    { AST_CAUSE_CALL_AWARDED_DELIVERED, "CALL_AWARDED_DELIVERED", "Call awarded and being delivered in an established channel" },
00145    { AST_CAUSE_NORMAL_CLEARING, "NORMAL_CLEARING", "Normal Clearing" },
00146    { AST_CAUSE_USER_BUSY, "USER_BUSY", "User busy" },
00147    { AST_CAUSE_NO_USER_RESPONSE, "NO_USER_RESPONSE", "No user responding" },
00148    { AST_CAUSE_NO_ANSWER, "NO_ANSWER", "User alerting, no answer" },
00149    { AST_CAUSE_CALL_REJECTED, "CALL_REJECTED", "Call Rejected" },
00150    { AST_CAUSE_NUMBER_CHANGED, "NUMBER_CHANGED", "Number changed" },
00151    { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "DESTINATION_OUT_OF_ORDER", "Destination out of order" },
00152    { AST_CAUSE_INVALID_NUMBER_FORMAT, "INVALID_NUMBER_FORMAT", "Invalid number format" },
00153    { AST_CAUSE_FACILITY_REJECTED, "FACILITY_REJECTED", "Facility rejected" },
00154    { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "RESPONSE_TO_STATUS_ENQUIRY", "Response to STATus ENQuiry" },
00155    { AST_CAUSE_NORMAL_UNSPECIFIED, "NORMAL_UNSPECIFIED", "Normal, unspecified" },
00156    { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "NORMAL_CIRCUIT_CONGESTION", "Circuit/channel congestion" },
00157    { AST_CAUSE_NETWORK_OUT_OF_ORDER, "NETWORK_OUT_OF_ORDER", "Network out of order" },
00158    { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "NORMAL_TEMPORARY_FAILURE", "Temporary failure" },
00159    { AST_CAUSE_SWITCH_CONGESTION, "SWITCH_CONGESTION", "Switching equipment congestion" },
00160    { AST_CAUSE_ACCESS_INFO_DISCARDED, "ACCESS_INFO_DISCARDED", "Access information discarded" },
00161    { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "REQUESTED_CHAN_UNAVAIL", "Requested channel not available" },
00162    { AST_CAUSE_PRE_EMPTED, "PRE_EMPTED", "Pre-empted" },
00163    { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "FACILITY_NOT_SUBSCRIBED", "Facility not subscribed" },
00164    { AST_CAUSE_OUTGOING_CALL_BARRED, "OUTGOING_CALL_BARRED", "Outgoing call barred" },
00165    { AST_CAUSE_INCOMING_CALL_BARRED, "INCOMING_CALL_BARRED", "Incoming call barred" },
00166    { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "BEARERCAPABILITY_NOTAUTH", "Bearer capability not authorized" },
00167    { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "BEARERCAPABILITY_NOTAVAIL", "Bearer capability not available" },
00168    { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "BEARERCAPABILITY_NOTIMPL", "Bearer capability not implemented" },
00169    { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "CHAN_NOT_IMPLEMENTED", "Channel not implemented" },
00170    { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "FACILITY_NOT_IMPLEMENTED", "Facility not implemented" },
00171    { AST_CAUSE_INVALID_CALL_REFERENCE, "INVALID_CALL_REFERENCE", "Invalid call reference value" },
00172    { AST_CAUSE_INCOMPATIBLE_DESTINATION, "INCOMPATIBLE_DESTINATION", "Incompatible destination" },
00173    { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "INVALID_MSG_UNSPECIFIED", "Invalid message unspecified" },
00174    { AST_CAUSE_MANDATORY_IE_MISSING, "MANDATORY_IE_MISSING", "Mandatory information element is missing" },
00175    { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "MESSAGE_TYPE_NONEXIST", "Message type nonexist." },
00176    { AST_CAUSE_WRONG_MESSAGE, "WRONG_MESSAGE", "Wrong message" },
00177    { AST_CAUSE_IE_NONEXIST, "IE_NONEXIST", "Info. element nonexist or not implemented" },
00178    { AST_CAUSE_INVALID_IE_CONTENTS, "INVALID_IE_CONTENTS", "Invalid information element contents" },
00179    { AST_CAUSE_WRONG_CALL_STATE, "WRONG_CALL_STATE", "Message not compatible with call state" },
00180    { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "RECOVERY_ON_TIMER_EXPIRE", "Recover on timer expiry" },
00181    { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "MANDATORY_IE_LENGTH_ERROR", "Mandatory IE length error" },
00182    { AST_CAUSE_PROTOCOL_ERROR, "PROTOCOL_ERROR", "Protocol error, unspecified" },
00183    { AST_CAUSE_INTERWORKING, "INTERWORKING", "Interworking, unspecified" },
00184 };
00185 
00186 struct ast_variable *ast_channeltype_list(void)
00187 {
00188    struct chanlist *cl;
00189    struct ast_variable *var=NULL, *prev = NULL;
00190    AST_LIST_TRAVERSE(&backends, cl, list) {
00191       if (prev)  {
00192          if ((prev->next = ast_variable_new(cl->tech->type, cl->tech->description, "")))
00193             prev = prev->next;
00194       } else {
00195          var = ast_variable_new(cl->tech->type, cl->tech->description, "");
00196          prev = var;
00197       }
00198    }
00199    return var;
00200 }
00201 
00202 /*! \brief Show channel types - CLI command */
00203 static char *handle_cli_core_show_channeltypes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00204 {
00205 #define FORMAT  "%-10.10s  %-40.40s %-12.12s %-12.12s %-12.12s\n"
00206    struct chanlist *cl;
00207    int count_chan = 0;
00208 
00209    switch (cmd) {
00210    case CLI_INIT:
00211       e->command = "core show channeltypes";
00212       e->usage =
00213          "Usage: core show channeltypes\n"
00214          "       Lists available channel types registered in your\n"
00215          "       Asterisk server.\n";
00216       return NULL;
00217    case CLI_GENERATE:
00218       return NULL;
00219    }
00220 
00221    if (a->argc != 3)
00222       return CLI_SHOWUSAGE;
00223 
00224    ast_cli(a->fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
00225    ast_cli(a->fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
00226 
00227    AST_RWLIST_RDLOCK(&channels);
00228 
00229    AST_LIST_TRAVERSE(&backends, cl, list) {
00230       ast_cli(a->fd, FORMAT, cl->tech->type, cl->tech->description,
00231          (cl->tech->devicestate) ? "yes" : "no",
00232          (cl->tech->indicate) ? "yes" : "no",
00233          (cl->tech->transfer) ? "yes" : "no");
00234       count_chan++;
00235    }
00236 
00237    AST_RWLIST_UNLOCK(&channels);
00238 
00239    ast_cli(a->fd, "----------\n%d channel drivers registered.\n", count_chan);
00240 
00241    return CLI_SUCCESS;
00242 
00243 #undef FORMAT
00244 }
00245 
00246 static char *complete_channeltypes(struct ast_cli_args *a)
00247 {
00248    struct chanlist *cl;
00249    int which = 0;
00250    int wordlen;
00251    char *ret = NULL;
00252 
00253    if (a->pos != 3)
00254       return NULL;
00255 
00256    wordlen = strlen(a->word);
00257 
00258    AST_LIST_TRAVERSE(&backends, cl, list) {
00259       if (!strncasecmp(a->word, cl->tech->type, wordlen) && ++which > a->n) {
00260          ret = ast_strdup(cl->tech->type);
00261          break;
00262       }
00263    }
00264    
00265    return ret;
00266 }
00267 
00268 /*! \brief Show details about a channel driver - CLI command */
00269 static char *handle_cli_core_show_channeltype(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
00270 {
00271    struct chanlist *cl = NULL;
00272 
00273    switch (cmd) {
00274    case CLI_INIT:
00275       e->command = "core show channeltype";
00276       e->usage =
00277          "Usage: core show channeltype <name>\n"
00278          "  Show details about the specified channel type, <name>.\n";
00279       return NULL;
00280    case CLI_GENERATE:
00281       return complete_channeltypes(a);
00282    }
00283 
00284    if (a->argc != 4)
00285       return CLI_SHOWUSAGE;
00286    
00287    AST_RWLIST_RDLOCK(&channels);
00288 
00289    AST_LIST_TRAVERSE(&backends, cl, list) {
00290       if (!strncasecmp(cl->tech->type, a->argv[3], strlen(cl->tech->type)))
00291          break;
00292    }
00293 
00294 
00295    if (!cl) {
00296       ast_cli(a->fd, "\n%s is not a registered channel driver.\n", a->argv[3]);
00297       AST_RWLIST_UNLOCK(&channels);
00298       return CLI_FAILURE;
00299    }
00300 
00301    ast_cli(a->fd,
00302       "-- Info about channel driver: %s --\n"
00303       "  Device State: %s\n"
00304       "    Indication: %s\n"
00305       "     Transfer : %s\n"
00306       "  Capabilities: %d\n"
00307       "   Digit Begin: %s\n"
00308       "     Digit End: %s\n"
00309       "    Send HTML : %s\n"
00310       " Image Support: %s\n"
00311       "  Text Support: %s\n",
00312       cl->tech->type,
00313       (cl->tech->devicestate) ? "yes" : "no",
00314       (cl->tech->indicate) ? "yes" : "no",
00315       (cl->tech->transfer) ? "yes" : "no",
00316       (cl->tech->capabilities) ? cl->tech->capabilities : -1,
00317       (cl->tech->send_digit_begin) ? "yes" : "no",
00318       (cl->tech->send_digit_end) ? "yes" : "no",
00319       (cl->tech->send_html) ? "yes" : "no",
00320       (cl->tech->send_image) ? "yes" : "no",
00321       (cl->tech->send_text) ? "yes" : "no"
00322       
00323    );
00324 
00325    AST_RWLIST_UNLOCK(&channels);
00326    return CLI_SUCCESS;
00327 }
00328 
00329 static struct ast_cli_entry cli_channel[] = {
00330    AST_CLI_DEFINE(handle_cli_core_show_channeltypes, "List available channel types"),
00331    AST_CLI_DEFINE(handle_cli_core_show_channeltype,  "Give more details on that channel type")
00332 };
00333 
00334 #ifdef CHANNEL_TRACE
00335 /*! \brief Destructor for the channel trace datastore */
00336 static void ast_chan_trace_destroy_cb(void *data)
00337 {
00338    struct ast_chan_trace *trace;
00339    struct ast_chan_trace_data *traced = data;
00340    while ((trace = AST_LIST_REMOVE_HEAD(&traced->trace, entry))) {
00341       ast_free(trace);
00342    }
00343    ast_free(traced);
00344 }
00345 
00346 /*! \brief Datastore to put the linked list of ast_chan_trace and trace status */
00347 const struct ast_datastore_info ast_chan_trace_datastore_info = {
00348    .type = "ChanTrace",
00349    .destroy = ast_chan_trace_destroy_cb
00350 };
00351 
00352 /*! \brief Put the channel backtrace in a string */
00353 int ast_channel_trace_serialize(struct ast_channel *chan, struct ast_str **buf)
00354 {
00355    int total = 0;
00356    struct ast_chan_trace *trace;
00357    struct ast_chan_trace_data *traced;
00358    struct ast_datastore *store;
00359 
00360    ast_channel_lock(chan);
00361    store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00362    if (!store) {
00363       ast_channel_unlock(chan);
00364       return total;
00365    }
00366    traced = store->data;
00367    ast_str_reset(*buf);
00368    AST_LIST_TRAVERSE(&traced->trace, trace, entry) {
00369       if (ast_str_append(buf, 0, "[%d] => %s, %s, %d\n", total, trace->context, trace->exten, trace->priority) < 0) {
00370          ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
00371          total = -1;
00372          break;
00373       }
00374       total++;
00375    }
00376    ast_channel_unlock(chan);
00377    return total;
00378 }
00379 
00380 /* !\brief Whether or not context tracing is enabled */
00381 int ast_channel_trace_is_enabled(struct ast_channel *chan)
00382 {
00383    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00384    if (!store)
00385       return 0;
00386    return ((struct ast_chan_trace_data *)store->data)->enabled;
00387 }
00388 
00389 /*! \brief Update the context backtrace data if tracing is enabled */
00390 static int ast_channel_trace_data_update(struct ast_channel *chan, struct ast_chan_trace_data *traced)
00391 {
00392    struct ast_chan_trace *trace;
00393    if (!traced->enabled)
00394       return 0;
00395    /* If the last saved context does not match the current one
00396       OR we have not saved any context so far, then save the current context */
00397    if ((!AST_LIST_EMPTY(&traced->trace) && strcasecmp(AST_LIST_FIRST(&traced->trace)->context, chan->context)) || 
00398        (AST_LIST_EMPTY(&traced->trace))) {
00399       /* Just do some debug logging */
00400       if (AST_LIST_EMPTY(&traced->trace))
00401          ast_log(LOG_DEBUG, "Setting initial trace context to %s\n", chan->context);
00402       else
00403          ast_log(LOG_DEBUG, "Changing trace context from %s to %s\n", AST_LIST_FIRST(&traced->trace)->context, chan->context);
00404       /* alloc or bail out */
00405       trace = ast_malloc(sizeof(*trace));
00406       if (!trace) 
00407          return -1;
00408       /* save the current location and store it in the trace list */
00409       ast_copy_string(trace->context, chan->context, sizeof(trace->context));
00410       ast_copy_string(trace->exten, chan->exten, sizeof(trace->exten));
00411       trace->priority = chan->priority;
00412       AST_LIST_INSERT_HEAD(&traced->trace, trace, entry);
00413    }
00414    return 0;
00415 }
00416 
00417 /*! \brief Update the context backtrace if tracing is enabled */
00418 int ast_channel_trace_update(struct ast_channel *chan)
00419 {
00420    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00421    if (!store)
00422       return 0;
00423    return ast_channel_trace_data_update(chan, store->data);
00424 }
00425 
00426 /*! \brief Enable context tracing in the channel */
00427 int ast_channel_trace_enable(struct ast_channel *chan)
00428 {
00429    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00430    struct ast_chan_trace_data *traced;
00431    if (!store) {
00432       store = ast_datastore_alloc(&ast_chan_trace_datastore_info, "ChanTrace");
00433       if (!store) 
00434          return -1;
00435       traced = ast_calloc(1, sizeof(*traced));
00436       if (!traced) {
00437          ast_datastore_free(store);
00438          return -1;
00439       }  
00440       store->data = traced;
00441       AST_LIST_HEAD_INIT_NOLOCK(&traced->trace);
00442       ast_channel_datastore_add(chan, store);
00443    }  
00444    ((struct ast_chan_trace_data *)store->data)->enabled = 1;
00445    ast_channel_trace_data_update(chan, store->data);
00446    return 0;
00447 }
00448 
00449 /*! \brief Disable context tracing in the channel */
00450 int ast_channel_trace_disable(struct ast_channel *chan)
00451 {
00452    struct ast_datastore *store = ast_channel_datastore_find(chan, &ast_chan_trace_datastore_info, NULL);
00453    if (!store)
00454       return 0;
00455    ((struct ast_chan_trace_data *)store->data)->enabled = 0;
00456    return 0;
00457 }
00458 #endif /* CHANNEL_TRACE */
00459 
00460 /*! \brief Checks to see if a channel is needing hang up */
00461 int ast_check_hangup(struct ast_channel *chan)
00462 {
00463    if (chan->_softhangup)     /* yes if soft hangup flag set */
00464       return 1;
00465    if (ast_tvzero(chan->whentohangup)) /* no if no hangup scheduled */
00466       return 0;
00467    if (ast_tvdiff_ms(chan->whentohangup, ast_tvnow()) > 0)  /* no if hangup time has not come yet. */
00468       return 0;
00469    chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT; /* record event */
00470    return 1;
00471 }
00472 
00473 static 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 /*! \brief Initiate system shutdown */
00483 void ast_begin_shutdown(int hangup)
00484 {
00485    struct ast_channel *c;
00486    shutting_down = 1;
00487    if (hangup) {
00488       AST_RWLIST_RDLOCK(&channels);
00489       AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
00490          ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
00491       }
00492       AST_RWLIST_UNLOCK(&channels);
00493    }
00494 }
00495 
00496 /*! \brief returns number of active/allocated channels */
00497 int ast_active_channels(void)
00498 {
00499    struct ast_channel *c;
00500    int cnt = 0;
00501    AST_RWLIST_RDLOCK(&channels);
00502    AST_RWLIST_TRAVERSE(&channels, c, chan_list)
00503       cnt++;
00504    AST_RWLIST_UNLOCK(&channels);
00505    return cnt;
00506 }
00507 
00508 /*! \brief Cancel a shutdown in progress */
00509 void ast_cancel_shutdown(void)
00510 {
00511    shutting_down = 0;
00512 }
00513 
00514 /*! \brief Returns non-zero if Asterisk is being shut down */
00515 int ast_shutting_down(void)
00516 {
00517    return shutting_down;
00518 }
00519 
00520 /*! \brief Set when to hangup channel */
00521 void ast_channel_setwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00522 {
00523    chan->whentohangup = ast_tvzero(offset) ? offset : ast_tvadd(offset, ast_tvnow());
00524    ast_queue_frame(chan, &ast_null_frame);
00525    return;
00526 }
00527 
00528 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
00529 {
00530    struct timeval when = { offset, };
00531    ast_channel_setwhentohangup_tv(chan, when);
00532 }
00533 
00534 /*! \brief Compare a offset with when to hangup channel */
00535 int ast_channel_cmpwhentohangup_tv(struct ast_channel *chan, struct timeval offset)
00536 {
00537    struct timeval whentohangup;
00538 
00539    if (ast_tvzero(chan->whentohangup))
00540       return ast_tvzero(offset) ? 0 : -1;
00541 
00542    if (ast_tvzero(offset))
00543       return 1;
00544 
00545    whentohangup = ast_tvadd(offset, ast_tvnow());
00546 
00547    return ast_tvdiff_ms(whentohangup, chan->whentohangup);
00548 }
00549 
00550 int ast_channel_cmpwhentohangup(struct ast_channel *chan, time_t offset)
00551 {
00552    struct timeval when = { offset, };
00553    return ast_channel_cmpwhentohangup_tv(chan, when);
00554 }
00555 
00556 /*! \brief Register a new telephony channel in Asterisk */
00557 int ast_channel_register(const struct ast_channel_tech *tech)
00558 {
00559    struct chanlist *chan;
00560 
00561    AST_RWLIST_WRLOCK(&channels);
00562 
00563    AST_LIST_TRAVERSE(&backends, chan, list) {
00564       if (!strcasecmp(tech->type, chan->tech->type)) {
00565          ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
00566          AST_RWLIST_UNLOCK(&channels);
00567          return -1;
00568       }
00569    }
00570    
00571    if (!(chan = ast_calloc(1, sizeof(*chan)))) {
00572       AST_RWLIST_UNLOCK(&channels);
00573       return -1;
00574    }
00575    chan->tech = tech;
00576    AST_LIST_INSERT_HEAD(&backends, chan, list);
00577 
00578    ast_debug(1, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
00579 
00580    ast_verb(2, "Registered channel type '%s' (%s)\n", chan->tech->type, chan->tech->description);
00581 
00582    AST_RWLIST_UNLOCK(&channels);
00583    return 0;
00584 }
00585 
00586 /*! \brief Unregister channel driver */
00587 void ast_channel_unregister(const struct ast_channel_tech *tech)
00588 {
00589    struct chanlist *chan;
00590 
00591    ast_debug(1, "Unregistering channel type '%s'\n", tech->type);
00592 
00593    AST_RWLIST_WRLOCK(&channels);
00594 
00595    AST_LIST_TRAVERSE_SAFE_BEGIN(&backends, chan, list) {
00596       if (chan->tech == tech) {
00597          AST_LIST_REMOVE_CURRENT(list);
00598          ast_free(chan);
00599          ast_verb(2, "Unregistered channel type '%s'\n", tech->type);
00600          break;   
00601       }
00602    }
00603    AST_LIST_TRAVERSE_SAFE_END;
00604 
00605    AST_RWLIST_UNLOCK(&channels);
00606 }
00607 
00608 /*! \brief Get handle to channel driver based on name */
00609 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
00610 {
00611    struct chanlist *chanls;
00612    const struct ast_channel_tech *ret = NULL;
00613 
00614    AST_RWLIST_RDLOCK(&channels);
00615 
00616    AST_LIST_TRAVERSE(&backends, chanls, list) {
00617       if (!strcasecmp(name, chanls->tech->type)) {
00618          ret = chanls->tech;
00619          break;
00620       }
00621    }
00622 
00623    AST_RWLIST_UNLOCK(&channels);
00624    
00625    return ret;
00626 }
00627 
00628 /*! \brief Gives the string form of a given hangup cause */
00629 const char *ast_cause2str(int cause)
00630 {
00631    int x;
00632 
00633    for (x = 0; x < ARRAY_LEN(causes); x++) {
00634       if (causes[x].cause == cause)
00635          return causes[x].desc;
00636    }
00637 
00638    return "Unknown";
00639 }
00640 
00641 /*! \brief Convert a symbolic hangup cause to number */
00642 int ast_str2cause(const char *name)
00643 {
00644    int x;
00645 
00646    for (x = 0; x < ARRAY_LEN(causes); x++)
00647       if (!strncasecmp(causes[x].name, name, strlen(causes[x].name)))
00648          return causes[x].cause;
00649 
00650    return -1;
00651 }
00652 
00653 /*! \brief Gives the string form of a given channel state.
00654    \note This function is not reentrant.
00655  */
00656 const char *ast_state2str(enum ast_channel_state state)
00657 {
00658    char *buf;
00659 
00660    switch (state) {
00661    case AST_STATE_DOWN:
00662       return "Down";
00663    case AST_STATE_RESERVED:
00664       return "Rsrvd";
00665    case AST_STATE_OFFHOOK:
00666       return "OffHook";
00667    case AST_STATE_DIALING:
00668       return "Dialing";
00669    case AST_STATE_RING:
00670       return "Ring";
00671    case AST_STATE_RINGING:
00672       return "Ringing";
00673    case AST_STATE_UP:
00674       return "Up";
00675    case AST_STATE_BUSY:
00676       return "Busy";
00677    case AST_STATE_DIALING_OFFHOOK:
00678       return "Dialing Offhook";
00679    case AST_STATE_PRERING:
00680       return "Pre-ring";
00681    default:
00682       if (!(buf = ast_threadstorage_get(&state2str_threadbuf, STATE2STR_BUFSIZE)))
00683          return "Unknown";
00684       snprintf(buf, STATE2STR_BUFSIZE, "Unknown (%d)", state);
00685       return buf;
00686    }
00687 }
00688 
00689 /*! \brief Gives the string form of a given transfer capability */
00690 char *ast_transfercapability2str(int transfercapability)
00691 {
00692    switch (transfercapability) {
00693    case AST_TRANS_CAP_SPEECH:
00694       return "SPEECH";
00695    case AST_TRANS_CAP_DIGITAL:
00696       return "DIGITAL";
00697    case AST_TRANS_CAP_RESTRICTED_DIGITAL:
00698       return "RESTRICTED_DIGITAL";
00699    case AST_TRANS_CAP_3_1K_AUDIO:
00700       return "3K1AUDIO";
00701    case AST_TRANS_CAP_DIGITAL_W_TONES:
00702       return "DIGITAL_W_TONES";
00703    case AST_TRANS_CAP_VIDEO:
00704       return "VIDEO";
00705    default:
00706       return "UNKNOWN";
00707    }
00708 }
00709 
00710 /*! \brief Pick the best audio codec */
00711 int ast_best_codec(int fmts)
00712 {
00713    /* This just our opinion, expressed in code.  We are asked to choose
00714       the best codec to use, given no information */
00715    int x;
00716    static const int prefs[] =
00717    {
00718       /*! Okay, ulaw is used by all telephony equipment, so start with it */
00719       AST_FORMAT_ULAW,
00720       /*! Unless of course, you're a silly European, so then prefer ALAW */
00721       AST_FORMAT_ALAW,
00722       AST_FORMAT_SIREN14,
00723       AST_FORMAT_SIREN7,
00724       /*! G.722 is better then all below, but not as common as the above... so give ulaw and alaw priority */
00725       AST_FORMAT_G722,
00726       /*! Okay, well, signed linear is easy to translate into other stuff */
00727       AST_FORMAT_SLINEAR16,
00728       AST_FORMAT_SLINEAR,
00729       /*! G.726 is standard ADPCM, in RFC3551 packing order */
00730       AST_FORMAT_G726,
00731       /*! G.726 is standard ADPCM, in AAL2 packing order */
00732       AST_FORMAT_G726_AAL2,
00733       /*! ADPCM has great sound quality and is still pretty easy to translate */
00734       AST_FORMAT_ADPCM,
00735       /*! Okay, we're down to vocoders now, so pick GSM because it's small and easier to
00736           translate and sounds pretty good */
00737       AST_FORMAT_GSM,
00738       /*! iLBC is not too bad */
00739       AST_FORMAT_ILBC,
00740       /*! Speex is free, but computationally more expensive than GSM */
00741       AST_FORMAT_SPEEX,
00742       /*! Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
00743           to use it */
00744       AST_FORMAT_LPC10,
00745       /*! G.729a is faster than 723 and slightly less expensive */
00746       AST_FORMAT_G729A,
00747       /*! Down to G.723.1 which is proprietary but at least designed for voice */
00748       AST_FORMAT_G723_1,
00749    };
00750 
00751    /* Strip out video */
00752    fmts &= AST_FORMAT_AUDIO_MASK;
00753    
00754    /* Find the first preferred codec in the format given */
00755    for (x = 0; x < ARRAY_LEN(prefs); x++) {
00756       if (fmts & prefs[x])
00757          return prefs[x];
00758    }
00759 
00760    ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
00761 
00762    return 0;
00763 }
00764 
00765 static const struct ast_channel_tech null_tech = {
00766    .type = "NULL",
00767    .description = "Null channel (should not see this)",
00768 };
00769 
00770 /*! \brief Create a new channel structure */
00771 static struct ast_channel * attribute_malloc __attribute__((format(printf, 12, 0)))
00772 __ast_channel_alloc_ap(int needqueue, int state, const char *cid_num, const char *cid_name,
00773              const char *acctcode, const char *exten, const char *context,
00774              const int amaflag, const char *file, int line, const char *function,
00775              const char *name_fmt, va_list ap1, va_list ap2)
00776 {
00777    struct ast_channel *tmp;
00778    int x;
00779    int flags;
00780    struct varshead *headp;
00781    char *tech = "";
00782 
00783    /* If shutting down, don't allocate any new channels */
00784    if (shutting_down) {
00785       ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
00786       return NULL;
00787    }
00788 
00789 #if defined(__AST_DEBUG_MALLOC)
00790    if (!(tmp = __ast_calloc(1, sizeof(*tmp), file, line, function))) {
00791       return NULL;
00792    }
00793 #else
00794    if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
00795       return NULL;
00796    }
00797 #endif
00798 
00799    if (!(tmp->sched = sched_context_create())) {
00800       ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
00801       ast_free(tmp);
00802       return NULL;
00803    }
00804    
00805    if ((ast_string_field_init(tmp, 128))) {
00806       sched_context_destroy(tmp->sched);
00807       ast_free(tmp);
00808       return NULL;
00809    }
00810 
00811 #ifdef HAVE_EPOLL
00812    tmp->epfd = epoll_create(25);
00813 #endif
00814 
00815    for (x = 0; x < AST_MAX_FDS; x++) {
00816       tmp->fds[x] = -1;
00817 #ifdef HAVE_EPOLL
00818       tmp->epfd_data[x] = NULL;
00819 #endif
00820    }
00821 
00822    if ((tmp->timer = ast_timer_open())) {
00823       needqueue = 0;
00824       tmp->timingfd = ast_timer_fd(tmp->timer);
00825    } else {
00826       tmp->timingfd = -1;
00827    }
00828 
00829    if (needqueue) {
00830       if (pipe(tmp->alertpipe)) {
00831          ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe! Try increasing max file descriptors with ulimit -n\n");
00832 alertpipe_failed:
00833          if (tmp->timer) {
00834             ast_timer_close(tmp->timer);
00835          }
00836 
00837          sched_context_destroy(tmp->sched);
00838          ast_string_field_free_memory(tmp);
00839          ast_free(tmp);
00840          return NULL;
00841       } else {
00842          flags = fcntl(tmp->alertpipe[0], F_GETFL);
00843          if (fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
00844             ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
00845             close(tmp->alertpipe[0]);
00846             close(tmp->alertpipe[1]);
00847             goto alertpipe_failed;
00848          }
00849          flags = fcntl(tmp->alertpipe[1], F_GETFL);
00850          if (fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
00851             ast_log(LOG_WARNING, "Channel allocation failed: Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
00852             close(tmp->alertpipe[0]);
00853             close(tmp->alertpipe[1]);
00854             goto alertpipe_failed;
00855          }
00856       }
00857    } else   /* Make sure we've got it done right if they don't */
00858       tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
00859 
00860    /* Always watch the alertpipe */
00861    ast_channel_set_fd(tmp, AST_ALERT_FD, tmp->alertpipe[0]);
00862    /* And timing pipe */
00863    ast_channel_set_fd(tmp, AST_TIMING_FD, tmp->timingfd);
00864    ast_string_field_set(tmp, name, "**Unknown**");
00865 
00866    /* Initial state */
00867    tmp->_state = state;
00868 
00869    tmp->streamid = -1;
00870    
00871    tmp->fin = global_fin;
00872    tmp->fout = global_fout;
00873 
00874    if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
00875       ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
00876                    ast_atomic_fetchadd_int(&uniqueint, 1));
00877    } else {
00878       ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
00879                    (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
00880    }
00881 
00882    tmp->cid.cid_name = ast_strdup(cid_name);
00883    tmp->cid.cid_num = ast_strdup(cid_num);
00884    
00885    if (!ast_strlen_zero(name_fmt)) {
00886       char *slash;
00887       /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
00888        * And they all use slightly different formats for their name string.
00889        * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
00890        * This means, that the stringfields must have a routine that takes the va_lists directly, and 
00891        * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
00892        * This new function was written so this can be accomplished.
00893        */
00894       ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
00895       tech = ast_strdupa(tmp->name);
00896       if ((slash = strchr(tech, '/'))) {
00897          *slash = '\0';
00898       }
00899    }
00900 
00901    /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
00902 
00903    /* These 4 variables need to be set up for the cdr_init() to work right */
00904    if (amaflag)
00905       tmp->amaflags = amaflag;
00906    else
00907       tmp->amaflags = ast_default_amaflags;
00908    
00909    if (!ast_strlen_zero(acctcode))
00910       ast_string_field_set(tmp, accountcode, acctcode);
00911    else
00912       ast_string_field_set(tmp, accountcode, ast_default_accountcode);
00913       
00914    if (!ast_strlen_zero(context))
00915       ast_copy_string(tmp->context, context, sizeof(tmp->context));
00916    else
00917       strcpy(tmp->context, "default");
00918 
00919    if (!ast_strlen_zero(exten))
00920       ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
00921    else
00922       strcpy(tmp->exten, "s");
00923 
00924    tmp->priority = 1;
00925       
00926    tmp->cdr = ast_cdr_alloc();
00927    ast_cdr_init(tmp->cdr, tmp);
00928    ast_cdr_start(tmp->cdr);
00929    
00930    headp = &tmp->varshead;
00931    AST_LIST_HEAD_INIT_NOLOCK(headp);
00932    
00933    ast_mutex_init(&tmp->lock_dont_use);
00934    
00935    AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
00936    
00937    ast_string_field_set(tmp, language, defaultlanguage);
00938 
00939    tmp->tech = &null_tech;
00940 
00941    ast_set_flag(tmp, AST_FLAG_IN_CHANNEL_LIST);
00942 
00943    AST_RWLIST_WRLOCK(&channels);
00944    AST_RWLIST_INSERT_HEAD(&channels, tmp, chan_list);
00945    AST_RWLIST_UNLOCK(&channels);
00946 
00947    /*\!note
00948     * and now, since the channel structure is built, and has its name, let's
00949     * call the manager event generator with this Newchannel event. This is the
00950     * proper and correct place to make this call, but you sure do have to pass
00951     * a lot of data into this func to do it here!
00952     */
00953    if (ast_get_channel_tech(tech)) {
00954       manager_event(EVENT_FLAG_CALL, "Newchannel",
00955          "Channel: %s\r\n"
00956          "ChannelState: %d\r\n"
00957          "ChannelStateDesc: %s\r\n"
00958          "CallerIDNum: %s\r\n"
00959          "CallerIDName: %s\r\n"
00960          "AccountCode: %s\r\n"
00961          "Exten: %s\r\n"
00962          "Context: %s\r\n"
00963          "Uniqueid: %s\r\n",
00964          tmp->name, 
00965          state, 
00966          ast_state2str(state),
00967          S_OR(cid_num, ""),
00968          S_OR(cid_name, ""),
00969          tmp->accountcode,
00970          S_OR(exten, ""),
00971          S_OR(context, ""),
00972          tmp->uniqueid);
00973    }
00974 
00975    return tmp;
00976 }
00977 
00978 struct ast_channel *__ast_channel_alloc(int needqueue, int state, const char *cid_num,
00979                const char *cid_name, const char *acctcode,
00980                const char *exten, const char *context,
00981                const int amaflag, const char *file, int line,
00982                const char *function, const char *name_fmt, ...)
00983 {
00984    va_list ap1, ap2;
00985    struct ast_channel *result;
00986 
00987    va_start(ap1, name_fmt);
00988    va_start(ap2, name_fmt);
00989    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
00990                amaflag, file, line, function, name_fmt, ap1, ap2);
00991    va_end(ap1);
00992    va_end(ap2);
00993 
00994    return result;
00995 }
00996 
00997 static int __ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int head, struct ast_frame *after)
00998 {
00999    struct ast_frame *f;
01000    struct ast_frame *cur;
01001    int blah = 1;
01002    unsigned int new_frames = 0;
01003    unsigned int new_voice_frames = 0;
01004    unsigned int queued_frames = 0;
01005    unsigned int queued_voice_frames = 0;
01006    AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
01007 
01008    ast_channel_lock(chan);
01009 
01010    /* See if the last frame on the queue is a hangup, if so don't queue anything */
01011    if ((cur = AST_LIST_LAST(&chan->readq)) &&
01012        (cur->frametype == AST_FRAME_CONTROL) &&
01013        (cur->subclass == AST_CONTROL_HANGUP)) {
01014       ast_channel_unlock(chan);
01015       return 0;
01016    }
01017 
01018    /* Build copies of all the frames and count them */
01019    AST_LIST_HEAD_INIT_NOLOCK(&frames);
01020    for (cur = fin; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
01021       if (!(f = ast_frdup(cur))) {
01022          ast_frfree(AST_LIST_FIRST(&frames));
01023          ast_channel_unlock(chan);
01024          return -1;
01025       }
01026 
01027       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01028       new_frames++;
01029       if (f->frametype == AST_FRAME_VOICE) {
01030          new_voice_frames++;
01031       }
01032    }
01033 
01034    /* Count how many frames exist on the queue */
01035    AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
01036       queued_frames++;
01037       if (cur->frametype == AST_FRAME_VOICE) {
01038          queued_voice_frames++;
01039       }
01040    }
01041 
01042    if ((queued_frames + new_frames > 128 || queued_voice_frames + new_voice_frames > 96)) {
01043       int count = 0;
01044       ast_log(LOG_WARNING, "Exceptionally long %squeue length queuing to %s\n", queued_frames + new_frames > 128 ? "" : "voice ", chan->name);
01045       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, cur, frame_list) {
01046          /* Save the most recent frame */
01047          if (!AST_LIST_NEXT(cur, frame_list)) {
01048             break;
01049          } else if (cur->frametype == AST_FRAME_VOICE || cur->frametype == AST_FRAME_VIDEO || cur->frametype == AST_FRAME_NULL) {
01050             if (++count > 64) {
01051                break;
01052             }
01053             AST_LIST_REMOVE_CURRENT(frame_list);
01054             ast_frfree(cur);
01055          }
01056       }
01057       AST_LIST_TRAVERSE_SAFE_END;
01058    }
01059 
01060    if (after) {
01061       AST_LIST_INSERT_LIST_AFTER(&chan->readq, &frames, after, frame_list);
01062    } else {
01063       if (head) {
01064          AST_LIST_APPEND_LIST(&frames, &chan->readq, frame_list);
01065          AST_LIST_HEAD_INIT_NOLOCK(&chan->readq);
01066       }
01067       AST_LIST_APPEND_LIST(&chan->readq, &frames, frame_list);
01068    }
01069 
01070    if (chan->alertpipe[1] > -1) {
01071       if (write(chan->alertpipe[1], &blah, new_frames * sizeof(blah)) != (new_frames * sizeof(blah))) {
01072          ast_log(LOG_WARNING, "Unable to write to alert pipe on %s (qlen = %d): %s!\n",
01073             chan->name, queued_frames, strerror(errno));
01074       }
01075    } else if (chan->timingfd > -1) {
01076       ast_timer_enable_continuous(chan->timer);
01077    } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
01078       pthread_kill(chan->blocker, SIGURG);
01079    }
01080 
01081    ast_channel_unlock(chan);
01082 
01083    return 0;
01084 }
01085 
01086 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
01087 {
01088    return __ast_queue_frame(chan, fin, 0, NULL);
01089 }
01090 
01091 int ast_queue_frame_head(struct ast_channel *chan, struct ast_frame *fin)
01092 {
01093    return __ast_queue_frame(chan, fin, 1, NULL);
01094 }
01095 
01096 /*! \brief Queue a hangup frame for channel */
01097 int ast_queue_hangup(struct ast_channel *chan)
01098 {
01099    struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
01100    /* Yeah, let's not change a lock-critical value without locking */
01101    if (!ast_channel_trylock(chan)) {
01102       chan->_softhangup |= AST_SOFTHANGUP_DEV;
01103       ast_channel_unlock(chan);
01104    }
01105    return ast_queue_frame(chan, &f);
01106 }
01107 
01108 /*! \brief Queue a hangup frame for channel */
01109 int ast_queue_hangup_with_cause(struct ast_channel *chan, int cause)
01110 {
01111    struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
01112 
01113    if (cause >= 0)
01114       f.data.uint32 = cause;
01115 
01116    /* Yeah, let's not change a lock-critical value without locking */
01117    if (!ast_channel_trylock(chan)) {
01118       chan->_softhangup |= AST_SOFTHANGUP_DEV;
01119       if (cause < 0)
01120          f.data.uint32 = chan->hangupcause;
01121 
01122       ast_channel_unlock(chan);
01123    }
01124 
01125    return ast_queue_frame(chan, &f);
01126 }
01127 
01128 /*! \brief Queue a control frame */
01129 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
01130 {
01131    struct ast_frame f = { AST_FRAME_CONTROL, };
01132 
01133    f.subclass = control;
01134 
01135    return ast_queue_frame(chan, &f);
01136 }
01137 
01138 /*! \brief Queue a control frame with payload */
01139 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
01140             const void *data, size_t datalen)
01141 {
01142    struct ast_frame f = { AST_FRAME_CONTROL, };
01143 
01144    f.subclass = control;
01145    f.data.ptr = (void *) data;
01146    f.datalen = datalen;
01147 
01148    return ast_queue_frame(chan, &f);
01149 }
01150 
01151 /*! \brief Set defer DTMF flag on channel */
01152 int ast_channel_defer_dtmf(struct ast_channel *chan)
01153 {
01154    int pre = 0;
01155 
01156    if (chan) {
01157       pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
01158       ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
01159    }
01160    return pre;
01161 }
01162 
01163 /*! \brief Unset defer DTMF flag on channel */
01164 void ast_channel_undefer_dtmf(struct ast_channel *chan)
01165 {
01166    if (chan)
01167       ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
01168 }
01169 
01170 /*!
01171  * \brief Helper function to find channels.
01172  *
01173  * It supports these modes:
01174  *
01175  * prev != NULL : get channel next in list after prev
01176  * name != NULL : get channel with matching name
01177  * name != NULL && namelen != 0 : get channel whose name starts with prefix
01178  * exten != NULL : get channel whose exten or macroexten matches
01179  * context != NULL && exten != NULL : get channel whose context or macrocontext
01180  *
01181  * It returns with the channel's lock held. If getting the individual lock fails,
01182  * unlock and retry quickly up to 10 times, then give up.
01183  *
01184  * \note XXX Note that this code has cost O(N) because of the need to verify
01185  * that the object is still on the global list.
01186  *
01187  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
01188  * can only be done with the lock held or someone could delete the
01189  * object while we work on it. This causes some ugliness in the code.
01190  * Note that removing the first ast_log() may be harmful, as it would
01191  * shorten the retry period and possibly cause failures.
01192  * We should definitely go for a better scheme that is deadlock-free.
01193  */
01194 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
01195                       const char *name, const int namelen,
01196                       const char *context, const char *exten)
01197 {
01198    const char *msg = prev ? "deadlock" : "initial deadlock";
01199    int retries;
01200    struct ast_channel *c;
01201    const struct ast_channel *_prev = prev;
01202 
01203    for (retries = 0; retries < 200; retries++) {
01204       int done;
01205       /* Reset prev on each retry.  See note below for the reason. */
01206       prev = _prev;
01207       AST_RWLIST_RDLOCK(&channels);
01208       AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
01209          if (prev) { /* look for last item, first, before any evaluation */
01210             if (c != prev) /* not this one */
01211                continue;
01212             /* found, prepare to return c->next */
01213             if ((c = AST_RWLIST_NEXT(c, chan_list)) == NULL) break;
01214             /*!\note
01215              * We're done searching through the list for the previous item.
01216              * Any item after this point, we want to evaluate for a match.
01217              * If we didn't set prev to NULL here, then we would only
01218              * return matches for the first matching item (since the above
01219              * "if (c != prev)" would not permit any other potential
01220              * matches to reach the additional matching logic, below).
01221              * Instead, it would just iterate until it once again found the
01222              * original match, then iterate down to the end of the list and
01223              * quit.
01224              */
01225             prev = NULL;
01226          }
01227          if (name) { /* want match by name */
01228             if ((!namelen && strcasecmp(c->name, name) && strcmp(c->uniqueid, name)) ||
01229                 (namelen && strncasecmp(c->name, name, namelen)))
01230                continue;   /* name match failed */
01231          } else if (exten) {
01232             if (context && strcasecmp(c->context, context) &&
01233                 strcasecmp(c->macrocontext, context))
01234                continue;   /* context match failed */
01235             if (strcasecmp(c->exten, exten) &&
01236                 strcasecmp(c->macroexten, exten))
01237                continue;   /* exten match failed */
01238          }
01239          /* if we get here, c points to the desired record */
01240          break;
01241       }
01242       /* exit if chan not found or mutex acquired successfully */
01243       /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
01244       done = c == NULL || ast_channel_trylock(c) == 0;
01245       if (!done) {
01246          ast_debug(1, "Avoiding %s for channel '%p'\n", msg, c);
01247          if (retries == 199) {
01248             /* We are about to fail due to a deadlock, so report this
01249              * while we still have the list lock.
01250              */
01251             ast_debug(1, "Failure, could not lock '%p' after %d retries!\n", c, retries);
01252             /* As we have deadlocked, we will skip this channel and
01253              * see if there is another match.
01254              * NOTE: No point doing this for a full-name match,
01255              * as there can be no more matches.
01256              */
01257             if (!(name && !namelen)) {
01258                prev = c;
01259                retries = -1;
01260             }
01261          }
01262       }
01263       AST_RWLIST_UNLOCK(&channels);
01264       if (done)
01265          return c;
01266       /* If we reach this point we basically tried to lock a channel and failed. Instead of
01267        * starting from the beginning of the list we can restore our saved pointer to the previous
01268        * channel and start from there.
01269        */
01270       prev = _prev;
01271       usleep(1);  /* give other threads a chance before retrying */
01272    }
01273 
01274    return NULL;
01275 }
01276 
01277 /*! \brief Browse channels in use */
01278 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
01279 {
01280    return channel_find_locked(prev, NULL, 0, NULL, NULL);
01281 }
01282 
01283 /*! \brief Get channel by name and lock it */
01284 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
01285 {
01286    return channel_find_locked(NULL, name, 0, NULL, NULL);
01287 }
01288 
01289 /*! \brief Get channel by name prefix and lock it */
01290 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
01291 {
01292    return channel_find_locked(NULL, name, namelen, NULL, NULL);
01293 }
01294 
01295 /*! \brief Get next channel by name prefix and lock it */
01296 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
01297                         const int namelen)
01298 {
01299    return channel_find_locked(chan, name, namelen, NULL, NULL);
01300 }
01301 
01302 /*! \brief Get channel by exten (and optionally context) and lock it */
01303 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
01304 {
01305    return channel_find_locked(NULL, NULL, 0, context, exten);
01306 }
01307 
01308 /*! \brief Get next channel by exten (and optionally context) and lock it */
01309 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
01310                        const char *context)
01311 {
01312    return channel_find_locked(chan, NULL, 0, context, exten);
01313 }
01314 
01315 /*! \brief Search for a channel based on the passed channel matching callback (first match) and return it, locked */
01316 struct ast_channel *ast_channel_search_locked(int (*is_match)(struct ast_channel *, void *), void *data)
01317 {
01318    struct ast_channel *c = NULL;
01319 
01320    AST_RWLIST_RDLOCK(&channels);
01321    AST_RWLIST_TRAVERSE(&channels, c, chan_list) {
01322       ast_channel_lock(c);
01323       if (is_match(c, data)) {
01324          break;
01325       }
01326       ast_channel_unlock(c);
01327    }
01328    AST_RWLIST_UNLOCK(&channels);
01329 
01330    return c;
01331 }
01332 
01333 /*! \brief Wait, look for hangups and condition arg */
01334 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
01335 {
01336    struct ast_frame *f;
01337    struct ast_silence_generator *silgen = NULL;
01338    int res = 0;
01339 
01340    /* If no other generator is present, start silencegen while waiting */
01341    if (ast_opt_transmit_silence && !chan->generatordata) {
01342       silgen = ast_channel_start_silence_generator(chan);
01343    }
01344 
01345    while (ms > 0) {
01346       if (cond && ((*cond)(data) == 0)) {
01347          break;
01348       }
01349       ms = ast_waitfor(chan, ms);
01350       if (ms < 0) {
01351          res = -1;
01352          break;
01353       }
01354       if (ms > 0) {
01355          f = ast_read(chan);
01356          if (!f) {
01357             res = -1;
01358             break;
01359          }
01360          ast_frfree(f);
01361       }
01362    }
01363 
01364    /* stop silgen if present */
01365    if (silgen) {
01366       ast_channel_stop_silence_generator(chan, silgen);
01367    }
01368 
01369    return res;
01370 }
01371 
01372 /*! \brief Wait, look for hangups */
01373 int ast_safe_sleep(struct ast_channel *chan, int ms)
01374 {
01375    return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
01376 }
01377 
01378 static void free_cid(struct ast_callerid *cid)
01379 {
01380    if (cid->cid_dnid)
01381       ast_free(cid->cid_dnid);
01382    if (cid->cid_num)
01383       ast_free(cid->cid_num); 
01384    if (cid->cid_name)
01385       ast_free(cid->cid_name);   
01386    if (cid->cid_ani)
01387       ast_free(cid->cid_ani);
01388    if (cid->cid_rdnis)
01389       ast_free(cid->cid_rdnis);
01390    cid->cid_dnid = cid->cid_num = cid->cid_name = cid->cid_ani = cid->cid_rdnis = NULL;
01391 }
01392 
01393 /*! \brief Free a channel structure */
01394 void ast_channel_free(struct ast_channel *chan)
01395 {
01396    int fd;
01397 #ifdef HAVE_EPOLL
01398    int i;
01399 #endif
01400    struct ast_var_t *vardata;
01401    struct ast_frame *f;
01402    struct varshead *headp;
01403    struct ast_datastore *datastore = NULL;
01404    char name[AST_CHANNEL_NAME], *dashptr;
01405    int inlist;
01406    
01407    headp=&chan->varshead;
01408    
01409    inlist = ast_test_flag(chan, AST_FLAG_IN_CHANNEL_LIST);
01410    if (inlist) {
01411       AST_RWLIST_WRLOCK(&channels);
01412       if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
01413          ast_debug(1, "Unable to find channel in list to free. Assuming it has already been done.\n");
01414       }
01415       /* Lock and unlock the channel just to be sure nobody has it locked still
01416          due to a reference retrieved from the channel list. */
01417       ast_channel_lock(chan);
01418       ast_channel_unlock(chan);
01419    }
01420 
01421    /* Get rid of each of the data stores on the channel */
01422    ast_channel_lock(chan);
01423    while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
01424       /* Free the data store */
01425       ast_datastore_free(datastore);
01426    ast_channel_unlock(chan);
01427 
01428    /* Lock and unlock the channel just to be sure nobody has it locked still
01429       due to a reference that was stored in a datastore. (i.e. app_chanspy) */
01430    ast_channel_lock(chan);
01431    ast_channel_unlock(chan);
01432 
01433    if (chan->tech_pvt) {
01434       ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
01435       ast_free(chan->tech_pvt);
01436    }
01437 
01438    if (chan->sched)
01439       sched_context_destroy(chan->sched);
01440 
01441    ast_copy_string(name, chan->name, sizeof(name));
01442    if ((dashptr = strrchr(name, '-'))) {
01443       *dashptr = '\0';
01444    }
01445 
01446    /* Stop monitoring */
01447    if (chan->monitor)
01448       chan->monitor->stop( chan, 0 );
01449 
01450    /* If there is native format music-on-hold state, free it */
01451    if (chan->music_state)
01452       ast_moh_cleanup(chan);
01453 
01454    /* Free translators */
01455    if (chan->readtrans)
01456       ast_translator_free_path(chan->readtrans);
01457    if (chan->writetrans)
01458       ast_translator_free_path(chan->writetrans);
01459    if (chan->pbx)
01460       ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
01461    free_cid(&chan->cid);
01462    /* Close pipes if appropriate */
01463    if ((fd = chan->alertpipe[0]) > -1)
01464       close(fd);
01465    if ((fd = chan->alertpipe[1]) > -1)
01466       close(fd);
01467    if (chan->timer) {
01468       ast_timer_close(chan->timer);
01469    }
01470 #ifdef HAVE_EPOLL
01471    for (i = 0; i < AST_MAX_FDS; i++) {
01472       if (chan->epfd_data[i])
01473          free(chan->epfd_data[i]);
01474    }
01475    close(chan->epfd);
01476 #endif
01477    while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
01478       ast_frfree(f);
01479    
01480    /* loop over the variables list, freeing all data and deleting list items */
01481    /* no need to lock the list, as the channel is already locked */
01482    
01483    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
01484       ast_var_delete(vardata);
01485 
01486    ast_app_group_discard(chan);
01487 
01488    /* Destroy the jitterbuffer */
01489    ast_jb_destroy(chan);
01490 
01491    if (chan->cdr) {
01492       ast_cdr_discard(chan->cdr);
01493       chan->cdr = NULL;
01494    }
01495 
01496    if (chan->zone) {
01497       chan->zone = ast_tone_zone_unref(chan->zone);
01498    }
01499 
01500    ast_mutex_destroy(&chan->lock_dont_use);
01501 
01502    ast_string_field_free_memory(chan);
01503    ast_free(chan);
01504    if (inlist)
01505       AST_RWLIST_UNLOCK(&channels);
01506 
01507    /* Queue an unknown state, because, while we know that this particular
01508     * instance is dead, we don't know the state of all other possible
01509     * instances. */
01510    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
01511 }
01512 
01513 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, const char *uid)
01514 {
01515    return ast_datastore_alloc(info, uid);
01516 }
01517 
01518 int ast_channel_datastore_free(struct ast_datastore *datastore)
01519 {
01520    return ast_datastore_free(datastore);
01521 }
01522 
01523 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
01524 {
01525    struct ast_datastore *datastore = NULL, *datastore2;
01526 
01527    AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
01528       if (datastore->inheritance > 0) {
01529          datastore2 = ast_datastore_alloc(datastore->info, datastore->uid);
01530          if (datastore2) {
01531             datastore2->data = datastore->info->duplicate ? datastore->info->duplicate(datastore->data) : NULL;
01532             datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
01533             AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
01534          }
01535       }
01536    }
01537    return 0;
01538 }
01539 
01540 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
01541 {
01542    int res = 0;
01543 
01544    AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
01545 
01546    return res;
01547 }
01548 
01549 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
01550 {
01551    return AST_LIST_REMOVE(&chan->datastores, datastore, entry) ? 0 : -1;
01552 }
01553 
01554 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
01555 {
01556    struct ast_datastore *datastore = NULL;
01557    
01558    if (info == NULL)
01559       return NULL;
01560 
01561    AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
01562       if (datastore->info != info) {
01563          continue;
01564       }
01565 
01566       if (uid == NULL) {
01567          /* matched by type only */
01568          break;
01569       }
01570 
01571       if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
01572          /* Matched by type AND uid */
01573          break;
01574       }
01575    }
01576    AST_LIST_TRAVERSE_SAFE_END;
01577 
01578    return datastore;
01579 }
01580 
01581 /*! Set the file descriptor on the channel */
01582 void ast_channel_set_fd(struct ast_channel *chan, int which, int fd)
01583 {
01584 #ifdef HAVE_EPOLL
01585    struct epoll_event ev;
01586    struct ast_epoll_data *aed = NULL;
01587 
01588    if (chan->fds[which] > -1) {
01589       epoll_ctl(chan->epfd, EPOLL_CTL_DEL, chan->fds[which], &ev);
01590       aed = chan->epfd_data[which];
01591    }
01592 
01593    /* If this new fd is valid, add it to the epoll */
01594    if (fd > -1) {
01595       if (!aed && (!(aed = ast_calloc(1, sizeof(*aed)))))
01596          return;
01597       
01598       chan->epfd_data[which] = aed;
01599       aed->chan = chan;
01600       aed->which = which;
01601       
01602       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
01603       ev.data.ptr = aed;
01604       epoll_ctl(chan->epfd, EPOLL_CTL_ADD, fd, &ev);
01605    } else if (aed) {
01606       /* We don't have to keep around this epoll data structure now */
01607       free(aed);
01608       chan->epfd_data[which] = NULL;
01609    }
01610 #endif
01611    chan->fds[which] = fd;
01612    return;
01613 }
01614 
01615 /*! Add a channel to an optimized waitfor */
01616 void ast_poll_channel_add(struct ast_channel *chan0, struct ast_channel *chan1)
01617 {
01618 #ifdef HAVE_EPOLL
01619    struct epoll_event ev;
01620    int i = 0;
01621 
01622    if (chan0->epfd == -1)
01623       return;
01624 
01625    /* Iterate through the file descriptors on chan1, adding them to chan0 */
01626    for (i = 0; i < AST_MAX_FDS; i++) {
01627       if (chan1->fds[i] == -1)
01628          continue;
01629       ev.events = EPOLLIN | EPOLLPRI | EPOLLERR | EPOLLHUP;
01630       ev.data.ptr = chan1->epfd_data[i];
01631       epoll_ctl(chan0->epfd, EPOLL_CTL_ADD, chan1->fds[i], &ev);
01632    }
01633 
01634 #endif
01635    return;
01636 }
01637 
01638 /*! Delete a channel from an optimized waitfor */
01639 void ast_poll_channel_del(struct ast_channel *chan0, struct ast_channel *chan1)
01640 {
01641 #ifdef HAVE_EPOLL
01642    struct epoll_event ev;
01643    int i = 0;
01644 
01645    if (chan0->epfd == -1)
01646       return;
01647 
01648    for (i = 0; i < AST_MAX_FDS; i++) {
01649       if (chan1->fds[i] == -1)
01650          continue;
01651       epoll_ctl(chan0->epfd, EPOLL_CTL_DEL, chan1->fds[i], &ev);
01652    }
01653 
01654 #endif
01655    return;
01656 }
01657 
01658 /*! \brief Softly hangup a channel, don't lock */
01659 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
01660 {
01661    ast_debug(1, "Soft-Hanging up channel '%s'\n", chan->name);
01662    /* Inform channel driver that we need to be hung up, if it cares */
01663    chan->_softhangup |= cause;
01664    ast_queue_frame(chan, &ast_null_frame);
01665    /* Interrupt any poll call or such */
01666    if (ast_test_flag(chan, AST_FLAG_BLOCKING))
01667       pthread_kill(chan->blocker, SIGURG);
01668    return 0;
01669 }
01670 
01671 /*! \brief Softly hangup a channel, lock */
01672 int ast_softhangup(struct ast_channel *chan, int cause)
01673 {
01674    int res;
01675 
01676    ast_channel_lock(chan);
01677    res = ast_softhangup_nolock(chan, cause);
01678    ast_channel_unlock(chan);
01679 
01680    return res;
01681 }
01682 
01683 static void free_translation(struct ast_channel *clonechan)
01684 {
01685    if (clonechan->writetrans)
01686       ast_translator_free_path(clonechan->writetrans);
01687    if (clonechan->readtrans)
01688       ast_translator_free_path(clonechan->readtrans);
01689    clonechan->writetrans = NULL;
01690    clonechan->readtrans = NULL;
01691    clonechan->rawwriteformat = clonechan->nativeformats;
01692    clonechan->rawreadformat = clonechan->nativeformats;
01693 }
01694 
01695 /*! \brief Hangup a channel */
01696 int ast_hangup(struct ast_channel *chan)
01697 {
01698    int res = 0;
01699 
01700    /* Don't actually hang up a channel that will masquerade as someone else, or
01701       if someone is going to masquerade as us */
01702    ast_channel_lock(chan);
01703 
01704    if (chan->audiohooks) {
01705       ast_audiohook_detach_list(chan->audiohooks);
01706       chan->audiohooks = NULL;
01707    }
01708 
01709    ast_autoservice_stop(chan);
01710 
01711    if (chan->masq) {
01712       if (ast_do_masquerade(chan))
01713          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
01714    }
01715 
01716    if (chan->masq) {
01717       ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
01718       ast_channel_unlock(chan);
01719       return 0;
01720    }
01721    /* If this channel is one which will be masqueraded into something,
01722       mark it as a zombie already, so we know to free it later */
01723    if (chan->masqr) {
01724       ast_set_flag(chan, AST_FLAG_ZOMBIE);
01725       ast_channel_unlock(chan);
01726       return 0;
01727    }
01728    ast_channel_unlock(chan);
01729 
01730    AST_RWLIST_WRLOCK(&channels);
01731    if (!AST_RWLIST_REMOVE(&channels, chan, chan_list)) {
01732       ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
01733    }
01734    ast_clear_flag(chan, AST_FLAG_IN_CHANNEL_LIST);
01735    AST_RWLIST_UNLOCK(&channels);
01736 
01737    ast_channel_lock(chan);
01738    free_translation(chan);
01739    /* Close audio stream */
01740    if (chan->stream) {
01741       ast_closestream(chan->stream);
01742       chan->stream = NULL;
01743    }
01744    /* Close video stream */
01745    if (chan->vstream) {
01746       ast_closestream(chan->vstream);
01747       chan->vstream = NULL;
01748    }
01749    if (chan->sched) {
01750       sched_context_destroy(chan->sched);
01751       chan->sched = NULL;
01752    }
01753    
01754    if (chan->generatordata)   /* Clear any tone stuff remaining */
01755       if (chan->generator && chan->generator->release)
01756          chan->generator->release(chan, chan->generatordata);
01757    chan->generatordata = NULL;
01758    chan->generator = NULL;
01759    if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
01760       ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
01761                "is blocked by thread %ld in procedure %s!  Expect a failure\n",
01762                (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
01763       ast_assert(ast_test_flag(chan, AST_FLAG_BLOCKING) == 0);
01764    }
01765    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
01766       ast_debug(1, "Hanging up channel '%s'\n", chan->name);
01767       if (chan->tech->hangup)
01768          res = chan->tech->hangup(chan);
01769    } else {
01770       ast_debug(1, "Hanging up zombie '%s'\n", chan->name);
01771    }
01772          
01773    ast_channel_unlock(chan);
01774    manager_event(EVENT_FLAG_CALL, "Hangup",
01775          "Channel: %s\r\n"
01776          "Uniqueid: %s\r\n"
01777          "CallerIDNum: %s\r\n"
01778          "CallerIDName: %s\r\n"
01779          "Cause: %d\r\n"
01780          "Cause-txt: %s\r\n",
01781          chan->name,
01782          chan->uniqueid,
01783          S_OR(chan->cid.cid_num, "<unknown>"),
01784          S_OR(chan->cid.cid_name, "<unknown>"),
01785          chan->hangupcause,
01786          ast_cause2str(chan->hangupcause)
01787          );
01788 
01789    if (chan->cdr && !ast_test_flag(chan->cdr, AST_CDR_FLAG_BRIDGED) && 
01790       !ast_test_flag(chan->cdr, AST_CDR_FLAG_POST_DISABLED) && 
01791        (chan->cdr->disposition != AST_CDR_NULL || ast_test_flag(chan->cdr, AST_CDR_FLAG_DIALED))) {
01792       ast_channel_lock(chan);
01793          
01794       ast_cdr_end(chan->cdr);
01795       ast_cdr_detach(chan->cdr);
01796       chan->cdr = NULL;
01797       ast_channel_unlock(chan);
01798    }
01799    
01800    ast_channel_free(chan);
01801 
01802    return res;
01803 }
01804 
01805 int ast_raw_answer(struct ast_channel *chan, int cdr_answer)
01806 {
01807    int res = 0;
01808 
01809    ast_channel_lock(chan);
01810 
01811    /* You can't answer an outbound call */
01812    if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
01813       ast_channel_unlock(chan);
01814       return 0;
01815    }
01816 
01817    /* Stop if we're a zombie or need a soft hangup */
01818    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
01819       ast_channel_unlock(chan);
01820       return -1;
01821    }
01822 
01823    ast_channel_unlock(chan);
01824 
01825    switch (chan->_state) {
01826    case AST_STATE_RINGING:
01827    case AST_STATE_RING:
01828       ast_channel_lock(chan);
01829       if (chan->tech->answer) {
01830          res = chan->tech->answer(chan);
01831       }
01832       ast_setstate(chan, AST_STATE_UP);
01833       if (cdr_answer) {
01834          ast_cdr_answer(chan->cdr);
01835       }
01836       ast_channel_unlock(chan);
01837       break;
01838    case AST_STATE_UP:
01839       /* Calling ast_cdr_answer when it it has previously been called
01840        * is essentially a no-op, so it is safe.
01841        */
01842       if (cdr_answer) {
01843          ast_cdr_answer(chan->cdr);
01844       }
01845       break;
01846    default:
01847       break;
01848    }
01849 
01850    ast_indicate(chan, -1);
01851    chan->visible_indication = 0;
01852 
01853    return res;
01854 }
01855 
01856 int __ast_answer(struct ast_channel *chan, unsigned int delay, int cdr_answer)
01857 {
01858    int res = 0;
01859    enum ast_channel_state old_state;
01860 
01861    old_state = chan->_state;
01862    if ((res = ast_raw_answer(chan, cdr_answer))) {
01863       return res;
01864    }
01865 
01866    switch (old_state) {
01867    case AST_STATE_RINGING:
01868    case AST_STATE_RING:
01869       /* wait for media to start flowing, but don't wait any longer
01870        * than 'delay' or 500 milliseconds, whichever is longer
01871        */
01872       do {
01873          AST_LIST_HEAD_NOLOCK(, ast_frame) frames;
01874          struct ast_frame *cur, *new;
01875          int ms = MAX(delay, 500);
01876          unsigned int done = 0;
01877 
01878          AST_LIST_HEAD_INIT_NOLOCK(&frames);
01879 
01880          for (;;) {
01881             ms = ast_waitfor(chan, ms);
01882             if (ms < 0) {
01883                ast_log(LOG_WARNING, "Error condition occurred when polling channel %s for a voice frame: %s\n", chan->name, strerror(errno));
01884                res = -1;
01885                break;
01886             }
01887             if (ms == 0) {
01888                ast_debug(2, "Didn't receive a media frame from %s within %d ms of answering. Continuing anyway\n", chan->name, MAX(delay, 500));
01889                break;
01890             }
01891             cur = ast_read(chan);
01892             if (!cur || ((cur->frametype == AST_FRAME_CONTROL) &&
01893                     (cur->subclass == AST_CONTROL_HANGUP))) {
01894                if (cur) {
01895                   ast_frfree(cur);
01896                }
01897                res = -1;
01898                ast_debug(2, "Hangup of channel %s detected in answer routine\n", chan->name);
01899                break;
01900             }
01901 
01902             if ((new = ast_frisolate(cur)) != cur) {
01903                ast_frfree(cur);
01904             }
01905 
01906             AST_LIST_INSERT_HEAD(&frames, new, frame_list);
01907 
01908             /* if a specific delay period was requested, continue
01909              * until that delay has passed. don't stop just because
01910              * incoming media has arrived.
01911              */
01912             if (delay) {
01913                continue;
01914             }
01915 
01916             switch (new->frametype) {
01917                /* all of these frametypes qualify as 'media' */
01918             case AST_FRAME_VOICE:
01919             case AST_FRAME_VIDEO:
01920             case AST_FRAME_TEXT:
01921             case AST_FRAME_DTMF_BEGIN:
01922             case AST_FRAME_DTMF_END:
01923             case AST_FRAME_IMAGE:
01924             case AST_FRAME_HTML:
01925             case AST_FRAME_MODEM:
01926                done = 1;
01927                break;
01928             case AST_FRAME_CONTROL:
01929             case AST_FRAME_IAX:
01930             case AST_FRAME_NULL:
01931             case AST_FRAME_CNG:
01932                break;
01933             }
01934 
01935             if (done) {
01936                break;
01937             }
01938          }
01939 
01940          if (res == 0) {
01941             ast_channel_lock(chan);
01942             while ((cur = AST_LIST_REMOVE_HEAD(&frames, frame_list))) {
01943                ast_queue_frame_head(chan, cur);
01944                ast_frfree(cur);
01945             }
01946             ast_channel_unlock(chan);
01947          }
01948       } while (0);
01949       break;
01950    default:
01951       break;
01952    }
01953 
01954    return res;
01955 }
01956 
01957 int ast_answer(struct ast_channel *chan)
01958 {
01959    return __ast_answer(chan, 0, 1);
01960 }
01961 
01962 void ast_deactivate_generator(struct ast_channel *chan)
01963 {
01964    ast_channel_lock(chan);
01965    if (chan->generatordata) {
01966       if (chan->generator && chan->generator->release)
01967          chan->generator->release(chan, chan->generatordata);
01968       chan->generatordata = NULL;
01969       chan->generator = NULL;
01970       ast_channel_set_fd(chan, AST_GENERATOR_FD, -1);
01971       ast_clear_flag(chan, AST_FLAG_WRITE_INT);
01972       ast_settimeout(chan, 0, NULL, NULL);
01973    }
01974    ast_channel_unlock(chan);
01975 }
01976 
01977 static int generator_force(const void *data)
01978 {
01979    /* Called if generator doesn't have data */
01980    void *tmp;
01981    int res;
01982    int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
01983    struct ast_channel *chan = (struct ast_channel *)data;
01984 
01985    ast_channel_lock(chan);
01986    tmp = chan->generatordata;
01987    chan->generatordata = NULL;
01988    if (chan->generator)
01989       generate = chan->generator->generate;
01990    ast_channel_unlock(chan);
01991 
01992    if (!tmp || !generate)
01993       return 0;
01994 
01995    res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
01996 
01997    chan->generatordata = tmp;
01998 
01999    if (res) {
02000       ast_debug(1, "Auto-deactivating generator\n");
02001       ast_deactivate_generator(chan);
02002    }
02003 
02004    return 0;
02005 }
02006 
02007 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
02008 {
02009    int res = 0;
02010 
02011    ast_channel_lock(chan);
02012    if (chan->generatordata) {
02013       if (chan->generator && chan->generator->release)
02014          chan->generator->release(chan, chan->generatordata);
02015       chan->generatordata = NULL;
02016    }
02017    if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
02018       res = -1;
02019    }
02020    if (!res) {
02021       ast_settimeout(chan, 50, generator_force, chan);
02022       chan->generator = gen;
02023    }
02024    ast_channel_unlock(chan);
02025 
02026    ast_prod(chan);
02027 
02028    return res;
02029 }
02030 
02031 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02032 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
02033 {
02034    int winner = -1;
02035    ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
02036    return winner;
02037 }
02038 
02039 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
02040 #ifdef HAVE_EPOLL
02041 static struct ast_channel *ast_waitfor_nandfds_classic(struct ast_channel **c, int n, int *fds, int nfds,
02042                int *exception, int *outfd, int *ms)
02043 #else
02044 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
02045                int *exception, int *outfd, int *ms)
02046 #endif
02047 {
02048    struct timeval start = { 0 , 0 };
02049    struct pollfd *pfds = NULL;
02050    int res;
02051    long rms;
02052    int x, y, max;
02053    int sz;
02054    struct timeval now = { 0, 0 };
02055    struct timeval whentohangup = { 0, 0 }, diff;
02056    struct ast_channel *winner = NULL;
02057    struct fdmap {
02058       int chan;
02059       int fdno;
02060    } *fdmap = NULL;
02061 
02062    if ((sz = n * AST_MAX_FDS + nfds)) {
02063       pfds = alloca(sizeof(*pfds) * sz);
02064       fdmap = alloca(sizeof(*fdmap) * sz);
02065    }
02066 
02067    if (outfd)
02068       *outfd = -99999;
02069    if (exception)
02070       *exception = 0;
02071    
02072    /* Perform any pending masquerades */
02073    for (x = 0; x < n; x++) {
02074       ast_channel_lock(c[x]);
02075       if (c[x]->masq && ast_do_masquerade(c[x])) {
02076          ast_log(LOG_WARNING, "Masquerade failed\n");
02077          *ms = -1;
02078          ast_channel_unlock(c[x]);
02079          return NULL;
02080       }
02081       if (!ast_tvzero(c[x]->whentohangup)) {
02082          if (ast_tvzero(whentohangup))
02083             now = ast_tvnow();
02084          diff = ast_tvsub(c[x]->whentohangup, now);
02085          if (diff.tv_sec < 0 || ast_tvzero(diff)) {
02086             /* Should already be hungup */
02087             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02088             ast_channel_unlock(c[x]);
02089             return c[x];
02090          }
02091          if (ast_tvzero(whentohangup) || ast_tvcmp(diff, whentohangup) < 0)
02092             whentohangup = diff;
02093       }
02094       ast_channel_unlock(c[x]);
02095    }
02096    /* Wait full interval */
02097    rms = *ms;
02098    /* INT_MAX, not LONG_MAX, because it matters on 64-bit */
02099    if (!ast_tvzero(whentohangup) && whentohangup.tv_sec < INT_MAX / 1000) {
02100       rms = whentohangup.tv_sec * 1000 + whentohangup.tv_usec / 1000;              /* timeout in milliseconds */
02101       if (*ms >= 0 && *ms < rms) {                                                 /* original *ms still smaller */
02102          rms =  *ms;
02103       }
02104    } else if (!ast_tvzero(whentohangup) && rms < 0) {
02105       /* Tiny corner case... call would need to last >24 days */
02106       rms = INT_MAX;
02107    }
02108    /*
02109     * Build the pollfd array, putting the channels' fds first,
02110     * followed by individual fds. Order is important because
02111     * individual fd's must have priority over channel fds.
02112     */
02113    max = 0;
02114    for (x = 0; x < n; x++) {
02115       for (y = 0; y < AST_MAX_FDS; y++) {
02116          fdmap[max].fdno = y;  /* fd y is linked to this pfds */
02117          fdmap[max].chan = x;  /* channel x is linked to this pfds */
02118          max += ast_add_fd(&pfds[max], c[x]->fds[y]);
02119       }
02120       CHECK_BLOCKING(c[x]);
02121    }
02122    /* Add the individual fds */
02123    for (x = 0; x < nfds; x++) {
02124       fdmap[max].chan = -1;
02125       max += ast_add_fd(&pfds[max], fds[x]);
02126    }
02127 
02128    if (*ms > 0)
02129       start = ast_tvnow();
02130    
02131    if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
02132       do {
02133          int kbrms = rms;
02134          if (kbrms > 600000)
02135             kbrms = 600000;
02136          res = ast_poll(pfds, max, kbrms);
02137          if (!res)
02138             rms -= kbrms;
02139       } while (!res && (rms > 0));
02140    } else {
02141       res = ast_poll(pfds, max, rms);
02142    }
02143    for (x = 0; x < n; x++)
02144       ast_clear_flag(c[x], AST_FLAG_BLOCKING);
02145    if (res < 0) { /* Simulate a timeout if we were interrupted */
02146       if (errno != EINTR)
02147          *ms = -1;
02148       return NULL;
02149    }
02150    if (!ast_tvzero(whentohangup)) {   /* if we have a timeout, check who expired */
02151       now = ast_tvnow();
02152       for (x = 0; x < n; x++) {
02153          if (!ast_tvzero(c[x]->whentohangup) && ast_tvcmp(c[x]->whentohangup, now) <= 0) {
02154             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02155             if (winner == NULL)
02156                winner = c[x];
02157          }
02158       }
02159    }
02160    if (res == 0) { /* no fd ready, reset timeout and done */
02161       *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
02162       return winner;
02163    }
02164    /*
02165     * Then check if any channel or fd has a pending event.
02166     * Remember to check channels first and fds last, as they
02167     * must have priority on setting 'winner'
02168     */
02169    for (x = 0; x < max; x++) {
02170       res = pfds[x].revents;
02171       if (res == 0)
02172          continue;
02173       if (fdmap[x].chan >= 0) {  /* this is a channel */
02174          winner = c[fdmap[x].chan]; /* override previous winners */
02175          if (res & POLLPRI)
02176             ast_set_flag(winner, AST_FLAG_EXCEPTION);
02177          else
02178             ast_clear_flag(winner, AST_FLAG_EXCEPTION);
02179          winner->fdno = fdmap[x].fdno;
02180       } else {       /* this is an fd */
02181          if (outfd)
02182             *outfd = pfds[x].fd;
02183          if (exception)
02184             *exception = (res & POLLPRI) ? -1 : 0;
02185          winner = NULL;
02186       }
02187    }
02188    if (*ms > 0) {
02189       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
02190       if (*ms < 0)
02191          *ms = 0;
02192    }
02193    return winner;
02194 }
02195 
02196 #ifdef HAVE_EPOLL
02197 static struct ast_channel *ast_waitfor_nandfds_simple(struct ast_channel *chan, int *ms)
02198 {
02199    struct timeval start = { 0 , 0 };
02200    int res = 0;
02201    struct epoll_event ev[1];
02202    long diff, rms = *ms;
02203    struct ast_channel *winner = NULL;
02204    struct ast_epoll_data *aed = NULL;
02205 
02206    ast_channel_lock(chan);
02207 
02208    /* See if this channel needs to be masqueraded */
02209    if (chan->masq && ast_do_masquerade(chan)) {
02210       ast_log(LOG_WARNING, "Failed to perform masquerade on %s\n", chan->name);
02211       *ms = -1;
02212       ast_channel_unlock(chan);
02213       return NULL;
02214    }
02215 
02216    /* Figure out their timeout */
02217    if (!ast_tvzero(chan->whentohangup)) {
02218       if ((diff = ast_tvdiff_ms(chan->whentohangup, ast_tvnow())) < 0) {
02219          /* They should already be hungup! */
02220          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02221          ast_channel_unlock(chan);
02222          return NULL;
02223       }
02224       /* If this value is smaller then the current one... make it priority */
02225       if (rms > diff)
02226          rms = diff;
02227    }
02228 
02229    ast_channel_unlock(chan);
02230 
02231    /* Time to make this channel block... */
02232    CHECK_BLOCKING(chan);
02233 
02234    if (*ms > 0)
02235       start = ast_tvnow();
02236 
02237    /* We don't have to add any file descriptors... they are already added, we just have to wait! */
02238    res = epoll_wait(chan->epfd, ev, 1, rms);
02239 
02240    /* Stop blocking */
02241    ast_clear_flag(chan, AST_FLAG_BLOCKING);
02242 
02243    /* Simulate a timeout if we were interrupted */
02244    if (res < 0) {
02245       if (errno != EINTR)
02246          *ms = -1;
02247       return NULL;
02248    }
02249 
02250    /* If this channel has a timeout see if it expired */
02251    if (!ast_tvzero(chan->whentohangup)) {
02252       if (ast_tvdiff_ms(ast_tvnow(), chan->whentohangup) >= 0) {
02253          chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02254          winner = chan;
02255       }
02256    }
02257 
02258    /* No fd ready, reset timeout and be done for now */
02259    if (!res) {
02260       *ms = 0;
02261       return winner;
02262    }
02263 
02264    /* See what events are pending */
02265    aed = ev[0].data.ptr;
02266    chan->fdno = aed->which;
02267    if (ev[0].events & EPOLLPRI)
02268       ast_set_flag(chan, AST_FLAG_EXCEPTION);
02269    else
02270       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02271 
02272    if (*ms > 0) {
02273       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
02274       if (*ms < 0)
02275          *ms = 0;
02276    }
02277 
02278    return chan;
02279 }
02280 
02281 static struct ast_channel *ast_waitfor_nandfds_complex(struct ast_channel **c, int n, int *ms)
02282 {
02283    struct timeval start = { 0 , 0 };
02284    int res = 0, i;
02285    struct epoll_event ev[25] = { { 0, } };
02286    struct timeval now = { 0, 0 };
02287    long whentohangup = 0, diff = 0, rms = *ms;
02288    struct ast_channel *winner = NULL;
02289 
02290    for (i = 0; i < n; i++) {
02291       ast_channel_lock(c[i]);
02292       if (c[i]->masq && ast_do_masquerade(c[i])) {
02293          ast_log(LOG_WARNING, "Masquerade failed\n");
02294          *ms = -1;
02295          ast_channel_unlock(c[i]);
02296          return NULL;
02297       }
02298       if (!ast_tvzero(c[i]->whentohangup)) {
02299          if (whentohangup == 0)
02300             now = ast_tvnow();
02301          if ((diff = ast_tvdiff_ms(c[i]->whentohangup, now)) < 0) {
02302             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02303             ast_channel_unlock(c[i]);
02304             return c[i];
02305          }
02306          if (!whentohangup || whentohangup > diff)
02307             whentohangup = diff;
02308       }
02309       ast_channel_unlock(c[i]);
02310       CHECK_BLOCKING(c[i]);
02311    }
02312 
02313    rms = *ms;
02314    if (whentohangup) {
02315       rms = whentohangup;
02316       if (*ms >= 0 && *ms < rms)
02317          rms = *ms;
02318    }
02319 
02320    if (*ms > 0)
02321       start = ast_tvnow();
02322 
02323    res = epoll_wait(c[0]->epfd, ev, 25, rms);
02324 
02325    for (i = 0; i < n; i++)
02326       ast_clear_flag(c[i], AST_FLAG_BLOCKING);
02327 
02328    if (res < 0) {
02329       if (errno != EINTR)
02330          *ms = -1;
02331       return NULL;
02332    }
02333 
02334    if (whentohangup) {
02335       now = ast_tvnow();
02336       for (i = 0; i < n; i++) {
02337          if (!ast_tvzero(c[i]->whentohangup) && ast_tvdiff_ms(now, c[i]->whentohangup) >= 0) {
02338             c[i]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
02339             if (!winner)
02340                winner = c[i];
02341          }
02342       }
02343    }
02344 
02345    if (!res) {
02346       *ms = 0;
02347       return winner;
02348    }
02349 
02350    for (i = 0; i < res; i++) {
02351       struct ast_epoll_data *aed = ev[i].data.ptr;
02352 
02353       if (!ev[i].events || !aed)
02354          continue;
02355 
02356       winner = aed->chan;
02357       if (ev[i].events & EPOLLPRI)
02358          ast_set_flag(winner, AST_FLAG_EXCEPTION);
02359       else
02360          ast_clear_flag(winner, AST_FLAG_EXCEPTION);
02361       winner->fdno = aed->which;
02362    }
02363 
02364    if (*ms > 0) {
02365       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
02366       if (*ms < 0)
02367          *ms = 0;
02368    }
02369 
02370    return winner;
02371 }
02372 
02373 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
02374                int *exception, int *outfd, int *ms)
02375 {
02376    /* Clear all provided values in one place. */
02377    if (outfd)
02378       *outfd = -99999;
02379    if (exception)
02380       *exception = 0;
02381 
02382    /* If no epoll file descriptor is available resort to classic nandfds */
02383    if (!n || nfds || c[0]->epfd == -1)
02384       return ast_waitfor_nandfds_classic(c, n, fds, nfds, exception, outfd, ms);
02385    else if (!nfds && n == 1)
02386       return ast_waitfor_nandfds_simple(c[0], ms);
02387    else
02388       return ast_waitfor_nandfds_complex(c, n, ms);
02389 }
02390 #endif
02391 
02392 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
02393 {
02394    return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
02395 }
02396 
02397 int ast_waitfor(struct ast_channel *c, int ms)
02398 {
02399    int oldms = ms;   /* -1 if no timeout */
02400 
02401    ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
02402    if ((ms < 0) && (oldms < 0))
02403       ms = 0;
02404    return ms;
02405 }
02406 
02407 /* XXX never to be called with ms = -1 */
02408 int ast_waitfordigit(struct ast_channel *c, int ms)
02409 {
02410    return ast_waitfordigit_full(c, ms, -1, -1);
02411 }
02412 
02413 int ast_settimeout(struct ast_channel *c, unsigned int rate, int (*func)(const void *data), void *data)
02414 {
02415    int res;
02416    unsigned int real_rate = rate, max_rate;
02417 
02418    ast_channel_lock(c);
02419 
02420    if (c->timingfd == -1) {
02421       ast_channel_unlock(c);
02422       return -1;
02423    }
02424 
02425    if (!func) {
02426       rate = 0;
02427       data = NULL;
02428    }
02429 
02430    if (rate && rate > (max_rate = ast_timer_get_max_rate(c->timer))) {
02431       real_rate = max_rate;
02432    }
02433 
02434    ast_debug(1, "Scheduling timer at (%u requested / %u actual) timer ticks per second\n", rate, real_rate);
02435 
02436    res = ast_timer_set_rate(c->timer, real_rate);
02437 
02438    c->timingfunc = func;
02439    c->timingdata = data;
02440 
02441    ast_channel_unlock(c);
02442 
02443    return res;
02444 }
02445 
02446 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
02447 {
02448    /* Stop if we're a zombie or need a soft hangup */
02449    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
02450       return -1;
02451 
02452    /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
02453    ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
02454 
02455    /* Wait for a digit, no more than ms milliseconds total. */
02456    
02457    while (ms) {
02458       struct ast_channel *rchan;
02459       int outfd=-1;
02460 
02461       errno = 0;
02462       rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
02463       
02464       if (!rchan && outfd < 0 && ms) {
02465          if (errno == 0 || errno == EINTR)
02466             continue;
02467          ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
02468          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
02469          return -1;
02470       } else if (outfd > -1) {
02471          /* The FD we were watching has something waiting */
02472          ast_log(LOG_WARNING, "The FD we were waiting for has something waiting. Waitfordigit returning numeric 1\n");
02473          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
02474          return 1;
02475       } else if (rchan) {
02476          int res;
02477          struct ast_frame *f = ast_read(c);
02478          if (!f)
02479             return -1;
02480 
02481          switch (f->frametype) {
02482          case AST_FRAME_DTMF_BEGIN:
02483             break;
02484          case AST_FRAME_DTMF_END:
02485             res = f->subclass;
02486             ast_frfree(f);
02487             ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
02488             return res;
02489          case AST_FRAME_CONTROL:
02490             switch (f->subclass) {
02491             case AST_CONTROL_HANGUP:
02492                ast_frfree(f);
02493                ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
02494                return -1;
02495             case AST_CONTROL_RINGING:
02496             case AST_CONTROL_ANSWER:
02497             case AST_CONTROL_SRCUPDATE:
02498             case AST_CONTROL_SRCCHANGE:
02499                /* Unimportant */
02500                break;
02501             default:
02502                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
02503                break;
02504             }
02505             break;
02506          case AST_FRAME_VOICE:
02507             /* Write audio if appropriate */
02508             if (audiofd > -1) {
02509                if (write(audiofd, f->data.ptr, f->datalen) < 0) {
02510                   ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
02511                }
02512             }
02513          default:
02514             /* Ignore */
02515             break;
02516          }
02517          ast_frfree(f);
02518       }
02519    }
02520 
02521    ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
02522 
02523    return 0; /* Time is up */
02524 }
02525 
02526 static void send_dtmf_event(const struct ast_channel *chan, const char *direction, const char digit, const char *begin, const char *end)
02527 {
02528    manager_event(EVENT_FLAG_DTMF,
02529          "DTMF",
02530          "Channel: %s\r\n"
02531          "Uniqueid: %s\r\n"
02532          "Digit: %c\r\n"
02533          "Direction: %s\r\n"
02534          "Begin: %s\r\n"
02535          "End: %s\r\n",
02536          chan->name, chan->uniqueid, digit, direction, begin, end);
02537 }
02538 
02539 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
02540 {
02541    if (chan->generator && chan->generator->generate && chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
02542       void *tmp = chan->generatordata;
02543       int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = chan->generator->generate;
02544       int res;
02545       int samples;
02546 
02547       if (chan->timingfunc) {
02548          ast_debug(1, "Generator got voice, switching to phase locked mode\n");
02549          ast_settimeout(chan, 0, NULL, NULL);
02550       }
02551 
02552       chan->generatordata = NULL;     /* reset, to let writes go through */
02553 
02554       if (f->subclass != chan->writeformat) {
02555          float factor;
02556          factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
02557          samples = (int) ( ((float) f->samples) * factor );
02558       } else {
02559          samples = f->samples;
02560       }
02561       
02562       /* This unlock is here based on two assumptions that hold true at this point in the
02563        * code. 1) this function is only called from within __ast_read() and 2) all generators
02564        * call ast_write() in their generate callback.
02565        *
02566        * The reason this is added is so that when ast_write is called, the lock that occurs 
02567        * there will not recursively lock the channel. Doing this will cause intended deadlock 
02568        * avoidance not to work in deeper functions
02569        */
02570       ast_channel_unlock(chan);
02571       res = generate(chan, tmp, f->datalen, samples);
02572       ast_channel_lock(chan);
02573       chan->generatordata = tmp;
02574       if (res) {
02575          ast_debug(1, "Auto-deactivating generator\n");
02576          ast_deactivate_generator(chan);
02577       }
02578 
02579    } else if (f->frametype == AST_FRAME_CNG) {
02580       if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
02581          ast_debug(1, "Generator got CNG, switching to timed mode\n");
02582          ast_settimeout(chan, 50, generator_force, chan);
02583       }
02584    }
02585 }
02586 
02587 static inline void queue_dtmf_readq(struct ast_channel *chan, struct ast_frame *f)
02588 {
02589    struct ast_frame *fr = &chan->dtmff;
02590 
02591    fr->frametype = AST_FRAME_DTMF_END;
02592    fr->subclass = f->subclass;
02593    fr->len = f->len;
02594 
02595    /* The only time this function will be called is for a frame that just came
02596     * out of the channel driver.  So, we want to stick it on the tail of the
02597     * readq. */
02598 
02599    ast_queue_frame(chan, fr);
02600 }
02601 
02602 /*!
02603  * \brief Determine whether or not we should ignore DTMF in the readq
02604  */
02605 static inline int should_skip_dtmf(struct ast_channel *chan)
02606 {
02607    if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF)) {
02608       /* We're in the middle of emulating a digit, or DTMF has been
02609        * explicitly deferred.  Skip this digit, then. */
02610       return 1;
02611    }
02612          
02613    if (!ast_tvzero(chan->dtmf_tv) && 
02614          ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
02615       /* We're not in the middle of a digit, but it hasn't been long enough
02616        * since the last digit, so we'll have to skip DTMF for now. */
02617       return 1;
02618    }
02619 
02620    return 0;
02621 }
02622 
02623 /*!
02624  * \brief calculates the number of samples to jump forward with in a monitor stream.
02625  
02626  * \note When using ast_seekstream() with the read and write streams of a monitor,
02627  * the number of samples to seek forward must be of the same sample rate as the stream
02628  * or else the jump will not be calculated correctly.
02629  *
02630  * \retval number of samples to seek forward after rate conversion.
02631  */
02632 static inline int calc_monitor_jump(int samples, int sample_rate, int seek_rate)
02633 {
02634    int diff = sample_rate - seek_rate;
02635 
02636    if (diff > 0) {
02637       samples = samples / (float) (sample_rate / seek_rate);
02638    } else if (diff < 0) {
02639       samples = samples * (float) (seek_rate / sample_rate);
02640    }
02641 
02642    return samples;
02643 }
02644 
02645 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
02646 {
02647    struct ast_frame *f = NULL;   /* the return value */
02648    int blah;
02649    int prestate;
02650    int count = 0, cause = 0;
02651 
02652    /* this function is very long so make sure there is only one return
02653     * point at the end (there are only two exceptions to this).
02654     */
02655    while(ast_channel_trylock(chan)) {
02656       if(count++ > 10) 
02657          /*cannot goto done since the channel is not locked*/
02658          return &ast_null_frame;
02659       usleep(1);
02660    }
02661 
02662    if (chan->masq) {
02663       if (ast_do_masquerade(chan))
02664          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
02665       else
02666          f =  &ast_null_frame;
02667       goto done;
02668    }
02669 
02670    /* Stop if we're a zombie or need a soft hangup */
02671    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
02672       if (chan->generator)
02673          ast_deactivate_generator(chan);
02674       goto done;
02675    }
02676 
02677 #ifdef AST_DEVMODE
02678    /* 
02679     * The ast_waitfor() code records which of the channel's file descriptors reported that
02680     * data is available.  In theory, ast_read() should only be called after ast_waitfor()
02681     * reports that a channel has data available for reading.  However, there still may be
02682     * some edge cases throughout the code where ast_read() is called improperly.  This can
02683     * potentially cause problems, so if this is a developer build, make a lot of noise if
02684     * this happens so that it can be addressed. 
02685     */
02686    if (chan->fdno == -1) {
02687       ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
02688    }
02689 #endif
02690 
02691    prestate = chan->_state;
02692 
02693    /* Read and ignore anything on the alertpipe, but read only
02694       one sizeof(blah) per frame that we send from it */
02695    if (chan->alertpipe[0] > -1) {
02696       int flags = fcntl(chan->alertpipe[0], F_GETFL);
02697       /* For some odd reason, the alertpipe occasionally loses nonblocking status,
02698        * which immediately causes a deadlock scenario.  Detect and prevent this. */
02699       if ((flags & O_NONBLOCK) == 0) {
02700          ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
02701          if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
02702             ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
02703             f = &ast_null_frame;
02704             goto done;
02705          }
02706       }
02707       if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
02708          if (errno != EINTR && errno != EAGAIN)
02709             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
02710       }
02711    }
02712 
02713    if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
02714       enum ast_timer_event res;
02715 
02716       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02717 
02718       res = ast_timer_get_event(chan->timer);
02719 
02720       switch (res) {
02721       case AST_TIMING_EVENT_EXPIRED:
02722          ast_timer_ack(chan->timer, 1);
02723 
02724          if (chan->timingfunc) {
02725             /* save a copy of func/data before unlocking the channel */
02726             int (*func)(const void *) = chan->timingfunc;
02727             void *data = chan->timingdata;
02728             chan->fdno = -1;
02729             ast_channel_unlock(chan);
02730             func(data);
02731          } else {
02732             ast_timer_set_rate(chan->timer, 0);
02733             chan->fdno = -1;
02734             ast_channel_unlock(chan);
02735          }
02736 
02737          /* cannot 'goto done' because the channel is already unlocked */
02738          return &ast_null_frame;
02739 
02740       case AST_TIMING_EVENT_CONTINUOUS:
02741          if (AST_LIST_EMPTY(&chan->readq) || 
02742             !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
02743             ast_timer_disable_continuous(chan->timer);
02744          }
02745          break;
02746       }
02747 
02748    } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
02749       /* if the AST_GENERATOR_FD is set, call the generator with args
02750        * set to -1 so it can do whatever it needs to.
02751        */
02752       void *tmp = chan->generatordata;
02753       chan->generatordata = NULL;     /* reset to let ast_write get through */
02754       chan->generator->generate(chan, tmp, -1, -1);
02755       chan->generatordata = tmp;
02756       f = &ast_null_frame;
02757       chan->fdno = -1;
02758       goto done;
02759    }
02760 
02761    /* Check for pending read queue */
02762    if (!AST_LIST_EMPTY(&chan->readq)) {
02763       int skip_dtmf = should_skip_dtmf(chan);
02764 
02765       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
02766          /* We have to be picky about which frame we pull off of the readq because
02767           * there are cases where we want to leave DTMF frames on the queue until
02768           * some later time. */
02769 
02770          if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
02771             continue;
02772          }
02773 
02774          AST_LIST_REMOVE_CURRENT(frame_list);
02775          break;
02776       }
02777       AST_LIST_TRAVERSE_SAFE_END;
02778       
02779       if (!f) {
02780          /* There were no acceptable frames on the readq. */
02781          f = &ast_null_frame;
02782          if (chan->alertpipe[0] > -1) {
02783             int poke = 0;
02784             /* Restore the state of the alertpipe since we aren't ready for any
02785              * of the frames in the readq. */
02786             if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
02787                ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
02788             }
02789          }
02790       }
02791 
02792       /* Interpret hangup and return NULL */
02793       /* XXX why not the same for frames from the channel ? */
02794       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
02795          cause = f->data.uint32;
02796          ast_frfree(f);
02797          f = NULL;
02798       }
02799    } else {
02800       chan->blocker = pthread_self();
02801       if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
02802          if (chan->tech->exception)
02803             f = chan->tech->exception(chan);
02804          else {
02805             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
02806             f = &ast_null_frame;
02807          }
02808          /* Clear the exception flag */
02809          ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02810       } else if (chan->tech->read)
02811          f = chan->tech->read(chan);
02812       else
02813          ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
02814    }
02815 
02816    /*
02817     * Reset the recorded file descriptor that triggered this read so that we can
02818     * easily detect when ast_read() is called without properly using ast_waitfor().
02819     */
02820    chan->fdno = -1;
02821 
02822    if (f) {
02823       struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
02824 
02825       /* if the channel driver returned more than one frame, stuff the excess
02826          into the readq for the next ast_read call
02827       */
02828       if (AST_LIST_NEXT(f, frame_list)) {
02829          ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
02830          ast_frfree(AST_LIST_NEXT(f, frame_list));
02831          AST_LIST_NEXT(f, frame_list) = NULL;
02832       }
02833 
02834       switch (f->frametype) {
02835       case AST_FRAME_CONTROL:
02836          if (f->subclass == AST_CONTROL_ANSWER) {
02837             if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
02838                ast_debug(1, "Ignoring answer on an inbound call!\n");
02839                ast_frfree(f);
02840                f = &ast_null_frame;
02841             } else if (prestate == AST_STATE_UP) {
02842                ast_debug(1, "Dropping duplicate answer!\n");
02843                ast_frfree(f);
02844                f = &ast_null_frame;
02845             } else {
02846                /* Answer the CDR */
02847                ast_setstate(chan, AST_STATE_UP);
02848                /* removed a call to ast_cdr_answer(chan->cdr) from here. */
02849             }
02850          }
02851          break;
02852       case AST_FRAME_DTMF_END:
02853          send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
02854          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
02855          /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
02856          if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
02857             queue_dtmf_readq(chan, f);
02858             ast_frfree(f);
02859             f = &ast_null_frame;
02860          } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
02861             if (!ast_tvzero(chan->dtmf_tv) && 
02862                 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
02863                /* If it hasn't been long enough, defer this digit */
02864                queue_dtmf_readq(chan, f);
02865                ast_frfree(f);
02866                f = &ast_null_frame;
02867             } else {
02868                /* There was no begin, turn this into a begin and send the end later */
02869                f->frametype = AST_FRAME_DTMF_BEGIN;
02870                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
02871                chan->emulate_dtmf_digit = f->subclass;
02872                chan->dtmf_tv = ast_tvnow();
02873                if (f->len) {
02874                   if (f->len > AST_MIN_DTMF_DURATION)
02875                      chan->emulate_dtmf_duration = f->len;
02876                   else 
02877                      chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
02878                } else
02879                   chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
02880                ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
02881             }
02882             if (chan->audiohooks) {
02883                struct ast_frame *old_frame = f;
02884                /*!
02885                 * \todo XXX It is possible to write a digit to the audiohook twice
02886                 * if the digit was originally read while the channel was in autoservice. */
02887                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02888                if (old_frame != f)
02889                   ast_frfree(old_frame);
02890             }
02891          } else {
02892             struct timeval now = ast_tvnow();
02893             if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02894                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
02895                ast_clear_flag(chan, AST_FLAG_IN_DTMF);
02896                if (!f->len)
02897                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02898             } else if (!f->len) {
02899                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
02900                f->len = AST_MIN_DTMF_DURATION;
02901             }
02902             if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
02903                ast_log(LOG_DTMF, "DTMF end '%c' has duration %ld but want minimum %d, emulating on %s\n", f->subclass, f->len, AST_MIN_DTMF_DURATION, chan->name);
02904                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
02905                chan->emulate_dtmf_digit = f->subclass;
02906                chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
02907                ast_frfree(f);
02908                f = &ast_null_frame;
02909             } else {
02910                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
02911                if (f->len < AST_MIN_DTMF_DURATION) {
02912                   f->len = AST_MIN_DTMF_DURATION;
02913                }
02914                chan->dtmf_tv = now;
02915             }
02916             if (chan->audiohooks) {
02917                struct ast_frame *old_frame = f;
02918                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02919                if (old_frame != f)
02920                   ast_frfree(old_frame);
02921             }
02922          }
02923          break;
02924       case AST_FRAME_DTMF_BEGIN:
02925          send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
02926          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
02927          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
02928              (!ast_tvzero(chan->dtmf_tv) && 
02929                ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
02930             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
02931             ast_frfree(f);
02932             f = &ast_null_frame;
02933          } else {
02934             ast_set_flag(chan, AST_FLAG_IN_DTMF);
02935             chan->dtmf_tv = ast_tvnow();
02936             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
02937          }
02938          break;
02939       case AST_FRAME_NULL:
02940          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
02941           * is reached , because we want to make sure we pass at least one
02942           * voice frame through before starting the next digit, to ensure a gap
02943           * between DTMF digits. */
02944          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
02945             struct timeval now = ast_tvnow();
02946             if (!chan->emulate_dtmf_duration) {
02947                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02948                chan->emulate_dtmf_digit = 0;
02949             } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
02950                chan->emulate_dtmf_duration = 0;
02951                ast_frfree(f);
02952                f = &chan->dtmff;
02953                f->frametype = AST_FRAME_DTMF_END;
02954                f->subclass = chan->emulate_dtmf_digit;
02955                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02956                chan->dtmf_tv = now;
02957                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02958                chan->emulate_dtmf_digit = 0;
02959                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
02960                if (chan->audiohooks) {
02961                   struct ast_frame *old_frame = f;
02962                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02963                   if (old_frame != f) {
02964                      ast_frfree(old_frame);
02965                   }
02966                }
02967             }
02968          }
02969          break;
02970       case AST_FRAME_VOICE:
02971          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
02972           * is reached , because we want to make sure we pass at least one
02973           * voice frame through before starting the next digit, to ensure a gap
02974           * between DTMF digits. */
02975          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
02976             ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02977             chan->emulate_dtmf_digit = 0;
02978          }
02979 
02980          if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02981             if (dropaudio)
02982                ast_read_generator_actions(chan, f);
02983             ast_frfree(f);
02984             f = &ast_null_frame;
02985          }
02986 
02987          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02988             struct timeval now = ast_tvnow();
02989             if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
02990                chan->emulate_dtmf_duration = 0;
02991                ast_frfree(f);
02992                f = &chan->dtmff;
02993                f->frametype = AST_FRAME_DTMF_END;
02994                f->subclass = chan->emulate_dtmf_digit;
02995                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02996                chan->dtmf_tv = now;
02997                if (chan->audiohooks) {
02998                   struct ast_frame *old_frame = f;
02999                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03000                   if (old_frame != f)
03001                      ast_frfree(old_frame);
03002                }
03003                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
03004             } else {
03005                /* Drop voice frames while we're still in the middle of the digit */
03006                ast_frfree(f);
03007                f = &ast_null_frame;
03008             }
03009          } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
03010             /* This frame is not one of the current native formats -- drop it on the floor */
03011             char to[200];
03012             ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
03013                chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
03014             ast_frfree(f);
03015             f = &ast_null_frame;
03016          } else if ((f->frametype == AST_FRAME_VOICE)) {
03017             /* Send frame to audiohooks if present */
03018             if (chan->audiohooks) {
03019                struct ast_frame *old_frame = f;
03020                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03021                if (old_frame != f)
03022                   ast_frfree(old_frame);
03023             }
03024             if (chan->monitor && chan->monitor->read_stream ) {
03025                /* XXX what does this do ? */
03026 #ifndef MONITOR_CONSTANT_DELAY
03027                int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
03028                if (jump >= 0) {
03029                   jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03030                   if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
03031                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
03032                   chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
03033                } else
03034                   chan->insmpl+= f->samples;
03035 #else
03036                int jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03037                if (jump - MONITOR_DELAY >= 0) {
03038                   if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
03039                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
03040                   chan->insmpl += chan->outsmpl - chan->insmpl;
03041                } else
03042                   chan->insmpl += f->samples;
03043 #endif
03044                if (chan->monitor->state == AST_MONITOR_RUNNING) {
03045                   if (ast_writestream(chan->monitor->read_stream, f) < 0)
03046                      ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
03047                }
03048             }
03049 
03050             if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL) {
03051                f = &ast_null_frame;
03052             }
03053 
03054             /* it is possible for the translation process on chan->readtrans to have
03055                produced multiple frames from the single input frame we passed it; if
03056                this happens, queue the additional frames *before* the frames we may
03057                have queued earlier. if the readq was empty, put them at the head of
03058                the queue, and if it was not, put them just after the frame that was
03059                at the end of the queue.
03060             */
03061             if (AST_LIST_NEXT(f, frame_list)) {
03062                if (!readq_tail) {
03063                   ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
03064                } else {
03065                   __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
03066                }
03067                ast_frfree(AST_LIST_NEXT(f, frame_list));
03068                AST_LIST_NEXT(f, frame_list) = NULL;
03069             }
03070 
03071             /* Run generator sitting on the line if timing device not available
03072             * and synchronous generation of outgoing frames is necessary       */
03073             ast_read_generator_actions(chan, f);
03074          }
03075       default:
03076          /* Just pass it on! */
03077          break;
03078       }
03079    } else {
03080       /* Make sure we always return NULL in the future */
03081       chan->_softhangup |= AST_SOFTHANGUP_DEV;
03082       if (cause)
03083          chan->hangupcause = cause;
03084       if (chan->generator)
03085          ast_deactivate_generator(chan);
03086       /* We no longer End the CDR here */
03087    }
03088 
03089    /* High bit prints debugging */
03090    if (chan->fin & DEBUGCHAN_FLAG)
03091       ast_frame_dump(chan->name, f, "<<");
03092    chan->fin = FRAMECOUNT_INC(chan->fin);
03093 
03094 done:
03095    if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
03096       chan->generator->digit(chan, f->subclass);
03097 
03098    ast_channel_unlock(chan);
03099    return f;
03100 }
03101 
03102 int ast_internal_timing_enabled(struct ast_channel *chan)
03103 {
03104    return (ast_opt_internal_timing && chan->timingfd > -1);
03105 }
03106 
03107 struct ast_frame *ast_read(struct ast_channel *chan)
03108 {
03109    return __ast_read(chan, 0);
03110 }
03111 
03112 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
03113 {
03114    return __ast_read(chan, 1);
03115 }
03116 
03117 int ast_indicate(struct ast_channel *chan, int condition)
03118 {
03119    return ast_indicate_data(chan, condition, NULL, 0);
03120 }
03121 
03122 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
03123 {
03124    /* Don't include a default case here so that we get compiler warnings
03125     * when a new type is added. */
03126 
03127    switch (condition) {
03128    case AST_CONTROL_PROGRESS:
03129    case AST_CONTROL_PROCEEDING:
03130    case AST_CONTROL_VIDUPDATE:
03131    case AST_CONTROL_SRCUPDATE:
03132    case AST_CONTROL_SRCCHANGE:
03133    case AST_CONTROL_RADIO_KEY:
03134    case AST_CONTROL_RADIO_UNKEY:
03135    case AST_CONTROL_OPTION:
03136    case AST_CONTROL_WINK:
03137    case AST_CONTROL_FLASH:
03138    case AST_CONTROL_OFFHOOK:
03139    case AST_CONTROL_TAKEOFFHOOK:
03140    case AST_CONTROL_ANSWER:
03141    case AST_CONTROL_HANGUP:
03142    case AST_CONTROL_T38_PARAMETERS:
03143    case _XXX_AST_CONTROL_T38:
03144       break;
03145 
03146    case AST_CONTROL_CONGESTION:
03147    case AST_CONTROL_BUSY:
03148    case AST_CONTROL_RINGING:
03149    case AST_CONTROL_RING:
03150    case AST_CONTROL_HOLD:
03151    case AST_CONTROL_UNHOLD:
03152       return 1;
03153    }
03154 
03155    return 0;
03156 }
03157 
03158 int ast_indicate_data(struct ast_channel *chan, int _condition,
03159       const void *data, size_t datalen)
03160 {
03161    /* By using an enum, we'll get compiler warnings for values not handled 
03162     * in switch statements. */
03163    enum ast_control_frame_type condition = _condition;
03164    struct ast_tone_zone_sound *ts = NULL;
03165    int res = -1;
03166 
03167    ast_channel_lock(chan);
03168 
03169    /* Don't bother if the channel is about to go away, anyway. */
03170    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03171       ast_channel_unlock(chan);
03172       return -1;
03173    }
03174 
03175    if (chan->tech->indicate) {
03176       /* See if the channel driver can handle this condition. */
03177       res = chan->tech->indicate(chan, condition, data, datalen);
03178    }
03179 
03180    ast_channel_unlock(chan);
03181 
03182    if (!res) {
03183       /* The channel driver successfully handled this indication */
03184       if (is_visible_indication(condition)) {
03185          chan->visible_indication = condition;
03186       }
03187       return 0;
03188    }
03189 
03190    /* The channel driver does not support this indication, let's fake
03191     * it by doing our own tone generation if applicable. */
03192 
03193    /*!\note If we compare the enumeration type, which does not have any
03194     * negative constants, the compiler may optimize this code away.
03195     * Therefore, we must perform an integer comparison here. */
03196    if (_condition < 0) {
03197       /* Stop any tones that are playing */
03198       ast_playtones_stop(chan);
03199       return 0;
03200    }
03201 
03202    /* Handle conditions that we have tones for. */
03203    switch (condition) {
03204    case _XXX_AST_CONTROL_T38:
03205       /* deprecated T.38 control frame */
03206       return -1;
03207    case AST_CONTROL_T38_PARAMETERS:
03208       /* there is no way to provide 'default' behavior for these
03209        * control frames, so we need to return failure, but there
03210        * is also no value in the log message below being emitted
03211        * since failure to handle these frames is not an 'error'
03212        * so just return right now. in addition, we want to return
03213        * whatever value the channel driver returned, in case it
03214        * has some meaning.*/
03215       return res;
03216    case AST_CONTROL_RINGING:
03217       ts = ast_get_indication_tone(chan->zone, "ring");
03218       /* It is common practice for channel drivers to return -1 if trying
03219        * to indicate ringing on a channel which is up. The idea is to let the
03220        * core generate the ringing inband. However, we don't want the
03221        * warning message about not being able to handle the specific indication
03222        * to print nor do we want ast_indicate_data to return an "error" for this
03223        * condition
03224        */
03225       if (chan->_state == AST_STATE_UP) {
03226          res = 0;
03227       }
03228       break;
03229    case AST_CONTROL_BUSY:
03230       ts = ast_get_indication_tone(chan->zone, "busy");
03231       break;
03232    case AST_CONTROL_CONGESTION:
03233       ts = ast_get_indication_tone(chan->zone, "congestion");
03234       break;
03235    case AST_CONTROL_PROGRESS:
03236    case AST_CONTROL_PROCEEDING:
03237    case AST_CONTROL_VIDUPDATE:
03238    case AST_CONTROL_SRCUPDATE:
03239    case AST_CONTROL_SRCCHANGE:
03240    case AST_CONTROL_RADIO_KEY:
03241    case AST_CONTROL_RADIO_UNKEY:
03242    case AST_CONTROL_OPTION:
03243    case AST_CONTROL_WINK:
03244    case AST_CONTROL_FLASH:
03245    case AST_CONTROL_OFFHOOK:
03246    case AST_CONTROL_TAKEOFFHOOK:
03247    case AST_CONTROL_ANSWER:
03248    case AST_CONTROL_HANGUP:
03249    case AST_CONTROL_RING:
03250    case AST_CONTROL_HOLD:
03251    case AST_CONTROL_UNHOLD:
03252       /* Nothing left to do for these. */
03253       res = 0;
03254       break;
03255    }
03256 
03257    if (ts) {
03258       /* We have a tone to play, yay. */
03259       ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
03260       ast_playtones_start(chan, 0, ts->data, 1);
03261       ts = ast_tone_zone_sound_unref(ts);
03262       res = 0;
03263       chan->visible_indication = condition;
03264    }
03265 
03266    if (res) {
03267       /* not handled */
03268       ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
03269    }
03270 
03271    return res;
03272 }
03273 
03274 int ast_recvchar(struct ast_channel *chan, int timeout)
03275 {
03276    int c;
03277    char *buf = ast_recvtext(chan, timeout);
03278    if (buf == NULL)
03279       return -1;  /* error or timeout */
03280    c = *(unsigned char *)buf;
03281    ast_free(buf);
03282    return c;
03283 }
03284 
03285 char *ast_recvtext(struct ast_channel *chan, int timeout)
03286 {
03287    int res, done = 0;
03288    char *buf = NULL;
03289    
03290    while (!done) {
03291       struct ast_frame *f;
03292       if (ast_check_hangup(chan))
03293          break;
03294       res = ast_waitfor(chan, timeout);
03295       if (res <= 0) /* timeout or error */
03296          break;
03297       timeout = res; /* update timeout */
03298       f = ast_read(chan);
03299       if (f == NULL)
03300          break; /* no frame */
03301       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
03302          done = 1;   /* force a break */
03303       else if (f->frametype == AST_FRAME_TEXT) {      /* what we want */
03304          buf = ast_strndup((char *) f->data.ptr, f->datalen);  /* dup and break */
03305          done = 1;
03306       }
03307       ast_frfree(f);
03308    }
03309    return buf;
03310 }
03311 
03312 int ast_sendtext(struct ast_channel *chan, const char *text)
03313 {
03314    int res = 0;
03315    /* Stop if we're a zombie or need a soft hangup */
03316    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
03317       return -1;
03318    CHECK_BLOCKING(chan);
03319    if (chan->tech->send_text)
03320       res = chan->tech->send_text(chan, text);
03321    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03322    return res;
03323 }
03324 
03325 int ast_senddigit_begin(struct ast_channel *chan, char digit)
03326 {
03327    /* Device does not support DTMF tones, lets fake
03328     * it by doing our own generation. */
03329    static const char* dtmf_tones[] = {
03330       "941+1336", /* 0 */
03331       "697+1209", /* 1 */
03332       "697+1336", /* 2 */
03333       "697+1477", /* 3 */
03334       "770+1209", /* 4 */
03335       "770+1336", /* 5 */
03336       "770+1477", /* 6 */
03337       "852+1209", /* 7 */
03338       "852+1336", /* 8 */
03339       "852+1477", /* 9 */
03340       "697+1633", /* A */
03341       "770+1633", /* B */
03342       "852+1633", /* C */
03343       "941+1633", /* D */
03344       "941+1209", /* * */
03345       "941+1477"  /* # */
03346    };
03347 
03348    if (!chan->tech->send_digit_begin)
03349       return 0;
03350 
03351    if (!chan->tech->send_digit_begin(chan, digit))
03352       return 0;
03353 
03354    if (digit >= '0' && digit <='9')
03355       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
03356    else if (digit >= 'A' && digit <= 'D')
03357       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
03358    else if (digit == '*')
03359       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
03360    else if (digit == '#')
03361       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
03362    else {
03363       /* not handled */
03364       ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
03365    }
03366 
03367    return 0;
03368 }
03369 
03370 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
03371 {
03372    int res = -1;
03373 
03374    if (chan->tech->send_digit_end)
03375       res = chan->tech->send_digit_end(chan, digit, duration);
03376 
03377    if (res && chan->generator)
03378       ast_playtones_stop(chan);
03379    
03380    return 0;
03381 }
03382 
03383 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
03384 {
03385    if (chan->tech->send_digit_begin) {
03386       ast_senddigit_begin(chan, digit);
03387       ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
03388    }
03389    
03390    return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
03391 }
03392 
03393 int ast_prod(struct ast_channel *chan)
03394 {
03395    struct ast_frame a = { AST_FRAME_VOICE };
03396    char nothing[128];
03397 
03398    /* Send an empty audio frame to get things moving */
03399    if (chan->_state != AST_STATE_UP) {
03400       ast_debug(1, "Prodding channel '%s'\n", chan->name);
03401       a.subclass = chan->rawwriteformat;
03402       a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
03403       a.src = "ast_prod";
03404       if (ast_write(chan, &a))
03405          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
03406    }
03407    return 0;
03408 }
03409 
03410 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
03411 {
03412    int res;
03413    if (!chan->tech->write_video)
03414       return 0;
03415    res = ast_write(chan, fr);
03416    if (!res)
03417       res = 1;
03418    return res;
03419 }
03420 
03421 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
03422 {
03423    int res = -1;
03424    struct ast_frame *f = NULL;
03425    int count = 0;
03426 
03427    /*Deadlock avoidance*/
03428    while(ast_channel_trylock(chan)) {
03429       /*cannot goto done since the channel is not locked*/
03430       if(count++ > 10) {
03431          ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
03432          return 0;
03433       }
03434       usleep(1);
03435    }
03436    /* Stop if we're a zombie or need a soft hangup */
03437    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
03438       goto done;
03439 
03440    /* Handle any pending masquerades */
03441    if (chan->masq && ast_do_masquerade(chan)) {
03442       ast_log(LOG_WARNING, "Failed to perform masquerade\n");
03443       goto done;
03444    }
03445    if (chan->masqr) {
03446       res = 0; /* XXX explain, why 0 ? */
03447       goto done;
03448    }
03449    if (chan->generatordata) {
03450       if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
03451          ast_deactivate_generator(chan);
03452       else {
03453          if (fr->frametype == AST_FRAME_DTMF_END) {
03454             /* There is a generator running while we're in the middle of a digit.
03455              * It's probably inband DTMF, so go ahead and pass it so it can
03456              * stop the generator */
03457             ast_clear_flag(chan, AST_FLAG_BLOCKING);
03458             ast_channel_unlock(chan);
03459             res = ast_senddigit_end(chan, fr->subclass, fr->len);
03460             ast_channel_lock(chan);
03461             CHECK_BLOCKING(chan);
03462          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
03463             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
03464             res = (chan->tech->indicate == NULL) ? 0 :
03465                chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
03466          }
03467          res = 0; /* XXX explain, why 0 ? */
03468          goto done;
03469       }
03470    }
03471    /* High bit prints debugging */
03472    if (chan->fout & DEBUGCHAN_FLAG)
03473       ast_frame_dump(chan->name, fr, ">>");
03474    CHECK_BLOCKING(chan);
03475    switch (fr->frametype) {
03476    case AST_FRAME_CONTROL:
03477       res = (chan->tech->indicate == NULL) ? 0 :
03478          chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
03479       break;
03480    case AST_FRAME_DTMF_BEGIN:
03481       if (chan->audiohooks) {
03482          struct ast_frame *old_frame = fr;
03483          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
03484          if (old_frame != fr)
03485             f = fr;
03486       }
03487       send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
03488       ast_clear_flag(chan, AST_FLAG_BLOCKING);
03489       ast_channel_unlock(chan);
03490       res = ast_senddigit_begin(chan, fr->subclass);
03491       ast_channel_lock(chan);
03492       CHECK_BLOCKING(chan);
03493       break;
03494    case AST_FRAME_DTMF_END:
03495       if (chan->audiohooks) {
03496          struct ast_frame *new_frame = fr;
03497 
03498          new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
03499          if (new_frame != fr) {
03500             ast_frfree(new_frame);
03501          }
03502       }
03503       send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
03504       ast_clear_flag(chan, AST_FLAG_BLOCKING);
03505       ast_channel_unlock(chan);
03506       res = ast_senddigit_end(chan, fr->subclass, fr->len);
03507       ast_channel_lock(chan);
03508       CHECK_BLOCKING(chan);
03509       break;
03510    case AST_FRAME_TEXT:
03511       if (fr->subclass == AST_FORMAT_T140) {
03512          res = (chan->tech->write_text == NULL) ? 0 :
03513             chan->tech->write_text(chan, fr);
03514       } else {
03515          res = (chan->tech->send_text == NULL) ? 0 :
03516             chan->tech->send_text(chan, (char *) fr->data.ptr);
03517       }
03518       break;
03519    case AST_FRAME_HTML:
03520       res = (chan->tech->send_html == NULL) ? 0 :
03521          chan->tech->send_html(chan, fr->subclass, (char *) fr->data.ptr, fr->datalen);
03522       break;
03523    case AST_FRAME_VIDEO:
03524       /* XXX Handle translation of video codecs one day XXX */
03525       res = (chan->tech->write_video == NULL) ? 0 :
03526          chan->tech->write_video(chan, fr);
03527       break;
03528    case AST_FRAME_MODEM:
03529       res = (chan->tech->write == NULL) ? 0 :
03530          chan->tech->write(chan, fr);
03531       break;
03532    case AST_FRAME_VOICE:
03533       if (chan->tech->write == NULL)
03534          break;   /*! \todo XXX should return 0 maybe ? */
03535 
03536       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
03537       if (fr->subclass == chan->rawwriteformat)
03538          f = fr;
03539       else
03540          f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
03541 
03542       if (!f) {
03543          res = 0;
03544          break;
03545       }
03546 
03547       if (chan->audiohooks) {
03548          struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
03549          int freeoldlist = 0;
03550 
03551          if (f != fr) {
03552             freeoldlist = 1;
03553          }
03554 
03555          /* Since ast_audiohook_write may return a new frame, and the cur frame is
03556           * an item in a list of frames, create a new list adding each cur frame back to it
03557           * regardless if the cur frame changes or not. */
03558          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
03559             new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, cur);
03560 
03561             /* if this frame is different than cur, preserve the end of the list,
03562              * free the old frames, and set cur to be the new frame */
03563             if (new_frame != cur) {
03564 
03565                /* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
03566                 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
03567                 * times it may override the previous frame we got from it unless we dup it */
03568                if ((dup = ast_frisolate(new_frame))) {
03569                   AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
03570                   if (freeoldlist) {
03571                      AST_LIST_NEXT(cur, frame_list) = NULL;
03572                      ast_frfree(cur);
03573                   }
03574                   cur = dup;
03575                }
03576             }
03577 
03578             /* now, regardless if cur is new or not, add it to the new list,
03579              * if the new list has not started, cur will become the first item. */
03580             if (prev) {
03581                AST_LIST_NEXT(prev, frame_list) = cur;
03582             } else {
03583                f = cur; /* set f to be the beginning of our new list */
03584             }
03585             prev = cur;
03586          }
03587       }
03588       
03589       /* If Monitor is running on this channel, then we have to write frames out there too */
03590       /* the translator on chan->writetrans may have returned multiple frames
03591          from the single frame we passed in; if so, feed each one of them to the
03592          monitor */
03593       if (chan->monitor && chan->monitor->write_stream) {
03594          struct ast_frame *cur;
03595 
03596          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
03597          /* XXX must explain this code */
03598 #ifndef MONITOR_CONSTANT_DELAY
03599             int jump = chan->insmpl - chan->outsmpl - 4 * cur->samples;
03600             if (jump >= 0) {
03601                jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03602                if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
03603                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
03604                chan->outsmpl += (chan->insmpl - chan->outsmpl) + cur->samples;
03605             } else {
03606                chan->outsmpl += cur->samples;
03607             }
03608 #else
03609             int jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03610             if (jump - MONITOR_DELAY >= 0) {
03611                if (ast_seekstream(chan->monitor->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1)
03612                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
03613                chan->outsmpl += chan->insmpl - chan->outsmpl;
03614             } else {
03615                chan->outsmpl += cur->samples;
03616             }
03617 #endif
03618             if (chan->monitor->state == AST_MONITOR_RUNNING) {
03619                if (ast_writestream(chan->monitor->write_stream, cur) < 0)
03620                   ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
03621             }
03622          }
03623       }
03624 
03625       /* the translator on chan->writetrans may have returned multiple frames
03626          from the single frame we passed in; if so, feed each one of them to the
03627          channel, freeing each one after it has been written */
03628       if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
03629          struct ast_frame *cur, *next;
03630          unsigned int skip = 0;
03631 
03632          for (cur = f, next = AST_LIST_NEXT(cur, frame_list);
03633               cur;
03634               cur = next, next = cur ? AST_LIST_NEXT(cur, frame_list) : NULL) {
03635             if (!skip) {
03636                if ((res = chan->tech->write(chan, cur)) < 0) {
03637                   chan->_softhangup |= AST_SOFTHANGUP_DEV;
03638                   skip = 1;
03639                } else if (next) {
03640                   /* don't do this for the last frame in the list,
03641                      as the code outside the loop will do it once
03642                   */
03643                   chan->fout = FRAMECOUNT_INC(chan->fout);
03644                }
03645             }
03646             ast_frfree(cur);
03647          }
03648 
03649          /* reset f so the code below doesn't attempt to free it */
03650          f = NULL;
03651       } else {
03652          res = chan->tech->write(chan, f);
03653       }
03654       break;
03655    case AST_FRAME_NULL:
03656    case AST_FRAME_IAX:
03657       /* Ignore these */
03658       res = 0;
03659       break;
03660    default:
03661       /* At this point, fr is the incoming frame and f is NULL.  Channels do
03662        * not expect to get NULL as a frame pointer and will segfault.  Hence,
03663        * we output the original frame passed in. */
03664       res = chan->tech->write(chan, fr);
03665       break;
03666    }
03667 
03668    if (f && f != fr)
03669       ast_frfree(f);
03670    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03671 
03672    /* Consider a write failure to force a soft hangup */
03673    if (res < 0) {
03674       chan->_softhangup |= AST_SOFTHANGUP_DEV;
03675    } else {
03676       chan->fout = FRAMECOUNT_INC(chan->fout);
03677    }
03678 done:
03679    ast_channel_unlock(chan);
03680    return res;
03681 }
03682 
03683 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
03684             struct ast_trans_pvt **trans, const int direction)
03685 {
03686    int native;
03687    int res;
03688    char from[200], to[200];
03689    
03690    /* Make sure we only consider audio */
03691    fmt &= AST_FORMAT_AUDIO_MASK;
03692    
03693    native = chan->nativeformats;
03694 
03695    if (!fmt || !native) /* No audio requested */
03696       return 0;   /* Let's try a call without any sounds (video, text) */
03697    
03698    /* Find a translation path from the native format to one of the desired formats */
03699    if (!direction)
03700       /* reading */
03701       res = ast_translator_best_choice(&fmt, &native);
03702    else
03703       /* writing */
03704       res = ast_translator_best_choice(&native, &fmt);
03705 
03706    if (res < 0) {
03707       ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
03708          ast_getformatname_multiple(from, sizeof(from), native),
03709          ast_getformatname_multiple(to, sizeof(to), fmt));
03710       return -1;
03711    }
03712    
03713    /* Now we have a good choice for both. */
03714    ast_channel_lock(chan);
03715 
03716    if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
03717       /* the channel is already in these formats, so nothing to do */
03718       ast_channel_unlock(chan);
03719       return 0;
03720    }
03721 
03722    *rawformat = native;
03723    /* User perspective is fmt */
03724    *format = fmt;
03725    /* Free any read translation we have right now */
03726    if (*trans)
03727       ast_translator_free_path(*trans);
03728    /* Build a translation path from the raw format to the desired format */
03729    if (!direction)
03730       /* reading */
03731       *trans = ast_translator_build_path(*format, *rawformat);
03732    else
03733       /* writing */
03734       *trans = ast_translator_build_path(*rawformat, *format);
03735    ast_channel_unlock(chan);
03736    ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
03737       direction ? "write" : "read", ast_getformatname(fmt));
03738    return 0;
03739 }
03740 
03741 int ast_set_read_format(struct ast_channel *chan, int fmt)
03742 {
03743    return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
03744            &chan->readtrans, 0);
03745 }
03746 
03747 int ast_set_write_format(struct ast_channel *chan, int fmt)
03748 {
03749    return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
03750            &chan->writetrans, 1);
03751 }
03752 
03753 const char *ast_channel_reason2str(int reason)
03754 {
03755    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
03756    {
03757    case 0:
03758       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
03759    case AST_CONTROL_HANGUP:
03760       return "Hangup";
03761    case AST_CONTROL_RING:
03762       return "Local Ring";
03763    case AST_CONTROL_RINGING:
03764       return "Remote end Ringing";
03765    case AST_CONTROL_ANSWER:
03766       return "Remote end has Answered";
03767    case AST_CONTROL_BUSY:
03768       return "Remote end is Busy";
03769    case AST_CONTROL_CONGESTION:
03770       return "Congestion (circuits busy)";
03771    default:
03772       return "Unknown Reason!!";
03773    }
03774 }
03775 
03776 static void handle_cause(int cause, int *outstate)
03777 {
03778    if (outstate) {
03779       /* compute error and return */
03780       if (cause == AST_CAUSE_BUSY)
03781          *outstate = AST_CONTROL_BUSY;
03782       else if (cause == AST_CAUSE_CONGESTION)
03783          *outstate = AST_CONTROL_CONGESTION;
03784       else
03785          *outstate = 0;
03786    }
03787 }
03788 
03789 struct ast_channel *ast_call_forward(struct ast_channel *caller, struct ast_channel *orig, int *timeout, int format, struct outgoing_helper *oh, int *outstate)
03790 {
03791    char tmpchan[256];
03792    struct ast_channel *new = NULL;
03793    char *data, *type;
03794    int cause = 0;
03795 
03796    /* gather data and request the new forward channel */
03797    ast_copy_string(tmpchan, orig->call_forward, sizeof(tmpchan));
03798    if ((data = strchr(tmpchan, '/'))) {
03799       *data++ = '\0';
03800       type = tmpchan;
03801    } else {
03802       const char *forward_context;
03803       ast_channel_lock(orig);
03804       forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
03805       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", orig->call_forward, S_OR(forward_context, orig->context));
03806       ast_channel_unlock(orig);
03807       data = tmpchan;
03808       type = "Local";
03809    }
03810    if (!(new = ast_request(type, format, data, &cause))) {
03811       ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
03812       handle_cause(cause, outstate);
03813       ast_hangup(orig);
03814       return NULL;
03815    }
03816 
03817    /* Copy/inherit important information into new channel */
03818    if (oh) {
03819       if (oh->vars) {
03820          ast_set_variables(new, oh->vars);
03821       }
03822       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
03823          ast_set_callerid(new, oh->cid_num, oh->cid_name, oh->cid_num);
03824       }
03825       if (oh->parent_channel) {
03826          ast_channel_inherit_variables(oh->parent_channel, new);
03827          ast_channel_datastore_inherit(oh->parent_channel, new);
03828       }
03829       if (oh->account) {
03830          ast_cdr_setaccount(new, oh->account);
03831       }
03832    } else if (caller) { /* no outgoing helper so use caller if avaliable */
03833       ast_channel_inherit_variables(caller, new);
03834       ast_channel_datastore_inherit(caller, new);
03835    }
03836 
03837    ast_channel_lock(orig);
03838    while (ast_channel_trylock(new)) {
03839       CHANNEL_DEADLOCK_AVOIDANCE(orig);
03840    }
03841    ast_copy_flags(new->cdr, orig->cdr, AST_CDR_FLAG_ORIGINATED);
03842    ast_string_field_set(new, accountcode, orig->accountcode);
03843    if (!ast_strlen_zero(orig->cid.cid_num) && !ast_strlen_zero(new->cid.cid_name)) {
03844       ast_set_callerid(new, orig->cid.cid_num, orig->cid.cid_name, orig->cid.cid_num);
03845    }
03846    ast_channel_unlock(new);
03847    ast_channel_unlock(orig);
03848 
03849    /* call new channel */
03850    if ((*timeout = ast_call(new, data, 0))) {
03851       ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
03852       ast_hangup(orig);
03853       ast_hangup(new);
03854       return NULL;
03855    }
03856    ast_hangup(orig);
03857 
03858    return new;
03859 }
03860 
03861 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
03862 {
03863    int dummy_outstate;
03864    int cause = 0;
03865    struct ast_channel *chan;
03866    int res = 0;
03867    int last_subclass = 0;
03868    
03869    if (outstate)
03870       *outstate = 0;
03871    else
03872       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
03873 
03874    chan = ast_request(type, format, data, &cause);
03875    if (!chan) {
03876       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
03877       handle_cause(cause, outstate);
03878       return NULL;
03879    }
03880 
03881    if (oh) {
03882       if (oh->vars)  
03883          ast_set_variables(chan, oh->vars);
03884       /* XXX why is this necessary, for the parent_channel perhaps ? */
03885       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
03886          ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
03887       if (oh->parent_channel) {
03888          ast_channel_inherit_variables(oh->parent_channel, chan);
03889          ast_channel_datastore_inherit(oh->parent_channel, chan);
03890       }
03891       if (oh->account)
03892          ast_cdr_setaccount(chan, oh->account); 
03893    }
03894    ast_set_callerid(chan, cid_num, cid_name, cid_num);
03895    ast_set_flag(chan->cdr, AST_CDR_FLAG_ORIGINATED);
03896 
03897    if (ast_call(chan, data, 0)) {   /* ast_call failed... */
03898       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
03899    } else {
03900       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
03901       while (timeout && chan->_state != AST_STATE_UP) {
03902          struct ast_frame *f;
03903          res = ast_waitfor(chan, timeout);
03904          if (res == 0) { /* timeout, treat it like ringing */
03905             *outstate = AST_CONTROL_RINGING;
03906             break;
03907          }
03908          if (res < 0) /* error or done */
03909             break;
03910          if (timeout > -1)
03911             timeout = res;
03912          if (!ast_strlen_zero(chan->call_forward)) {
03913             if (!(chan = ast_call_forward(NULL, chan, &timeout, format, oh, outstate))) {
03914                return NULL;
03915             }
03916             continue;
03917          }
03918 
03919          f = ast_read(chan);
03920          if (!f) {
03921             *outstate = AST_CONTROL_HANGUP;
03922             res = 0;
03923             break;
03924          }
03925          if (f->frametype == AST_FRAME_CONTROL) {
03926             switch (f->subclass) {
03927             case AST_CONTROL_RINGING:  /* record but keep going */
03928                *outstate = f->subclass;
03929                break;
03930 
03931             case AST_CONTROL_BUSY:
03932                ast_cdr_busy(chan->cdr);
03933                *outstate = f->subclass;
03934                timeout = 0;
03935                break;
03936 
03937             case AST_CONTROL_CONGESTION:
03938                ast_cdr_failed(chan->cdr);
03939                *outstate = f->subclass;
03940                timeout = 0;
03941                break;
03942 
03943             case AST_CONTROL_ANSWER:
03944                ast_cdr_answer(chan->cdr);
03945                *outstate = f->subclass;
03946                timeout = 0;      /* trick to force exit from the while() */
03947                break;
03948 
03949             /* Ignore these */
03950             case AST_CONTROL_PROGRESS:
03951             case AST_CONTROL_PROCEEDING:
03952             case AST_CONTROL_HOLD:
03953             case AST_CONTROL_UNHOLD:
03954             case AST_CONTROL_VIDUPDATE:
03955             case AST_CONTROL_SRCUPDATE:
03956             case AST_CONTROL_SRCCHANGE:
03957             case -1:       /* Ignore -- just stopping indications */
03958                break;
03959 
03960             default:
03961                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
03962             }
03963             last_subclass = f->subclass;
03964          }
03965          ast_frfree(f);
03966       }
03967    }
03968 
03969    /* Final fixups */
03970    if (oh) {
03971       if (!ast_strlen_zero(oh->context))
03972          ast_copy_string(chan->context, oh->context, sizeof(chan->context));
03973       if (!ast_strlen_zero(oh->exten))
03974          ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
03975       if (oh->priority) 
03976          chan->priority = oh->priority;
03977    }
03978    if (chan->_state == AST_STATE_UP)
03979       *outstate = AST_CONTROL_ANSWER;
03980 
03981    if (res <= 0) {
03982       if ( AST_CONTROL_RINGING == last_subclass ) 
03983          chan->hangupcause = AST_CAUSE_NO_ANSWER;
03984       if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
03985          ast_cdr_init(chan->cdr, chan);
03986       if (chan->cdr) {
03987          char tmp[256];
03988          snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
03989          ast_cdr_setapp(chan->cdr,"Dial",tmp);
03990          ast_cdr_update(chan);
03991          ast_cdr_start(chan->cdr);
03992          ast_cdr_end(chan->cdr);
03993          /* If the cause wasn't handled properly */
03994          if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
03995             ast_cdr_failed(chan->cdr);
03996       }
03997       ast_hangup(chan);
03998       chan = NULL;
03999    }
04000    return chan;
04001 }
04002 
04003 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
04004 {
04005    return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
04006 }
04007 
04008 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
04009 {
04010    struct chanlist *chan;
04011    struct ast_channel *c;
04012    int capabilities;
04013    int fmt;
04014    int res;
04015    int foo;
04016    int videoformat = format & AST_FORMAT_VIDEO_MASK;
04017    int textformat = format & AST_FORMAT_TEXT_MASK;
04018 
04019    if (!cause)
04020       cause = &foo;
04021    *cause = AST_CAUSE_NOTDEFINED;
04022 
04023    if (AST_RWLIST_RDLOCK(&channels)) {
04024       ast_log(LOG_WARNING, "Unable to lock channel list\n");
04025       return NULL;
04026    }
04027 
04028    AST_LIST_TRAVERSE(&backends, chan, list) {
04029       if (strcasecmp(type, chan->tech->type))
04030          continue;
04031 
04032       capabilities = chan->tech->capabilities;
04033       fmt = format & AST_FORMAT_AUDIO_MASK;
04034       if (fmt) {
04035          /* We have audio - is it possible to connect the various calls to each other? 
04036             (Avoid this check for calls without audio, like text+video calls)
04037          */
04038          res = ast_translator_best_choice(&fmt, &capabilities);
04039          if (res < 0) {
04040             ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
04041             *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
04042             AST_RWLIST_UNLOCK(&channels);
04043             return NULL;
04044          }
04045       }
04046       AST_RWLIST_UNLOCK(&channels);
04047       if (!chan->tech->requester)
04048          return NULL;
04049       
04050       if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
04051          return NULL;
04052       
04053       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
04054       return c;
04055    }
04056 
04057    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
04058    *cause = AST_CAUSE_NOSUCHDRIVER;
04059    AST_RWLIST_UNLOCK(&channels);
04060 
04061    return NULL;
04062 }
04063 
04064 int ast_call(struct ast_channel *chan, char *addr, int timeout)
04065 {
04066    /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
04067       If the remote end does not answer within the timeout, then do NOT hang up, but
04068       return anyway.  */
04069    int res = -1;
04070    /* Stop if we're a zombie or need a soft hangup */
04071    ast_channel_lock(chan);
04072    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
04073       if (chan->cdr) {
04074          ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
04075       }
04076       if (chan->tech->call)
04077          res = chan->tech->call(chan, addr, timeout);
04078       ast_set_flag(chan, AST_FLAG_OUTGOING);
04079    }
04080    ast_channel_unlock(chan);
04081    return res;
04082 }
04083 
04084 /*!
04085   \brief Transfer a call to dest, if the channel supports transfer
04086 
04087   Called by:
04088    \arg app_transfer
04089    \arg the manager interface
04090 */
04091 int ast_transfer(struct ast_channel *chan, char *dest)
04092 {
04093    int res = -1;
04094 
04095    /* Stop if we're a zombie or need a soft hangup */
04096    ast_channel_lock(chan);
04097    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
04098       if (chan->tech->transfer) {
04099          res = chan->tech->transfer(chan, dest);
04100          if (!res)
04101             res = 1;
04102       } else
04103          res = 0;
04104    }
04105    ast_channel_unlock(chan);
04106    return res;
04107 }
04108 
04109 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
04110 {
04111    return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
04112 }
04113 
04114 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
04115 {
04116    int pos = 0;   /* index in the buffer where we accumulate digits */
04117    int to = ftimeout;
04118 
04119    /* Stop if we're a zombie or need a soft hangup */
04120    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
04121       return -1;
04122    if (!len)
04123       return -1;
04124    for (;;) {
04125       int d;
04126       if (c->stream) {
04127          d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
04128          ast_stopstream(c);
04129          usleep(1000);
04130          if (!d)
04131             d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
04132       } else {
04133          d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
04134       }
04135       if (d < 0)
04136          return AST_GETDATA_FAILED;
04137       if (d == 0) {
04138          s[pos] = '\0';
04139          return AST_GETDATA_TIMEOUT;
04140       }
04141       if (d == 1) {
04142          s[pos] = '\0';
04143          return AST_GETDATA_INTERRUPTED;
04144       }
04145       if (strchr(enders, d) && (pos == 0)) {
04146          s[pos] = '\0';
04147          return AST_GETDATA_EMPTY_END_TERMINATED;
04148       }
04149       if (!strchr(enders, d)) {
04150          s[pos++] = d;
04151       }
04152       if (strchr(enders, d) || (pos >= len)) {
04153          s[pos] = '\0';
04154          return AST_GETDATA_COMPLETE;
04155       }
04156       to = timeout;
04157    }
04158    /* Never reached */
04159    return 0;
04160 }
04161 
04162 int ast_channel_supports_html(struct ast_channel *chan)
04163 {
04164    return (chan->tech->send_html) ? 1 : 0;
04165 }
04166 
04167 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04168 {
04169    if (chan->tech->send_html)
04170       return chan->tech->send_html(chan, subclass, data, datalen);
04171    return -1;
04172 }
04173 
04174 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
04175 {
04176    return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
04177 }
04178 
04179 /*! \brief Set up translation from one channel to another */
04180 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
04181 {
04182    int src;
04183    int dst;
04184 
04185    if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
04186       /* Already compatible!  Moving on ... */
04187       return 0;
04188    }
04189 
04190    /* Set up translation from the 'from' channel to the 'to' channel */
04191    src = from->nativeformats;
04192    dst = to->nativeformats;
04193 
04194    /* If there's no audio in this call, don't bother with trying to find a translation path */
04195    if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
04196       return 0;
04197 
04198    if (ast_translator_best_choice(&dst, &src) < 0) {
04199       ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
04200       return -1;
04201    }
04202 
04203    /* if the best path is not 'pass through', then
04204       transcoding is needed; if desired, force transcode path
04205       to use SLINEAR between channels, but only if there is
04206       no direct conversion available */
04207    if ((src != dst) && ast_opt_transcode_via_slin &&
04208        (ast_translate_path_steps(dst, src) != 1))
04209       dst = AST_FORMAT_SLINEAR;
04210    if (ast_set_read_format(from, dst) < 0) {
04211       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
04212       return -1;
04213    }
04214    if (ast_set_write_format(to, dst) < 0) {
04215       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
04216       return -1;
04217    }
04218    return 0;
04219 }
04220 
04221 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
04222 {
04223    /* Some callers do not check return code, and we must try to set all call legs correctly */
04224    int rc = 0;
04225 
04226    /* Set up translation from the chan to the peer */
04227    rc = ast_channel_make_compatible_helper(chan, peer);
04228 
04229    if (rc < 0)
04230       return rc;
04231 
04232    /* Set up translation from the peer to the chan */
04233    rc = ast_channel_make_compatible_helper(peer, chan);
04234 
04235    return rc;
04236 }
04237 
04238 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clonechan)
04239 {
04240    int res = -1;
04241    struct ast_channel *final_orig, *final_clone, *base;
04242 
04243 retrymasq:
04244    final_orig = original;
04245    final_clone = clonechan;
04246 
04247    ast_channel_lock(original);
04248    while (ast_channel_trylock(clonechan)) {
04249       ast_channel_unlock(original);
04250       usleep(1);
04251       ast_channel_lock(original);
04252    }
04253 
04254    /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
04255       and if so, we don't really want to masquerade it, but its proxy */
04256    if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
04257       final_orig = original->_bridge;
04258 
04259    if (clonechan->_bridge && (clonechan->_bridge != ast_bridged_channel(clonechan)) && (clonechan->_bridge->_bridge != clonechan))
04260       final_clone = clonechan->_bridge;
04261    
04262    if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
04263       final_clone = base;
04264    }
04265 
04266    if ((final_orig != original) || (final_clone != clonechan)) {
04267       /* Lots and lots of deadlock avoidance.  The main one we're competing with
04268        * is ast_write(), which locks channels recursively, when working with a
04269        * proxy channel. */
04270       if (ast_channel_trylock(final_orig)) {
04271          ast_channel_unlock(clonechan);
04272          ast_channel_unlock(original);
04273          goto retrymasq;
04274       }
04275       if (ast_channel_trylock(final_clone)) {
04276          ast_channel_unlock(final_orig);
04277          ast_channel_unlock(clonechan);
04278          ast_channel_unlock(original);
04279          goto retrymasq;
04280       }
04281       ast_channel_unlock(clonechan);
04282       ast_channel_unlock(original);
04283       original = final_orig;
04284       clonechan = final_clone;
04285    }
04286 
04287    if (original == clonechan) {
04288       ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
04289       ast_channel_unlock(clonechan);
04290       ast_channel_unlock(original);
04291       return -1;
04292    }
04293 
04294    ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
04295       clonechan->name, original->name);
04296    if (original->masq) {
04297       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04298          original->masq->name, original->name);
04299    } else if (clonechan->masqr) {
04300       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04301          clonechan->name, clonechan->masqr->name);
04302    } else {
04303       original->masq = clonechan;
04304       clonechan->masqr = original;
04305       ast_queue_frame(original, &ast_null_frame);
04306       ast_queue_frame(clonechan, &ast_null_frame);
04307       ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan->name, original->name);
04308       res = 0;
04309    }
04310 
04311    ast_channel_unlock(clonechan);
04312    ast_channel_unlock(original);
04313 
04314    return res;
04315 }
04316 
04317 void ast_change_name(struct ast_channel *chan, char *newname)
04318 {
04319    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
04320    ast_string_field_set(chan, name, newname);
04321 }
04322 
04323 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
04324 {
04325    struct ast_var_t *current, *newvar;
04326    const char *varname;
04327 
04328    AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
04329       int vartype = 0;
04330 
04331       varname = ast_var_full_name(current);
04332       if (!varname)
04333          continue;
04334 
04335       if (varname[0] == '_') {
04336          vartype = 1;
04337          if (varname[1] == '_')
04338             vartype = 2;
04339       }
04340 
04341       switch (vartype) {
04342       case 1:
04343          newvar = ast_var_assign(&varname[1], ast_var_value(current));
04344          if (newvar) {
04345             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
04346             ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
04347          }
04348          break;
04349       case 2:
04350          newvar = ast_var_assign(varname, ast_var_value(current));
04351          if (newvar) {
04352             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
04353             ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
04354          }
04355          break;
04356       default:
04357          ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
04358          break;
04359       }
04360    }
04361 }
04362 
04363 /*!
04364   \brief Clone channel variables from 'clone' channel into 'original' channel
04365 
04366   All variables except those related to app_groupcount are cloned.
04367   Variables are actually _removed_ from 'clone' channel, presumably
04368   because it will subsequently be destroyed.
04369 
04370   \note Assumes locks will be in place on both channels when called.
04371 */
04372 static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
04373 {
04374    struct ast_var_t *current, *newvar;
04375    /* Append variables from clone channel into original channel */
04376    /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
04377    if (AST_LIST_FIRST(&clonechan->varshead))
04378       AST_LIST_APPEND_LIST(&original->varshead, &clonechan->varshead, entries);
04379 
04380    /* then, dup the varshead list into the clone */
04381    
04382    AST_LIST_TRAVERSE(&original->varshead, current, entries) {
04383       newvar = ast_var_assign(current->name, current->value);
04384       if (newvar)
04385          AST_LIST_INSERT_TAIL(&clonechan->varshead, newvar, entries);
04386    }
04387 }
04388 
04389 /*!
04390  * \pre chan is locked
04391  */
04392 static void report_new_callerid(const struct ast_channel *chan)
04393 {
04394    manager_event(EVENT_FLAG_CALL, "NewCallerid",
04395             "Channel: %s\r\n"
04396             "CallerIDNum: %s\r\n"
04397             "CallerIDName: %s\r\n"
04398             "Uniqueid: %s\r\n"
04399             "CID-CallingPres: %d (%s)\r\n",
04400             chan->name,
04401             S_OR(chan->cid.cid_num, ""),
04402             S_OR(chan->cid.cid_name, ""),
04403             chan->uniqueid,
04404             chan->cid.cid_pres,
04405             ast_describe_caller_presentation(chan->cid.cid_pres)
04406             );
04407 }
04408 
04409 /*!
04410   \brief Masquerade a channel
04411 
04412   \note Assumes channel will be locked when called
04413 */
04414 int ast_do_masquerade(struct ast_channel *original)
04415 {
04416    int x,i;
04417    int res=0;
04418    int origstate;
04419    struct ast_frame *current;
04420    const struct ast_channel_tech *t;
04421    void *t_pvt;
04422    struct ast_callerid tmpcid;
04423    struct ast_channel *clonechan = original->masq;
04424    struct ast_cdr *cdr;
04425    int rformat = original->readformat;
04426    int wformat = original->writeformat;
04427    char newn[AST_CHANNEL_NAME];
04428    char orig[AST_CHANNEL_NAME];
04429    char masqn[AST_CHANNEL_NAME];
04430    char zombn[AST_CHANNEL_NAME];
04431 
04432    ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
04433       clonechan->name, clonechan->_state, original->name, original->_state);
04434 
04435    manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
04436             clonechan->name, ast_state2str(clonechan->_state), original->name, ast_state2str(original->_state));
04437 
04438    /* XXX This operation is a bit odd.  We're essentially putting the guts of
04439     * the clone channel into the original channel.  Start by killing off the
04440     * original channel's backend.  While the features are nice, which is the
04441     * reason we're keeping it, it's still awesomely weird. XXX */
04442 
04443    /* We need the clone's lock, too */
04444    ast_channel_lock(clonechan);
04445 
04446    ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clonechan->name, &clonechan->lock_dont_use);
04447 
04448    /* Having remembered the original read/write formats, we turn off any translation on either
04449       one */
04450    free_translation(clonechan);
04451    free_translation(original);
04452 
04453 
04454    /* Unlink the masquerade */
04455    original->masq = NULL;
04456    clonechan->masqr = NULL;
04457    
04458    /* Save the original name */
04459    ast_copy_string(orig, original->name, sizeof(orig));
04460    /* Save the new name */
04461    ast_copy_string(newn, clonechan->name, sizeof(newn));
04462    /* Create the masq name */
04463    snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
04464       
04465    /* Copy the name from the clone channel */
04466    ast_string_field_set(original, name, newn);
04467 
04468    /* Mangle the name of the clone channel */
04469    ast_string_field_set(clonechan, name, masqn);
04470    
04471    /* Notify any managers of the change, first the masq then the other */
04472    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clonechan->uniqueid);
04473    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
04474 
04475    /* Swap the technologies */   
04476    t = original->tech;
04477    original->tech = clonechan->tech;
04478    clonechan->tech = t;
04479 
04480    /* Swap the cdrs */
04481    cdr = original->cdr;
04482    original->cdr = clonechan->cdr;
04483    clonechan->cdr = cdr;
04484 
04485    t_pvt = original->tech_pvt;
04486    original->tech_pvt = clonechan->tech_pvt;
04487    clonechan->tech_pvt = t_pvt;
04488 
04489    /* Swap the alertpipes */
04490    for (i = 0; i < 2; i++) {
04491       x = original->alertpipe[i];
04492       original->alertpipe[i] = clonechan->alertpipe[i];
04493       clonechan->alertpipe[i] = x;
04494    }
04495 
04496    /* 
04497     * Swap the readq's.  The end result should be this:
04498     *
04499     *  1) All frames should be on the new (original) channel.
04500     *  2) Any frames that were already on the new channel before this
04501     *     masquerade need to be at the end of the readq, after all of the
04502     *     frames on the old (clone) channel.
04503     *  3) The alertpipe needs to get poked for every frame that was already
04504     *     on the new channel, since we are now using the alert pipe from the
04505     *     old (clone) channel.
04506     */
04507    {
04508       AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
04509       AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
04510 
04511       AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
04512       AST_LIST_APPEND_LIST(&original->readq, &clonechan->readq, frame_list);
04513 
04514       while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
04515          AST_LIST_INSERT_TAIL(&original->readq, current, frame_list);
04516          if (original->alertpipe[1] > -1) {
04517             int poke = 0;
04518 
04519             if (write(original->alertpipe[1], &poke, sizeof(poke)) < 0) {
04520                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
04521             }
04522          }
04523       }
04524    }
04525 
04526    /* Swap the raw formats */
04527    x = original->rawreadformat;
04528    original->rawreadformat = clonechan->rawreadformat;
04529    clonechan->rawreadformat = x;
04530    x = original->rawwriteformat;
04531    original->rawwriteformat = clonechan->rawwriteformat;
04532    clonechan->rawwriteformat = x;
04533 
04534    clonechan->_softhangup = AST_SOFTHANGUP_DEV;
04535 
04536    /* And of course, so does our current state.  Note we need not
04537       call ast_setstate since the event manager doesn't really consider
04538       these separate.  We do this early so that the clone has the proper
04539       state of the original channel. */
04540    origstate = original->_state;
04541    original->_state = clonechan->_state;
04542    clonechan->_state = origstate;
04543 
04544    if (clonechan->tech->fixup){
04545       res = clonechan->tech->fixup(original, clonechan);
04546       if (res)
04547          ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clonechan->name);
04548    }
04549 
04550    /* Start by disconnecting the original's physical side */
04551    if (clonechan->tech->hangup)
04552       res = clonechan->tech->hangup(clonechan);
04553    if (res) {
04554       ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
04555       ast_channel_unlock(clonechan);
04556       return -1;
04557    }
04558 
04559    snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
04560    /* Mangle the name of the clone channel */
04561    ast_string_field_set(clonechan, name, zombn);
04562    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clonechan->uniqueid);
04563 
04564    /* Update the type. */
04565    t_pvt = original->monitor;
04566    original->monitor = clonechan->monitor;
04567    clonechan->monitor = t_pvt;
04568 
04569    /* Keep the same language.  */
04570    ast_string_field_set(original, language, clonechan->language);
04571    /* Copy the FD's other than the generator fd */
04572    for (x = 0; x < AST_MAX_FDS; x++) {
04573       if (x != AST_GENERATOR_FD)
04574          ast_channel_set_fd(original, x, clonechan->fds[x]);
04575    }
04576 
04577    ast_app_group_update(clonechan, original);
04578 
04579    /* Move data stores over */
04580    if (AST_LIST_FIRST(&clonechan->datastores)) {
04581       struct ast_datastore *ds;
04582       /* We use a safe traversal here because some fixup routines actually
04583        * remove the datastore from the list and free them.
04584        */
04585       AST_LIST_TRAVERSE_SAFE_BEGIN(&clonechan->datastores, ds, entry) {
04586          if (ds->info->chan_fixup)
04587             ds->info->chan_fixup(ds->data, clonechan, original);
04588       }
04589       AST_LIST_TRAVERSE_SAFE_END;
04590       AST_LIST_APPEND_LIST(&original->datastores, &clonechan->datastores, entry);
04591    }
04592 
04593    clone_variables(original, clonechan);
04594    /* Presense of ADSI capable CPE follows clone */
04595    original->adsicpe = clonechan->adsicpe;
04596    /* Bridge remains the same */
04597    /* CDR fields remain the same */
04598    /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
04599    /* Application and data remain the same */
04600    /* Clone exception  becomes real one, as with fdno */
04601    ast_set_flag(original, ast_test_flag(clonechan, AST_FLAG_OUTGOING | AST_FLAG_EXCEPTION));
04602    original->fdno = clonechan->fdno;
04603    /* Schedule context remains the same */
04604    /* Stream stuff stays the same */
04605    /* Keep the original state.  The fixup code will need to work with it most likely */
04606 
04607    /* Just swap the whole structures, nevermind the allocations, they'll work themselves
04608       out. */
04609    tmpcid = original->cid;
04610    original->cid = clonechan->cid;
04611    clonechan->cid = tmpcid;
04612    report_new_callerid(original);
04613 
04614    /* Restore original timing file descriptor */
04615    ast_channel_set_fd(original, AST_TIMING_FD, original->timingfd);
04616 
04617    /* Our native formats are different now */
04618    original->nativeformats = clonechan->nativeformats;
04619 
04620    /* Context, extension, priority, app data, jump table,  remain the same */
04621    /* pvt switches.  pbx stays the same, as does next */
04622 
04623    /* Set the write format */
04624    ast_set_write_format(original, wformat);
04625 
04626    /* Set the read format */
04627    ast_set_read_format(original, rformat);
04628 
04629    /* Copy the music class */
04630    ast_string_field_set(original, musicclass, clonechan->musicclass);
04631 
04632    ast_debug(1, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
04633 
04634    /* Okay.  Last thing is to let the channel driver know about all this mess, so he
04635       can fix up everything as best as possible */
04636    if (original->tech->fixup) {
04637       res = original->tech->fixup(clonechan, original);
04638       if (res) {
04639          ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
04640             original->tech->type, original->name);
04641          ast_channel_unlock(clonechan);
04642          return -1;
04643       }
04644    } else
04645       ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
04646          original->tech->type, original->name);
04647 
04648    /* 
04649     * If an indication is currently playing, maintain it on the channel 
04650     * that is taking the place of original 
04651     *
04652     * This is needed because the masquerade is swapping out in the internals
04653     * of this channel, and the new channel private data needs to be made
04654     * aware of the current visible indication (RINGING, CONGESTION, etc.)
04655     */
04656    if (original->visible_indication) {
04657       ast_indicate(original, original->visible_indication);
04658    }
04659    
04660    /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
04661       a zombie so nothing tries to touch it.  If it's already been marked as a
04662       zombie, then free it now (since it already is considered invalid). */
04663    if (ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
04664       ast_debug(1, "Destroying channel clone '%s'\n", clonechan->name);
04665       ast_channel_unlock(clonechan);
04666       manager_event(EVENT_FLAG_CALL, "Hangup",
04667          "Channel: %s\r\n"
04668          "Uniqueid: %s\r\n"
04669          "Cause: %d\r\n"
04670          "Cause-txt: %s\r\n",
04671          clonechan->name,
04672          clonechan->uniqueid,
04673          clonechan->hangupcause,
04674          ast_cause2str(clonechan->hangupcause)
04675          );
04676       ast_channel_free(clonechan);
04677    } else {
04678       ast_debug(1, "Released clone lock on '%s'\n", clonechan->name);
04679       ast_set_flag(clonechan, AST_FLAG_ZOMBIE);
04680       ast_queue_frame(clonechan, &ast_null_frame);
04681       ast_channel_unlock(clonechan);
04682    }
04683 
04684    /* Signal any blocker */
04685    if (ast_test_flag(original, AST_FLAG_BLOCKING))
04686       pthread_kill(original->blocker, SIGURG);
04687    ast_debug(1, "Done Masquerading %s (%d)\n", original->name, original->_state);
04688    return 0;
04689 }
04690 
04691 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
04692 {
04693    ast_channel_lock(chan);
04694 
04695    if (cid_num) {
04696       if (chan->cid.cid_num)
04697          ast_free(chan->cid.cid_num);
04698       chan->cid.cid_num = ast_strdup(cid_num);
04699    }
04700    if (cid_name) {
04701       if (chan->cid.cid_name)
04702          ast_free(chan->cid.cid_name);
04703       chan->cid.cid_name = ast_strdup(cid_name);
04704    }
04705    if (cid_ani) {
04706       if (chan->cid.cid_ani)
04707          ast_free(chan->cid.cid_ani);
04708       chan->cid.cid_ani = ast_strdup(cid_ani);
04709    }
04710 
04711    report_new_callerid(chan);
04712 
04713    ast_channel_unlock(chan);
04714 }
04715 
04716 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
04717 {
04718    int oldstate = chan->_state;
04719    char name[AST_CHANNEL_NAME], *dashptr;
04720 
04721    if (oldstate == state)
04722       return 0;
04723 
04724    ast_copy_string(name, chan->name, sizeof(name));
04725    if ((dashptr = strrchr(name, '-'))) {
04726       *dashptr = '\0';
04727    }
04728 
04729    chan->_state = state;
04730 
04731    /* We have to pass AST_DEVICE_UNKNOWN here because it is entirely possible that the channel driver
04732     * for this channel is using the callback method for device state. If we pass in an actual state here
04733     * we override what they are saying the state is and things go amuck. */
04734    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
04735 
04736    /* setstate used to conditionally report Newchannel; this is no more */
04737    manager_event(EVENT_FLAG_CALL,
04738             "Newstate",
04739             "Channel: %s\r\n"
04740             "ChannelState: %d\r\n"
04741             "ChannelStateDesc: %s\r\n"
04742             "CallerIDNum: %s\r\n"
04743             "CallerIDName: %s\r\n"
04744             "Uniqueid: %s\r\n",
04745             chan->name, chan->_state, ast_state2str(chan->_state),
04746             S_OR(chan->cid.cid_num, ""),
04747             S_OR(chan->cid.cid_name, ""),
04748             chan->uniqueid);
04749 
04750    return 0;
04751 }
04752 
04753 /*! \brief Find bridged channel */
04754 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
04755 {
04756    struct ast_channel *bridged;
04757    bridged = chan->_bridge;
04758    if (bridged && bridged->tech->bridged_channel)
04759       bridged = bridged->tech->bridged_channel(chan, bridged);
04760    return bridged;
04761 }
04762 
04763 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
04764 {
04765    int min = 0, sec = 0, check;
04766 
04767    check = ast_autoservice_start(peer);
04768    if (check)
04769       return;
04770 
04771    if (remain > 0) {
04772       if (remain / 60 > 1) {
04773          min = remain / 60;
04774          sec = remain % 60;
04775       } else {
04776          sec = remain;
04777       }
04778    }
04779    
04780    if (!strcmp(sound,"timeleft")) { /* Queue support */
04781       ast_stream_and_wait(chan, "vm-youhave", "");
04782       if (min) {
04783          ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
04784          ast_stream_and_wait(chan, "queue-minutes", "");
04785       }
04786       if (sec) {
04787          ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
04788          ast_stream_and_wait(chan, "queue-seconds", "");
04789       }
04790    } else {
04791       ast_stream_and_wait(chan, sound, "");
04792    }
04793 
04794    ast_autoservice_stop(peer);
04795 }
04796 
04797 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
04798                    struct ast_bridge_config *config, struct ast_frame **fo,
04799                    struct ast_channel **rc, struct timeval bridge_end)
04800 {
04801    /* Copy voice back and forth between the two channels. */
04802    struct ast_channel *cs[3];
04803    struct ast_frame *f;
04804    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
04805    int o0nativeformats;
04806    int o1nativeformats;
04807    int watch_c0_dtmf;
04808    int watch_c1_dtmf;
04809    void *pvt0, *pvt1;
04810    /* Indicates whether a frame was queued into a jitterbuffer */
04811    int frame_put_in_jb = 0;
04812    int jb_in_use;
04813    int to;
04814    
04815    cs[0] = c0;
04816    cs[1] = c1;
04817    pvt0 = c0->tech_pvt;
04818    pvt1 = c1->tech_pvt;
04819    o0nativeformats = c0->nativeformats;
04820    o1nativeformats = c1->nativeformats;
04821    watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
04822    watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
04823 
04824    /* Check the need of a jitterbuffer for each channel */
04825    jb_in_use = ast_jb_do_usecheck(c0, c1);
04826    if (jb_in_use)
04827       ast_jb_empty_and_reset(c0, c1);
04828 
04829    ast_poll_channel_add(c0, c1);
04830 
04831    if (config->feature_timer > 0 && ast_tvzero(config->nexteventts)) {
04832       /* calculate when the bridge should possibly break
04833        * if a partial feature match timed out */
04834       config->partialfeature_timer = ast_tvadd(ast_tvnow(), ast_samp2tv(config->feature_timer, 1000));
04835    } else {
04836       memset(&config->partialfeature_timer, 0, sizeof(config->partialfeature_timer));
04837    }
04838 
04839    for (;;) {
04840       struct ast_channel *who, *other;
04841 
04842       if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
04843           (o0nativeformats != c0->nativeformats) ||
04844           (o1nativeformats != c1->nativeformats)) {
04845          /* Check for Masquerade, codec changes, etc */
04846          res = AST_BRIDGE_RETRY;
04847          break;
04848       }
04849       if (bridge_end.tv_sec) {
04850          to = ast_tvdiff_ms(bridge_end, ast_tvnow());
04851          if (to <= 0) {
04852             if (config->timelimit) {
04853                res = AST_BRIDGE_RETRY;
04854                /* generic bridge ending to play warning */
04855                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
04856             } else {
04857                res = AST_BRIDGE_COMPLETE;
04858             }
04859             break;
04860          }
04861       } else {
04862          /* If a feature has been started and the bridge is configured to 
04863           * to not break, leave the channel bridge when the feature timer
04864           * time has elapsed so the DTMF will be sent to the other side. 
04865           */
04866          if (!ast_tvzero(config->partialfeature_timer)) {
04867             int diff = ast_tvdiff_ms(config->partialfeature_timer, ast_tvnow());
04868             if (diff <= 0) {
04869                res = AST_BRIDGE_RETRY;
04870                break;
04871             }
04872          }
04873          to = -1;
04874       }
04875       /* Calculate the appropriate max sleep interval - in general, this is the time,
04876          left to the closest jb delivery moment */
04877       if (jb_in_use)
04878          to = ast_jb_get_when_to_wakeup(c0, c1, to);
04879       who = ast_waitfor_n(cs, 2, &to);
04880       if (!who) {
04881          /* No frame received within the specified timeout - check if we have to deliver now */
04882          if (jb_in_use)
04883             ast_jb_get_and_deliver(c0, c1);
04884          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
04885             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
04886                c0->_softhangup = 0;
04887             if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
04888                c1->_softhangup = 0;
04889             c0->_bridge = c1;
04890             c1->_bridge = c0;
04891          }
04892          continue;
04893       }
04894       f = ast_read(who);
04895       if (!f) {
04896          *fo = NULL;
04897          *rc = who;
04898          ast_debug(1, "Didn't get a frame from channel: %s\n",who->name);
04899          break;
04900       }
04901 
04902       other = (who == c0) ? c1 : c0; /* the 'other' channel */
04903       /* Try add the frame info the who's bridged channel jitterbuff */
04904       if (jb_in_use)
04905          frame_put_in_jb = !ast_jb_put(other, f);
04906 
04907       if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
04908          int bridge_exit = 0;
04909 
04910          switch (f->subclass) {
04911          case AST_CONTROL_HOLD:
04912          case AST_CONTROL_UNHOLD:
04913          case AST_CONTROL_VIDUPDATE:
04914          case AST_CONTROL_SRCUPDATE:
04915          case AST_CONTROL_SRCCHANGE:
04916          case AST_CONTROL_T38_PARAMETERS:
04917             ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
04918             if (jb_in_use) {
04919                ast_jb_empty_and_reset(c0, c1);
04920             }
04921             break;
04922          default:
04923             *fo = f;
04924             *rc = who;
04925             bridge_exit = 1;
04926             ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
04927             break;
04928          }
04929          if (bridge_exit)
04930             break;
04931       }
04932       if ((f->frametype == AST_FRAME_VOICE) ||
04933           (f->frametype == AST_FRAME_DTMF_BEGIN) ||
04934           (f->frametype == AST_FRAME_DTMF) ||
04935           (f->frametype == AST_FRAME_VIDEO) ||
04936           (f->frametype == AST_FRAME_IMAGE) ||
04937           (f->frametype == AST_FRAME_HTML) ||
04938           (f->frametype == AST_FRAME_MODEM) ||
04939           (f->frametype == AST_FRAME_TEXT)) {
04940          /* monitored dtmf causes exit from bridge */
04941          int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
04942 
04943          if (monitored_source && 
04944             (f->frametype == AST_FRAME_DTMF_END || 
04945             f->frametype == AST_FRAME_DTMF_BEGIN)) {
04946             *fo = f;
04947             *rc = who;
04948             ast_debug(1, "Got DTMF %s on channel (%s)\n", 
04949                f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
04950                who->name);
04951 
04952             break;
04953          }
04954          /* Write immediately frames, not passed through jb */
04955          if (!frame_put_in_jb)
04956             ast_write(other, f);
04957             
04958          /* Check if we have to deliver now */
04959          if (jb_in_use)
04960             ast_jb_get_and_deliver(c0, c1);
04961       }
04962       /* XXX do we want to pass on also frames not matched above ? */
04963       ast_frfree(f);
04964 
04965 #ifndef HAVE_EPOLL
04966       /* Swap who gets priority */
04967       cs[2] = cs[0];
04968       cs[0] = cs[1];
04969       cs[1] = cs[2];
04970 #endif
04971    }
04972 
04973    ast_poll_channel_del(c0, c1);
04974 
04975    return res;
04976 }
04977 
04978 /*! \brief Bridge two channels together (early) */
04979 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
04980 {
04981    /* Make sure we can early bridge, if not error out */
04982    if (!c0->tech->early_bridge || (c1 && (!c1->tech->early_bridge || c0->tech->early_bridge != c1->tech->early_bridge)))
04983       return -1;
04984 
04985    return c0->tech->early_bridge(c0, c1);
04986 }
04987 
04988 /*! \brief Send manager event for bridge link and unlink events.
04989  * \param onoff Link/Unlinked 
04990  * \param type 1 for core, 2 for native
04991  * \param c0 first channel in bridge
04992  * \param c1 second channel in bridge
04993 */
04994 static void manager_bridge_event(int onoff, int type, struct ast_channel *c0, struct ast_channel *c1)
04995 {
04996    manager_event(EVENT_FLAG_CALL, "Bridge",
04997          "Bridgestate: %s\r\n"
04998            "Bridgetype: %s\r\n"
04999             "Channel1: %s\r\n"
05000             "Channel2: %s\r\n"
05001             "Uniqueid1: %s\r\n"
05002             "Uniqueid2: %s\r\n"
05003             "CallerID1: %s\r\n"
05004             "CallerID2: %s\r\n",
05005          onoff ? "Link" : "Unlink",
05006          type == 1 ? "core" : "native",
05007          c0->name, c1->name, c0->uniqueid, c1->uniqueid, 
05008          S_OR(c0->cid.cid_num, ""), 
05009          S_OR(c1->cid.cid_num, ""));
05010 }
05011 
05012 static void update_bridge_vars(struct ast_channel *c0, struct ast_channel *c1)
05013 {
05014    const char *c0_name;
05015    const char *c1_name;
05016    const char *c0_pvtid = NULL;
05017    const char *c1_pvtid = NULL;
05018 
05019    ast_channel_lock(c1);
05020    c1_name = ast_strdupa(c1->name);
05021    if (c1->tech->get_pvt_uniqueid) {
05022       c1_pvtid = ast_strdupa(c1->tech->get_pvt_uniqueid(c1));
05023    }
05024    ast_channel_unlock(c1);
05025 
05026    ast_channel_lock(c0);
05027    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER"))) {
05028       pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1_name);
05029    }
05030    if (c1_pvtid) {
05031       pbx_builtin_setvar_helper(c0, "BRIDGEPVTCALLID", c1_pvtid);
05032    }
05033    c0_name = ast_strdupa(c0->name);
05034    if (c0->tech->get_pvt_uniqueid) {
05035       c0_pvtid = ast_strdupa(c0->tech->get_pvt_uniqueid(c0));
05036    }
05037    ast_channel_unlock(c0);
05038 
05039    ast_channel_lock(c1);
05040    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER"))) {
05041       pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0_name);
05042    }
05043    if (c0_pvtid) {
05044       pbx_builtin_setvar_helper(c1, "BRIDGEPVTCALLID", c0_pvtid);
05045    }
05046    ast_channel_unlock(c1);
05047 }
05048 
05049 static void bridge_play_sounds(struct ast_channel *c0, struct ast_channel *c1)
05050 {
05051    const char *s, *sound;
05052 
05053    /* See if we need to play an audio file to any side of the bridge */
05054 
05055    ast_channel_lock(c0);
05056    if ((s = pbx_builtin_getvar_helper(c0, "BRIDGE_PLAY_SOUND"))) {
05057       sound = ast_strdupa(s);
05058       ast_channel_unlock(c0);
05059       bridge_playfile(c0, c1, sound, 0);
05060       pbx_builtin_setvar_helper(c0, "BRIDGE_PLAY_SOUND", NULL);
05061    } else {
05062       ast_channel_unlock(c0);
05063    }
05064 
05065    ast_channel_lock(c1);
05066    if ((s = pbx_builtin_getvar_helper(c1, "BRIDGE_PLAY_SOUND"))) {
05067       sound = ast_strdupa(s);
05068       ast_channel_unlock(c1);
05069       bridge_playfile(c1, c0, sound, 0);
05070       pbx_builtin_setvar_helper(c1, "BRIDGE_PLAY_SOUND", NULL);
05071    } else {
05072       ast_channel_unlock(c1);
05073    }
05074 }
05075 
05076 /*! \brief Bridge two channels together */
05077 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
05078                  struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
05079 {
05080    struct ast_channel *who = NULL;
05081    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
05082    int nativefailed=0;
05083    int firstpass;
05084    int o0nativeformats;
05085    int o1nativeformats;
05086    long time_left_ms=0;
05087    char caller_warning = 0;
05088    char callee_warning = 0;
05089 
05090    if (c0->_bridge) {
05091       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
05092          c0->name, c0->_bridge->name);
05093       return -1;
05094    }
05095    if (c1->_bridge) {
05096       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
05097          c1->name, c1->_bridge->name);
05098       return -1;
05099    }
05100    
05101    /* Stop if we're a zombie or need a soft hangup */
05102    if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
05103        ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
05104       return -1;
05105 
05106    *fo = NULL;
05107    firstpass = config->firstpass;
05108    config->firstpass = 0;
05109 
05110    if (ast_tvzero(config->start_time))
05111       config->start_time = ast_tvnow();
05112    time_left_ms = config->timelimit;
05113 
05114    caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
05115    callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
05116 
05117    if (config->start_sound && firstpass) {
05118       if (caller_warning)
05119          bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
05120       if (callee_warning)
05121          bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
05122    }
05123 
05124    /* Keep track of bridge */
05125    c0->_bridge = c1;
05126    c1->_bridge = c0;
05127 
05128 
05129    o0nativeformats = c0->nativeformats;
05130    o1nativeformats = c1->nativeformats;
05131 
05132    if (config->feature_timer && !ast_tvzero(config->nexteventts)) {
05133       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
05134    } else if (config->timelimit && firstpass) {
05135       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
05136       if (caller_warning || callee_warning)
05137          config->nexteventts = ast_tvsub(config->nexteventts, ast_samp2tv(config->play_warning, 1000));
05138    }
05139 
05140    if (!c0->tech->send_digit_begin)
05141       ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
05142    if (!c1->tech->send_digit_begin)
05143       ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
05144    manager_bridge_event(1, 1, c0, c1);
05145 
05146    /* Before we enter in and bridge these two together tell them both the source of audio has changed */
05147    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
05148    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
05149 
05150    for (/* ever */;;) {
05151       struct timeval now = { 0, };
05152       int to;
05153 
05154       to = -1;
05155 
05156       if (!ast_tvzero(config->nexteventts)) {
05157          now = ast_tvnow();
05158          to = ast_tvdiff_ms(config->nexteventts, now);
05159          if (to <= 0) {
05160             if (!config->timelimit) {
05161                res = AST_BRIDGE_COMPLETE;
05162                break;
05163             }
05164             to = 0;
05165          }
05166       }
05167 
05168       if (config->timelimit) {
05169          time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
05170          if (time_left_ms < to)
05171             to = time_left_ms;
05172 
05173          if (time_left_ms <= 0) {
05174             if (caller_warning && config->end_sound)
05175                bridge_playfile(c0, c1, config->end_sound, 0);
05176             if (callee_warning && config->end_sound)
05177                bridge_playfile(c1, c0, config->end_sound, 0);
05178             *fo = NULL;
05179             if (who)
05180                *rc = who;
05181             res = 0;
05182             break;
05183          }
05184 
05185          if (!to) {
05186             if (time_left_ms >= 5000 && config->warning_sound && config->play_warning && ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
05187                int t = (time_left_ms + 500) / 1000; /* round to nearest second */
05188                if (caller_warning)
05189                   bridge_playfile(c0, c1, config->warning_sound, t);
05190                if (callee_warning)
05191                   bridge_playfile(c1, c0, config->warning_sound, t);
05192             }
05193             if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
05194                config->nexteventts = ast_tvadd(config->nexteventts, ast_samp2tv(config->warning_freq, 1000));
05195             else
05196                config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
05197          }
05198          ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
05199       }
05200 
05201       if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
05202          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
05203             c0->_softhangup = 0;
05204          if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
05205             c1->_softhangup = 0;
05206          c0->_bridge = c1;
05207          c1->_bridge = c0;
05208          ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
05209          continue;
05210       }
05211 
05212       /* Stop if we're a zombie or need a soft hangup */
05213       if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
05214           ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
05215          *fo = NULL;
05216          if (who)
05217             *rc = who;
05218          res = 0;
05219          ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
05220             c0->name, c1->name,
05221             ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
05222             ast_check_hangup(c0) ? "Yes" : "No",
05223             ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
05224             ast_check_hangup(c1) ? "Yes" : "No");
05225          break;
05226       }
05227 
05228       update_bridge_vars(c0, c1);
05229 
05230       bridge_play_sounds(c0, c1);
05231 
05232       if (c0->tech->bridge &&
05233          /* if < 1 ms remains use generic bridging for accurate timing */
05234          (!config->timelimit || to > 1000 || to == 0) &&
05235           (c0->tech->bridge == c1->tech->bridge) &&
05236           !nativefailed && !c0->monitor && !c1->monitor &&
05237           !c0->audiohooks && !c1->audiohooks &&
05238           !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
05239          int timeoutms = to - 1000 > 0 ? to - 1000 : to;
05240          /* Looks like they share a bridge method and nothing else is in the way */
05241          ast_set_flag(c0, AST_FLAG_NBRIDGE);
05242          ast_set_flag(c1, AST_FLAG_NBRIDGE);
05243          if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, timeoutms)) == AST_BRIDGE_COMPLETE) {
05244             /* \todo  XXX here should check that cid_num is not NULL */
05245             manager_event(EVENT_FLAG_CALL, "Unlink",
05246                      "Channel1: %s\r\n"
05247                      "Channel2: %s\r\n"
05248                      "Uniqueid1: %s\r\n"
05249                      "Uniqueid2: %s\r\n"
05250                      "CallerID1: %s\r\n"
05251                      "CallerID2: %s\r\n",
05252                      c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
05253             ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
05254 
05255             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
05256             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
05257 
05258             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
05259                continue;
05260 
05261             c0->_bridge = NULL;
05262             c1->_bridge = NULL;
05263 
05264             return res;
05265          } else {
05266             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
05267             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
05268          }
05269          switch (res) {
05270          case AST_BRIDGE_RETRY:
05271             if (config->play_warning) {
05272                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
05273             }
05274             continue;
05275          default:
05276             ast_verb(3, "Native bridging %s and %s ended\n", c0->name, c1->name);
05277             /* fallthrough */
05278          case AST_BRIDGE_FAILED_NOWARN:
05279             nativefailed++;
05280             break;
05281          }
05282       }
05283 
05284       if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
05285           (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
05286           !(c0->generator || c1->generator)) {
05287          if (ast_channel_make_compatible(c0, c1)) {
05288             ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
05289             manager_bridge_event(0, 1, c0, c1);
05290             return AST_BRIDGE_FAILED;
05291          }
05292          o0nativeformats = c0->nativeformats;
05293          o1nativeformats = c1->nativeformats;
05294       }
05295 
05296       update_bridge_vars(c0, c1);
05297 
05298       res = ast_generic_bridge(c0, c1, config, fo, rc, config->nexteventts);
05299       if (res != AST_BRIDGE_RETRY) {
05300          break;
05301       } else if (config->feature_timer) {
05302          /* feature timer expired but has not been updated, sending to ast_bridge_call to do so */
05303          break;
05304       }
05305    }
05306 
05307    ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
05308    ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
05309 
05310    /* Now that we have broken the bridge the source will change yet again */
05311    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
05312    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
05313 
05314    c0->_bridge = NULL;
05315    c1->_bridge = NULL;
05316 
05317    /* \todo  XXX here should check that cid_num is not NULL */
05318    manager_event(EVENT_FLAG_CALL, "Unlink",
05319             "Channel1: %s\r\n"
05320             "Channel2: %s\r\n"
05321             "Uniqueid1: %s\r\n"
05322             "Uniqueid2: %s\r\n"
05323             "CallerID1: %s\r\n"
05324             "CallerID2: %s\r\n",
05325             c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
05326    ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
05327 
05328    return res;
05329 }
05330 
05331 /*! \brief Sets an option on a channel */
05332 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
05333 {
05334    if (!chan->tech->setoption) {
05335       errno = ENOSYS;
05336       return -1;
05337    }
05338 
05339    if (block)
05340       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
05341 
05342    return chan->tech->setoption(chan, option, data, datalen);
05343 }
05344 
05345 int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
05346 {
05347    if (!chan->tech->queryoption) {
05348       errno = ENOSYS;
05349       return -1;
05350    }
05351 
05352    if (block)
05353       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
05354 
05355    return chan->tech->queryoption(chan, option, data, datalen);
05356 }
05357 
05358 struct tonepair_def {
05359    int freq1;
05360    int freq2;
05361    int duration;
05362    int vol;
05363 };
05364 
05365 struct tonepair_state {
05366    int fac1;
05367    int fac2;
05368    int v1_1;
05369    int v2_1;
05370    int v3_1;
05371    int v1_2;
05372    int v2_2;
05373    int v3_2;
05374    int origwfmt;
05375    int pos;
05376    int duration;
05377    int modulate;
05378    struct ast_frame f;
05379    unsigned char offset[AST_FRIENDLY_OFFSET];
05380    short data[4000];
05381 };
05382 
05383 static void tonepair_release(struct ast_channel *chan, void *params)
05384 {
05385    struct tonepair_state *ts = params;
05386 
05387    if (chan)
05388       ast_set_write_format(chan, ts->origwfmt);
05389    ast_free(ts);
05390 }
05391 
05392 static void *tonepair_alloc(struct ast_channel *chan, void *params)
05393 {
05394    struct tonepair_state *ts;
05395    struct tonepair_def *td = params;
05396 
05397    if (!(ts = ast_calloc(1, sizeof(*ts))))
05398       return NULL;
05399    ts->origwfmt = chan->writeformat;
05400    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
05401       ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
05402       tonepair_release(NULL, ts);
05403       ts = NULL;
05404    } else {
05405       ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
05406       ts->v1_1 = 0;
05407       ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
05408       ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
05409       ts->v2_1 = 0;
05410       ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
05411       ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
05412       ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
05413       ts->duration = td->duration;
05414       ts->modulate = 0;
05415    }
05416    /* Let interrupts interrupt :) */
05417    ast_set_flag(chan, AST_FLAG_WRITE_INT);
05418    return ts;
05419 }
05420 
05421 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
05422 {
05423    struct tonepair_state *ts = data;
05424    int x;
05425 
05426    /* we need to prepare a frame with 16 * timelen samples as we're
05427     * generating SLIN audio
05428     */
05429    len = samples * 2;
05430 
05431    if (len > sizeof(ts->data) / 2 - 1) {
05432       ast_log(LOG_WARNING, "Can't generate that much data!\n");
05433       return -1;
05434    }
05435    memset(&ts->f, 0, sizeof(ts->f));
05436    for (x=0;x<len/2;x++) {
05437       ts->v1_1 = ts->v2_1;
05438       ts->v2_1 = ts->v3_1;
05439       ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
05440       
05441       ts->v1_2 = ts->v2_2;
05442       ts->v2_2 = ts->v3_2;
05443       ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
05444       if (ts->modulate) {
05445          int p;
05446          p = ts->v3_2 - 32768;
05447          if (p < 0) p = -p;
05448          p = ((p * 9) / 10) + 1;
05449          ts->data[x] = (ts->v3_1 * p) >> 15;
05450       } else
05451          ts->data[x] = ts->v3_1 + ts->v3_2; 
05452    }
05453    ts->f.frametype = AST_FRAME_VOICE;
05454    ts->f.subclass = AST_FORMAT_SLINEAR;
05455    ts->f.datalen = len;
05456    ts->f.samples = samples;
05457    ts->f.offset = AST_FRIENDLY_OFFSET;
05458    ts->f.data.ptr = ts->data;
05459    ast_write(chan, &ts->f);
05460    ts->pos += x;
05461    if (ts->duration > 0) {
05462       if (ts->pos >= ts->duration * 8)
05463          return -1;
05464    }
05465    return 0;
05466 }
05467 
05468 static struct ast_generator tonepair = {
05469    alloc: tonepair_alloc,
05470    release: tonepair_release,
05471    generate: tonepair_generator,
05472 };
05473 
05474 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
05475 {
05476    struct tonepair_def d = { 0, };
05477 
05478    d.freq1 = freq1;
05479    d.freq2 = freq2;
05480    d.duration = duration;
05481    d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
05482    if (ast_activate_generator(chan, &tonepair, &d))
05483       return -1;
05484    return 0;
05485 }
05486 
05487 void ast_tonepair_stop(struct ast_channel *chan)
05488 {
05489    ast_deactivate_generator(chan);
05490 }
05491 
05492 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
05493 {
05494    int res;
05495 
05496    if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
05497       return res;
05498 
05499    /* Give us some wiggle room */
05500    while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
05501       struct ast_frame *f = ast_read(chan);
05502       if (f)
05503          ast_frfree(f);
05504       else
05505          return -1;
05506    }
05507    return 0;
05508 }
05509 
05510 ast_group_t ast_get_group(const char *s)
05511 {
05512    char *piece;
05513    char *c;
05514    int start=0, finish=0, x;
05515    ast_group_t group = 0;
05516 
05517    if (ast_strlen_zero(s))
05518       return 0;
05519 
05520    c = ast_strdupa(s);
05521    
05522    while ((piece = strsep(&c, ","))) {
05523       if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) {
05524          /* Range */
05525       } else if (sscanf(piece, "%30d", &start)) {
05526          /* Just one */
05527          finish = start;
05528       } else {
05529          ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
05530          continue;
05531       }
05532       for (x = start; x <= finish; x++) {
05533          if ((x > 63) || (x < 0)) {
05534             ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
05535          } else
05536             group |= ((ast_group_t) 1 << x);
05537       }
05538    }
05539    return group;
05540 }
05541 
05542 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
05543 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
05544 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
05545 
05546 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
05547              void (*stop_ptr)(struct ast_channel *),
05548              void (*cleanup_ptr)(struct ast_channel *))
05549 {
05550    ast_moh_start_ptr = start_ptr;
05551    ast_moh_stop_ptr = stop_ptr;
05552    ast_moh_cleanup_ptr = cleanup_ptr;
05553 }
05554 
05555 void ast_uninstall_music_functions(void)
05556 {
05557    ast_moh_start_ptr = NULL;
05558    ast_moh_stop_ptr = NULL;
05559    ast_moh_cleanup_ptr = NULL;
05560 }
05561 
05562 /*! \brief Turn on music on hold on a given channel */
05563 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
05564 {
05565    if (ast_moh_start_ptr)
05566       return ast_moh_start_ptr(chan, mclass, interpclass);
05567 
05568    ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));
05569 
05570    return 0;
05571 }
05572 
05573 /*! \brief Turn off music on hold on a given channel */
05574 void ast_moh_stop(struct ast_channel *chan)
05575 {
05576    if (ast_moh_stop_ptr)
05577       ast_moh_stop_ptr(chan);
05578 }
05579 
05580 void ast_moh_cleanup(struct ast_channel *chan)
05581 {
05582    if (ast_moh_cleanup_ptr)
05583       ast_moh_cleanup_ptr(chan);
05584 }
05585 
05586 void ast_channels_init(void)
05587 {
05588    ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));
05589 }
05590 
05591 /*! \brief Print call group and pickup group ---*/
05592 char *ast_print_group(char *buf, int buflen, ast_group_t group)
05593 {
05594    unsigned int i;
05595    int first = 1;
05596    char num[3];
05597 
05598    buf[0] = '\0';
05599    
05600    if (!group) /* Return empty string if no group */
05601       return buf;
05602 
05603    for (i = 0; i <= 63; i++) {   /* Max group is 63 */
05604       if (group & ((ast_group_t) 1 << i)) {
05605             if (!first) {
05606             strncat(buf, ", ", buflen - strlen(buf) - 1);
05607          } else {
05608             first = 0;
05609          }
05610          snprintf(num, sizeof(num), "%u", i);
05611          strncat(buf, num, buflen - strlen(buf) - 1);
05612       }
05613    }
05614    return buf;
05615 }
05616 
05617 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
05618 {
05619    struct ast_variable *cur;
05620 
05621    for (cur = vars; cur; cur = cur->next)
05622       pbx_builtin_setvar_helper(chan, cur->name, cur->value);  
05623 }
05624 
05625 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
05626 {
05627    /* just store the data pointer in the channel structure */
05628    return data;
05629 }
05630 
05631 static void silence_generator_release(struct ast_channel *chan, void *data)
05632 {
05633    /* nothing to do */
05634 }
05635 
05636 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
05637 {
05638    short buf[samples];
05639    struct ast_frame frame = {
05640       .frametype = AST_FRAME_VOICE,
05641       .subclass = AST_FORMAT_SLINEAR,
05642       .data.ptr = buf,
05643       .samples = samples,
05644       .datalen = sizeof(buf),
05645    };
05646 
05647    memset(buf, 0, sizeof(buf));
05648 
05649    if (ast_write(chan, &frame))
05650       return -1;
05651 
05652    return 0;
05653 }
05654 
05655 static struct ast_generator silence_generator = {
05656    .alloc = silence_generator_alloc,
05657    .release = silence_generator_release,
05658    .generate = silence_generator_generate,
05659 };
05660 
05661 struct ast_silence_generator {
05662    int old_write_format;
05663 };
05664 
05665 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
05666 {
05667    struct ast_silence_generator *state;
05668 
05669    if (!(state = ast_calloc(1, sizeof(*state)))) {
05670       return NULL;
05671    }
05672 
05673    state->old_write_format = chan->writeformat;
05674 
05675    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
05676       ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
05677       ast_free(state);
05678       return NULL;
05679    }
05680 
05681    ast_activate_generator(chan, &silence_generator, state);
05682 
05683    ast_debug(1, "Started silence generator on '%s'\n", chan->name);
05684 
05685    return state;
05686 }
05687 
05688 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
05689 {
05690    if (!state)
05691       return;
05692 
05693    ast_deactivate_generator(chan);
05694 
05695    ast_debug(1, "Stopped silence generator on '%s'\n", chan->name);
05696 
05697    if (ast_set_write_format(chan, state->old_write_format) < 0)
05698       ast_log(LOG_ERROR, "Could not return write format to its original state\n");
05699 
05700    ast_free(state);
05701 }
05702 
05703 
05704 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
05705 const char *channelreloadreason2txt(enum channelreloadreason reason)
05706 {
05707    switch (reason) {
05708    case CHANNEL_MODULE_LOAD:
05709       return "LOAD (Channel module load)";
05710 
05711    case CHANNEL_MODULE_RELOAD:
05712       return "RELOAD (Channel module reload)";
05713 
05714    case CHANNEL_CLI_RELOAD:
05715       return "CLIRELOAD (Channel module reload by CLI command)";
05716 
05717    default:
05718       return "MANAGERRELOAD (Channel module reload by manager)";
05719    }
05720 };
05721 
05722 #ifdef DEBUG_CHANNEL_LOCKS
05723 
05724 /*! \brief Unlock AST channel (and print debugging output) 
05725 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
05726 */
05727 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
05728 {
05729    int res = 0;
05730    ast_debug(3, "::::==== Unlocking AST channel %s\n", chan->name);
05731    
05732    if (!chan) {
05733       ast_debug(1, "::::==== Unlocking non-existing channel \n");
05734       return 0;
05735    }
05736 #ifdef DEBUG_THREADS
05737    res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
05738 #else
05739    res = ast_mutex_unlock(&chan->lock_dont_use);
05740 #endif
05741 
05742    if (option_debug > 2) {
05743 #ifdef DEBUG_THREADS
05744       int count = 0;
05745       if ((count = chan->lock_dont_use.track.reentrancy))
05746          ast_debug(3, ":::=== Still have %d locks (recursive)\n", count);
05747 #endif
05748       if (!res)
05749          ast_debug(3, "::::==== Channel %s was unlocked\n", chan->name);
05750       if (res == EINVAL) {
05751          ast_debug(3, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
05752       }
05753    }
05754    if (res == EPERM) {
05755       /* We had no lock, so okay any way*/
05756       ast_debug(4, "::::==== Channel %s was not locked at all \n", chan->name);
05757       res = 0;
05758    }
05759    return res;
05760 }
05761 
05762 /*! \brief Lock AST channel (and print debugging output)
05763 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
05764 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
05765 {
05766    int res;
05767 
05768    ast_debug(4, "====:::: Locking AST channel %s\n", chan->name);
05769 
05770 #ifdef DEBUG_THREADS
05771    res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
05772 #else
05773    res = ast_mutex_lock(&chan->lock_dont_use);
05774 #endif
05775 
05776    if (option_debug > 3) {
05777 #ifdef DEBUG_THREADS
05778       int count = 0;
05779       if ((count = chan->lock_dont_use.track.reentrancy))
05780          ast_debug(4, ":::=== Now have %d locks (recursive)\n", count);
05781 #endif
05782       if (!res)
05783          ast_debug(4, "::::==== Channel %s was locked\n", chan->name);
05784       if (res == EDEADLK) {
05785          /* We had no lock, so okey any way */
05786          ast_debug(4, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
05787       }
05788       if (res == EINVAL) {
05789          ast_debug(4, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
05790       }
05791    }
05792    return res;
05793 }
05794 
05795 /*! \brief Lock AST channel (and print debugging output)
05796 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
05797 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
05798 {
05799    int res;
05800 
05801    ast_debug(3, "====:::: Trying to lock AST channel %s\n", chan->name);
05802 #ifdef DEBUG_THREADS
05803    res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
05804 #else
05805    res = ast_mutex_trylock(&chan->lock_dont_use);
05806 #endif
05807 
05808    if (option_debug > 2) {
05809 #ifdef DEBUG_THREADS
05810       int count = 0;
05811       if ((count = chan->lock_dont_use.track.reentrancy))
05812          ast_debug(3, ":::=== Now have %d locks (recursive)\n", count);
05813 #endif
05814       if (!res)
05815          ast_debug(3, "::::==== Channel %s was locked\n", chan->name);
05816       if (res == EBUSY) {
05817          /* We failed to lock */
05818          ast_debug(3, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
05819       }
05820       if (res == EDEADLK) {
05821          /* We had no lock, so okey any way*/
05822          ast_debug(3, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
05823       }
05824       if (res == EINVAL)
05825          ast_debug(3, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
05826    }
05827    return res;
05828 }
05829 
05830 #endif
05831 
05832 /*
05833  * Wrappers for various ast_say_*() functions that call the full version
05834  * of the same functions.
05835  * The proper place would be say.c, but that file is optional and one
05836  * must be able to build asterisk even without it (using a loadable 'say'
05837  * implementation that only supplies the 'full' version of the functions.
05838  */
05839 
05840 int ast_say_number(struct ast_channel *chan, int num,
05841    const char *ints, const char *language, const char *options)
05842 {
05843    return ast_say_number_full(chan, num, ints, language, options, -1, -1);
05844 }
05845 
05846 int ast_say_enumeration(struct ast_channel *chan, int num,
05847    const char *ints, const char *language, const char *options)
05848 {
05849    return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
05850 }
05851 
05852 int ast_say_digits(struct ast_channel *chan, int num,
05853    const char *ints, const char *lang)
05854 {
05855    return ast_say_digits_full(chan, num, ints, lang, -1, -1);
05856 }
05857 
05858 int ast_say_digit_str(struct ast_channel *chan, const char *str,
05859    const char *ints, const char *lang)
05860 {
05861    return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
05862 }
05863 
05864 int ast_say_character_str(struct ast_channel *chan, const char *str,
05865    const char *ints, const char *lang)
05866 {
05867    return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
05868 }
05869 
05870 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
05871    const char *ints, const char *lang)
05872 {
05873    return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
05874 }
05875 
05876 int ast_say_digits_full(struct ast_channel *chan, int num,
05877    const char *ints, const char *lang, int audiofd, int ctrlfd)
05878 {
05879    char buf[256];
05880 
05881    snprintf(buf, sizeof(buf), "%d", num);
05882 
05883    return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
05884 }
05885 
05886 /* DO NOT PUT ADDITIONAL FUNCTIONS BELOW THIS BOUNDARY
05887  *
05888  * ONLY FUNCTIONS FOR PROVIDING BACKWARDS ABI COMPATIBILITY BELONG HERE
05889  *
05890  */
05891 
05892 /* Provide binary compatibility for modules that call ast_channel_alloc() directly;
05893  * newly compiled modules will call __ast_channel_alloc() via the macros in channel.h
05894  */
05895 #undef ast_channel_alloc
05896 struct ast_channel __attribute__((format(printf, 9, 10)))
05897    *ast_channel_alloc(int needqueue, int state, const char *cid_num,
05898             const char *cid_name, const char *acctcode,
05899             const char *exten, const char *context,
05900             const int amaflag, const char *name_fmt, ...);
05901 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num,
05902                   const char *cid_name, const char *acctcode,
05903                   const char *exten, const char *context,
05904                   const int amaflag, const char *name_fmt, ...)
05905 {
05906    va_list ap1, ap2;
05907    struct ast_channel *result;
05908 
05909 
05910    va_start(ap1, name_fmt);
05911    va_start(ap2, name_fmt);
05912    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
05913                amaflag, __FILE__, __LINE__, __FUNCTION__, name_fmt, ap1, ap2);
05914    va_end(ap1);
05915    va_end(ap2);
05916 
05917    return result;
05918 }