Fri Jul 15 2011 11:58:00

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