Thu Apr 28 2011 17:15:21

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: 305889 $")
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    }
02804 
02805 #ifdef AST_DEVMODE
02806    /* 
02807     * The ast_waitfor() code records which of the channel's file descriptors reported that
02808     * data is available.  In theory, ast_read() should only be called after ast_waitfor()
02809     * reports that a channel has data available for reading.  However, there still may be
02810     * some edge cases throughout the code where ast_read() is called improperly.  This can
02811     * potentially cause problems, so if this is a developer build, make a lot of noise if
02812     * this happens so that it can be addressed. 
02813     */
02814    if (chan->fdno == -1) {
02815       ast_log(LOG_ERROR, "ast_read() called with no recorded file descriptor.\n");
02816    }
02817 #endif
02818 
02819    prestate = chan->_state;
02820 
02821    /* Read and ignore anything on the alertpipe, but read only
02822       one sizeof(blah) per frame that we send from it */
02823    if (chan->alertpipe[0] > -1) {
02824       int flags = fcntl(chan->alertpipe[0], F_GETFL);
02825       /* For some odd reason, the alertpipe occasionally loses nonblocking status,
02826        * which immediately causes a deadlock scenario.  Detect and prevent this. */
02827       if ((flags & O_NONBLOCK) == 0) {
02828          ast_log(LOG_ERROR, "Alertpipe on channel %s lost O_NONBLOCK?!!\n", chan->name);
02829          if (fcntl(chan->alertpipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
02830             ast_log(LOG_WARNING, "Unable to set alertpipe nonblocking! (%d: %s)\n", errno, strerror(errno));
02831             f = &ast_null_frame;
02832             goto done;
02833          }
02834       }
02835       if (read(chan->alertpipe[0], &blah, sizeof(blah)) < 0) {
02836          if (errno != EINTR && errno != EAGAIN)
02837             ast_log(LOG_WARNING, "read() failed: %s\n", strerror(errno));
02838       }
02839    }
02840 
02841    if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD) {
02842       enum ast_timer_event res;
02843 
02844       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02845 
02846       res = ast_timer_get_event(chan->timer);
02847 
02848       switch (res) {
02849       case AST_TIMING_EVENT_EXPIRED:
02850          ast_timer_ack(chan->timer, 1);
02851 
02852          if (chan->timingfunc) {
02853             /* save a copy of func/data before unlocking the channel */
02854             int (*func)(const void *) = chan->timingfunc;
02855             void *data = chan->timingdata;
02856             chan->fdno = -1;
02857             ast_channel_unlock(chan);
02858             func(data);
02859          } else {
02860             ast_timer_set_rate(chan->timer, 0);
02861             chan->fdno = -1;
02862             ast_channel_unlock(chan);
02863          }
02864 
02865          /* cannot 'goto done' because the channel is already unlocked */
02866          return &ast_null_frame;
02867 
02868       case AST_TIMING_EVENT_CONTINUOUS:
02869          if (AST_LIST_EMPTY(&chan->readq) || 
02870             !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
02871             ast_timer_disable_continuous(chan->timer);
02872          }
02873          break;
02874       }
02875 
02876    } else if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
02877       /* if the AST_GENERATOR_FD is set, call the generator with args
02878        * set to -1 so it can do whatever it needs to.
02879        */
02880       void *tmp = chan->generatordata;
02881       chan->generatordata = NULL;     /* reset to let ast_write get through */
02882       chan->generator->generate(chan, tmp, -1, -1);
02883       chan->generatordata = tmp;
02884       f = &ast_null_frame;
02885       chan->fdno = -1;
02886       goto done;
02887    }
02888 
02889    /* Check for pending read queue */
02890    if (!AST_LIST_EMPTY(&chan->readq)) {
02891       int skip_dtmf = should_skip_dtmf(chan);
02892 
02893       AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->readq, f, frame_list) {
02894          /* We have to be picky about which frame we pull off of the readq because
02895           * there are cases where we want to leave DTMF frames on the queue until
02896           * some later time. */
02897 
02898          if ( (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) && skip_dtmf) {
02899             continue;
02900          }
02901 
02902          AST_LIST_REMOVE_CURRENT(frame_list);
02903          break;
02904       }
02905       AST_LIST_TRAVERSE_SAFE_END;
02906       
02907       if (!f) {
02908          /* There were no acceptable frames on the readq. */
02909          f = &ast_null_frame;
02910          if (chan->alertpipe[0] > -1) {
02911             int poke = 0;
02912             /* Restore the state of the alertpipe since we aren't ready for any
02913              * of the frames in the readq. */
02914             if (write(chan->alertpipe[1], &poke, sizeof(poke)) != sizeof(poke)) {
02915                ast_log(LOG_ERROR, "Failed to write to alertpipe: %s\n", strerror(errno));
02916             }
02917          }
02918       }
02919 
02920       /* Interpret hangup and end-of-Q frames to return NULL */
02921       /* XXX why not the same for frames from the channel ? */
02922       if (f->frametype == AST_FRAME_CONTROL) {
02923          switch (f->subclass) {
02924          case AST_CONTROL_HANGUP:
02925             chan->_softhangup |= AST_SOFTHANGUP_DEV;
02926             cause = f->data.uint32;
02927             /* Fall through */
02928          case AST_CONTROL_END_OF_Q:
02929             ast_frfree(f);
02930             f = NULL;
02931             break;
02932          default:
02933             break;
02934          }
02935       }
02936    } else {
02937       chan->blocker = pthread_self();
02938       if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
02939          if (chan->tech->exception)
02940             f = chan->tech->exception(chan);
02941          else {
02942             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
02943             f = &ast_null_frame;
02944          }
02945          /* Clear the exception flag */
02946          ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02947       } else if (chan->tech->read)
02948          f = chan->tech->read(chan);
02949       else
02950          ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
02951    }
02952 
02953    /*
02954     * Reset the recorded file descriptor that triggered this read so that we can
02955     * easily detect when ast_read() is called without properly using ast_waitfor().
02956     */
02957    chan->fdno = -1;
02958 
02959    if (f) {
02960       struct ast_frame *readq_tail = AST_LIST_LAST(&chan->readq);
02961 
02962       /* if the channel driver returned more than one frame, stuff the excess
02963          into the readq for the next ast_read call
02964       */
02965       if (AST_LIST_NEXT(f, frame_list)) {
02966          ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list));
02967          ast_frfree(AST_LIST_NEXT(f, frame_list));
02968          AST_LIST_NEXT(f, frame_list) = NULL;
02969       }
02970 
02971       switch (f->frametype) {
02972       case AST_FRAME_CONTROL:
02973          if (f->subclass == AST_CONTROL_ANSWER) {
02974             if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
02975                ast_debug(1, "Ignoring answer on an inbound call!\n");
02976                ast_frfree(f);
02977                f = &ast_null_frame;
02978             } else if (prestate == AST_STATE_UP && ast_bridged_channel(chan)) {
02979                ast_debug(1, "Dropping duplicate answer!\n");
02980                ast_frfree(f);
02981                f = &ast_null_frame;
02982             } else {
02983                /* Answer the CDR */
02984                ast_setstate(chan, AST_STATE_UP);
02985                /* removed a call to ast_cdr_answer(chan->cdr) from here. */
02986             }
02987          }
02988          break;
02989       case AST_FRAME_DTMF_END:
02990          send_dtmf_event(chan, "Received", f->subclass, "No", "Yes");
02991          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
02992          /* Queue it up if DTMF is deferred, or if DTMF emulation is forced. */
02993          if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) || ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
02994             queue_dtmf_readq(chan, f);
02995             ast_frfree(f);
02996             f = &ast_null_frame;
02997          } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
02998             if (!ast_tvzero(chan->dtmf_tv) && 
02999                 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
03000                /* If it hasn't been long enough, defer this digit */
03001                queue_dtmf_readq(chan, f);
03002                ast_frfree(f);
03003                f = &ast_null_frame;
03004             } else {
03005                /* There was no begin, turn this into a begin and send the end later */
03006                f->frametype = AST_FRAME_DTMF_BEGIN;
03007                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
03008                chan->emulate_dtmf_digit = f->subclass;
03009                chan->dtmf_tv = ast_tvnow();
03010                if (f->len) {
03011                   if (f->len > AST_MIN_DTMF_DURATION)
03012                      chan->emulate_dtmf_duration = f->len;
03013                   else 
03014                      chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
03015                } else
03016                   chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
03017                ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
03018             }
03019             if (chan->audiohooks) {
03020                struct ast_frame *old_frame = f;
03021                /*!
03022                 * \todo XXX It is possible to write a digit to the audiohook twice
03023                 * if the digit was originally read while the channel was in autoservice. */
03024                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03025                if (old_frame != f)
03026                   ast_frfree(old_frame);
03027             }
03028          } else {
03029             struct timeval now = ast_tvnow();
03030             if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03031                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
03032                ast_clear_flag(chan, AST_FLAG_IN_DTMF);
03033                if (!f->len)
03034                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03035 
03036                /* detect tones that were received on
03037                 * the wire with durations shorter than
03038                 * AST_MIN_DTMF_DURATION and set f->len
03039                 * to the actual duration of the DTMF
03040                 * frames on the wire.  This will cause
03041                 * dtmf emulation to be triggered later
03042                 * on.
03043                 */
03044                if (ast_tvdiff_ms(now, chan->dtmf_tv) < AST_MIN_DTMF_DURATION) {
03045                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03046                   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);
03047                }
03048             } else if (!f->len) {
03049                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
03050                f->len = AST_MIN_DTMF_DURATION;
03051             }
03052             if (f->len < AST_MIN_DTMF_DURATION && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
03053                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);
03054                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
03055                chan->emulate_dtmf_digit = f->subclass;
03056                chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
03057                ast_frfree(f);
03058                f = &ast_null_frame;
03059             } else {
03060                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
03061                if (f->len < AST_MIN_DTMF_DURATION) {
03062                   f->len = AST_MIN_DTMF_DURATION;
03063                }
03064                chan->dtmf_tv = now;
03065             }
03066             if (chan->audiohooks) {
03067                struct ast_frame *old_frame = f;
03068                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03069                if (old_frame != f)
03070                   ast_frfree(old_frame);
03071             }
03072          }
03073          break;
03074       case AST_FRAME_DTMF_BEGIN:
03075          send_dtmf_event(chan, "Received", f->subclass, "Yes", "No");
03076          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
03077          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
03078              (!ast_tvzero(chan->dtmf_tv) && 
03079                ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
03080             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
03081             ast_frfree(f);
03082             f = &ast_null_frame;
03083          } else {
03084             ast_set_flag(chan, AST_FLAG_IN_DTMF);
03085             chan->dtmf_tv = ast_tvnow();
03086             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
03087          }
03088          break;
03089       case AST_FRAME_NULL:
03090          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
03091           * is reached , because we want to make sure we pass at least one
03092           * voice frame through before starting the next digit, to ensure a gap
03093           * between DTMF digits. */
03094          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
03095             struct timeval now = ast_tvnow();
03096             if (!chan->emulate_dtmf_duration) {
03097                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03098                chan->emulate_dtmf_digit = 0;
03099             } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
03100                chan->emulate_dtmf_duration = 0;
03101                ast_frfree(f);
03102                f = &chan->dtmff;
03103                f->frametype = AST_FRAME_DTMF_END;
03104                f->subclass = chan->emulate_dtmf_digit;
03105                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03106                chan->dtmf_tv = now;
03107                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03108                chan->emulate_dtmf_digit = 0;
03109                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
03110                if (chan->audiohooks) {
03111                   struct ast_frame *old_frame = f;
03112                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03113                   if (old_frame != f) {
03114                      ast_frfree(old_frame);
03115                   }
03116                }
03117             }
03118          }
03119          break;
03120       case AST_FRAME_VOICE:
03121          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
03122           * is reached , because we want to make sure we pass at least one
03123           * voice frame through before starting the next digit, to ensure a gap
03124           * between DTMF digits. */
03125          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
03126             ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
03127             chan->emulate_dtmf_digit = 0;
03128          }
03129 
03130          if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03131             if (dropaudio)
03132                ast_read_generator_actions(chan, f);
03133             ast_frfree(f);
03134             f = &ast_null_frame;
03135          }
03136 
03137          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
03138             struct timeval now = ast_tvnow();
03139             if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
03140                chan->emulate_dtmf_duration = 0;
03141                ast_frfree(f);
03142                f = &chan->dtmff;
03143                f->frametype = AST_FRAME_DTMF_END;
03144                f->subclass = chan->emulate_dtmf_digit;
03145                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
03146                chan->dtmf_tv = now;
03147                if (chan->audiohooks) {
03148                   struct ast_frame *old_frame = f;
03149                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03150                   if (old_frame != f)
03151                      ast_frfree(old_frame);
03152                }
03153                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
03154             } else {
03155                /* Drop voice frames while we're still in the middle of the digit */
03156                ast_frfree(f);
03157                f = &ast_null_frame;
03158             }
03159          } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
03160             /* This frame is not one of the current native formats -- drop it on the floor */
03161             char to[200];
03162             ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
03163                chan->name, ast_getformatname(f->subclass), ast_getformatname_multiple(to, sizeof(to), chan->nativeformats));
03164             ast_frfree(f);
03165             f = &ast_null_frame;
03166          } else if ((f->frametype == AST_FRAME_VOICE)) {
03167             /* Send frame to audiohooks if present */
03168             if (chan->audiohooks) {
03169                struct ast_frame *old_frame = f;
03170                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
03171                if (old_frame != f)
03172                   ast_frfree(old_frame);
03173             }
03174             if (chan->monitor && chan->monitor->read_stream ) {
03175                /* XXX what does this do ? */
03176 #ifndef MONITOR_CONSTANT_DELAY
03177                int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
03178                if (jump >= 0) {
03179                   jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03180                   if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
03181                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
03182                   chan->insmpl += (chan->outsmpl - chan->insmpl) + f->samples;
03183                } else
03184                   chan->insmpl+= f->samples;
03185 #else
03186                int jump = calc_monitor_jump((chan->outsmpl - chan->insmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03187                if (jump - MONITOR_DELAY >= 0) {
03188                   if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
03189                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
03190                   chan->insmpl += chan->outsmpl - chan->insmpl;
03191                } else
03192                   chan->insmpl += f->samples;
03193 #endif
03194                if (chan->monitor->state == AST_MONITOR_RUNNING) {
03195                   if (ast_writestream(chan->monitor->read_stream, f) < 0)
03196                      ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
03197                }
03198             }
03199 
03200             if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL) {
03201                f = &ast_null_frame;
03202             }
03203 
03204             /* it is possible for the translation process on chan->readtrans to have
03205                produced multiple frames from the single input frame we passed it; if
03206                this happens, queue the additional frames *before* the frames we may
03207                have queued earlier. if the readq was empty, put them at the head of
03208                the queue, and if it was not, put them just after the frame that was
03209                at the end of the queue.
03210             */
03211             if (AST_LIST_NEXT(f, frame_list)) {
03212                if (!readq_tail) {
03213                   ast_queue_frame_head(chan, AST_LIST_NEXT(f, frame_list));
03214                } else {
03215                   __ast_queue_frame(chan, AST_LIST_NEXT(f, frame_list), 0, readq_tail);
03216                }
03217                ast_frfree(AST_LIST_NEXT(f, frame_list));
03218                AST_LIST_NEXT(f, frame_list) = NULL;
03219             }
03220 
03221             /* Run generator sitting on the line if timing device not available
03222             * and synchronous generation of outgoing frames is necessary       */
03223             ast_read_generator_actions(chan, f);
03224          }
03225       default:
03226          /* Just pass it on! */
03227          break;
03228       }
03229    } else {
03230       /* Make sure we always return NULL in the future */
03231       if (!chan->_softhangup) {
03232          chan->_softhangup |= AST_SOFTHANGUP_DEV;
03233       }
03234       if (cause)
03235          chan->hangupcause = cause;
03236       if (chan->generator)
03237          ast_deactivate_generator(chan);
03238       /* We no longer End the CDR here */
03239    }
03240 
03241    /* High bit prints debugging */
03242    if (chan->fin & DEBUGCHAN_FLAG)
03243       ast_frame_dump(chan->name, f, "<<");
03244    chan->fin = FRAMECOUNT_INC(chan->fin);
03245 
03246 done:
03247    if (chan->music_state && chan->generator && chan->generator->digit && f && f->frametype == AST_FRAME_DTMF_END)
03248       chan->generator->digit(chan, f->subclass);
03249 
03250    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
03251       /* The list gets recreated if audiohooks are added again later */
03252       ast_audiohook_detach_list(chan->audiohooks);
03253       chan->audiohooks = NULL;
03254    }
03255    ast_channel_unlock(chan);
03256    return f;
03257 }
03258 
03259 int ast_internal_timing_enabled(struct ast_channel *chan)
03260 {
03261    return (ast_opt_internal_timing && chan->timingfd > -1);
03262 }
03263 
03264 struct ast_frame *ast_read(struct ast_channel *chan)
03265 {
03266    return __ast_read(chan, 0);
03267 }
03268 
03269 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
03270 {
03271    return __ast_read(chan, 1);
03272 }
03273 
03274 int ast_indicate(struct ast_channel *chan, int condition)
03275 {
03276    return ast_indicate_data(chan, condition, NULL, 0);
03277 }
03278 
03279 static int attribute_const is_visible_indication(enum ast_control_frame_type condition)
03280 {
03281    /* Don't include a default case here so that we get compiler warnings
03282     * when a new type is added. */
03283 
03284    switch (condition) {
03285    case AST_CONTROL_PROGRESS:
03286    case AST_CONTROL_PROCEEDING:
03287    case AST_CONTROL_VIDUPDATE:
03288    case AST_CONTROL_SRCUPDATE:
03289    case AST_CONTROL_SRCCHANGE:
03290    case AST_CONTROL_RADIO_KEY:
03291    case AST_CONTROL_RADIO_UNKEY:
03292    case AST_CONTROL_OPTION:
03293    case AST_CONTROL_WINK:
03294    case AST_CONTROL_FLASH:
03295    case AST_CONTROL_OFFHOOK:
03296    case AST_CONTROL_TAKEOFFHOOK:
03297    case AST_CONTROL_ANSWER:
03298    case AST_CONTROL_HANGUP:
03299    case AST_CONTROL_T38_PARAMETERS:
03300    case _XXX_AST_CONTROL_T38:
03301    case AST_CONTROL_END_OF_Q:
03302       break;
03303 
03304    case AST_CONTROL_CONGESTION:
03305    case AST_CONTROL_BUSY:
03306    case AST_CONTROL_RINGING:
03307    case AST_CONTROL_RING:
03308    case AST_CONTROL_HOLD:
03309    case AST_CONTROL_UNHOLD:
03310       return 1;
03311    }
03312 
03313    return 0;
03314 }
03315 
03316 int ast_indicate_data(struct ast_channel *chan, int _condition,
03317       const void *data, size_t datalen)
03318 {
03319    /* By using an enum, we'll get compiler warnings for values not handled 
03320     * in switch statements. */
03321    enum ast_control_frame_type condition = _condition;
03322    struct ast_tone_zone_sound *ts = NULL;
03323    int res = -1;
03324 
03325    ast_channel_lock(chan);
03326 
03327    /* Don't bother if the channel is about to go away, anyway. */
03328    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03329       ast_channel_unlock(chan);
03330       return -1;
03331    }
03332 
03333    if (chan->tech->indicate) {
03334       /* See if the channel driver can handle this condition. */
03335       res = chan->tech->indicate(chan, condition, data, datalen);
03336    }
03337 
03338    ast_channel_unlock(chan);
03339 
03340    if (!res) {
03341       /* The channel driver successfully handled this indication */
03342       if (is_visible_indication(condition)) {
03343          chan->visible_indication = condition;
03344       }
03345       return 0;
03346    }
03347 
03348    /* The channel driver does not support this indication, let's fake
03349     * it by doing our own tone generation if applicable. */
03350 
03351    /*!\note If we compare the enumeration type, which does not have any
03352     * negative constants, the compiler may optimize this code away.
03353     * Therefore, we must perform an integer comparison here. */
03354    if (_condition < 0) {
03355       /* Stop any tones that are playing */
03356       ast_playtones_stop(chan);
03357       return 0;
03358    }
03359 
03360    /* Handle conditions that we have tones for. */
03361    switch (condition) {
03362    case _XXX_AST_CONTROL_T38:
03363       /* deprecated T.38 control frame */
03364       return -1;
03365    case AST_CONTROL_T38_PARAMETERS:
03366       /* there is no way to provide 'default' behavior for these
03367        * control frames, so we need to return failure, but there
03368        * is also no value in the log message below being emitted
03369        * since failure to handle these frames is not an 'error'
03370        * so just return right now. in addition, we want to return
03371        * whatever value the channel driver returned, in case it
03372        * has some meaning.*/
03373       return res;
03374    case AST_CONTROL_RINGING:
03375       ts = ast_get_indication_tone(chan->zone, "ring");
03376       /* It is common practice for channel drivers to return -1 if trying
03377        * to indicate ringing on a channel which is up. The idea is to let the
03378        * core generate the ringing inband. However, we don't want the
03379        * warning message about not being able to handle the specific indication
03380        * to print nor do we want ast_indicate_data to return an "error" for this
03381        * condition
03382        */
03383       if (chan->_state == AST_STATE_UP) {
03384          res = 0;
03385       }
03386       break;
03387    case AST_CONTROL_BUSY:
03388       ts = ast_get_indication_tone(chan->zone, "busy");
03389       break;
03390    case AST_CONTROL_CONGESTION:
03391       ts = ast_get_indication_tone(chan->zone, "congestion");
03392       break;
03393    case AST_CONTROL_PROGRESS:
03394    case AST_CONTROL_PROCEEDING:
03395    case AST_CONTROL_VIDUPDATE:
03396    case AST_CONTROL_SRCUPDATE:
03397    case AST_CONTROL_SRCCHANGE:
03398    case AST_CONTROL_RADIO_KEY:
03399    case AST_CONTROL_RADIO_UNKEY:
03400    case AST_CONTROL_OPTION:
03401    case AST_CONTROL_WINK:
03402    case AST_CONTROL_FLASH:
03403    case AST_CONTROL_OFFHOOK:
03404    case AST_CONTROL_TAKEOFFHOOK:
03405    case AST_CONTROL_ANSWER:
03406    case AST_CONTROL_HANGUP:
03407    case AST_CONTROL_RING:
03408    case AST_CONTROL_HOLD:
03409    case AST_CONTROL_UNHOLD:
03410    case AST_CONTROL_END_OF_Q:
03411       /* Nothing left to do for these. */
03412       res = 0;
03413       break;
03414    }
03415 
03416    if (ts) {
03417       /* We have a tone to play, yay. */
03418       ast_debug(1, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
03419       res = ast_playtones_start(chan, 0, ts->data, 1);
03420       ts = ast_tone_zone_sound_unref(ts);
03421       chan->visible_indication = condition;
03422    }
03423 
03424    if (res) {
03425       /* not handled */
03426       ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
03427    }
03428 
03429    return res;
03430 }
03431 
03432 int ast_recvchar(struct ast_channel *chan, int timeout)
03433 {
03434    int c;
03435    char *buf = ast_recvtext(chan, timeout);
03436    if (buf == NULL)
03437       return -1;  /* error or timeout */
03438    c = *(unsigned char *)buf;
03439    ast_free(buf);
03440    return c;
03441 }
03442 
03443 char *ast_recvtext(struct ast_channel *chan, int timeout)
03444 {
03445    int res, done = 0;
03446    char *buf = NULL;
03447    
03448    while (!done) {
03449       struct ast_frame *f;
03450       if (ast_check_hangup(chan))
03451          break;
03452       res = ast_waitfor(chan, timeout);
03453       if (res <= 0) /* timeout or error */
03454          break;
03455       timeout = res; /* update timeout */
03456       f = ast_read(chan);
03457       if (f == NULL)
03458          break; /* no frame */
03459       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
03460          done = 1;   /* force a break */
03461       else if (f->frametype == AST_FRAME_TEXT) {      /* what we want */
03462          buf = ast_strndup((char *) f->data.ptr, f->datalen);  /* dup and break */
03463          done = 1;
03464       }
03465       ast_frfree(f);
03466    }
03467    return buf;
03468 }
03469 
03470 int ast_sendtext(struct ast_channel *chan, const char *text)
03471 {
03472    int res = 0;
03473 
03474    ast_channel_lock(chan);
03475    /* Stop if we're a zombie or need a soft hangup */
03476    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
03477       ast_channel_unlock(chan);
03478       return -1;
03479    }
03480    CHECK_BLOCKING(chan);
03481    if (chan->tech->send_text)
03482       res = chan->tech->send_text(chan, text);
03483    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03484    ast_channel_unlock(chan);
03485    return res;
03486 }
03487 
03488 int ast_senddigit_begin(struct ast_channel *chan, char digit)
03489 {
03490    /* Device does not support DTMF tones, lets fake
03491     * it by doing our own generation. */
03492    static const char* dtmf_tones[] = {
03493       "941+1336", /* 0 */
03494       "697+1209", /* 1 */
03495       "697+1336", /* 2 */
03496       "697+1477", /* 3 */
03497       "770+1209", /* 4 */
03498       "770+1336", /* 5 */
03499       "770+1477", /* 6 */
03500       "852+1209", /* 7 */
03501       "852+1336", /* 8 */
03502       "852+1477", /* 9 */
03503       "697+1633", /* A */
03504       "770+1633", /* B */
03505       "852+1633", /* C */
03506       "941+1633", /* D */
03507       "941+1209", /* * */
03508       "941+1477"  /* # */
03509    };
03510 
03511    if (!chan->tech->send_digit_begin)
03512       return 0;
03513 
03514    if (!chan->tech->send_digit_begin(chan, digit))
03515       return 0;
03516 
03517    if (digit >= '0' && digit <='9')
03518       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
03519    else if (digit >= 'A' && digit <= 'D')
03520       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
03521    else if (digit == '*')
03522       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
03523    else if (digit == '#')
03524       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
03525    else {
03526       /* not handled */
03527       ast_debug(1, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
03528    }
03529 
03530    return 0;
03531 }
03532 
03533 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
03534 {
03535    int res = -1;
03536 
03537    if (chan->tech->send_digit_end)
03538       res = chan->tech->send_digit_end(chan, digit, duration);
03539 
03540    if (res && chan->generator)
03541       ast_playtones_stop(chan);
03542    
03543    return 0;
03544 }
03545 
03546 int ast_senddigit(struct ast_channel *chan, char digit, unsigned int duration)
03547 {
03548    if (chan->tech->send_digit_begin) {
03549       ast_senddigit_begin(chan, digit);
03550       ast_safe_sleep(chan, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
03551    }
03552    
03553    return ast_senddigit_end(chan, digit, (duration >= AST_DEFAULT_EMULATE_DTMF_DURATION ? duration : AST_DEFAULT_EMULATE_DTMF_DURATION));
03554 }
03555 
03556 int ast_prod(struct ast_channel *chan)
03557 {
03558    struct ast_frame a = { AST_FRAME_VOICE };
03559    char nothing[128];
03560 
03561    /* Send an empty audio frame to get things moving */
03562    if (chan->_state != AST_STATE_UP) {
03563       ast_debug(1, "Prodding channel '%s'\n", chan->name);
03564       a.subclass = chan->rawwriteformat;
03565       a.data.ptr = nothing + AST_FRIENDLY_OFFSET;
03566       a.src = "ast_prod"; /* this better match check in ast_write */
03567       if (ast_write(chan, &a))
03568          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
03569    }
03570    return 0;
03571 }
03572 
03573 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
03574 {
03575    int res;
03576    if (!chan->tech->write_video)
03577       return 0;
03578    res = ast_write(chan, fr);
03579    if (!res)
03580       res = 1;
03581    return res;
03582 }
03583 
03584 struct plc_ds {
03585    /* A buffer in which to store SLIN PLC
03586     * samples generated by the generic PLC
03587     * functionality in plc.c
03588     */
03589    int16_t *samples_buf;
03590    /* The current number of samples in the
03591     * samples_buf
03592     */
03593    size_t num_samples;
03594    plc_state_t plc_state;
03595 };
03596 
03597 static void plc_ds_destroy(void *data)
03598 {
03599    struct plc_ds *plc = data;
03600    ast_free(plc->samples_buf);
03601    ast_free(plc);
03602 }
03603 
03604 static struct ast_datastore_info plc_ds_info = {
03605    .type = "plc",
03606    .destroy = plc_ds_destroy,
03607 };
03608 
03609 static void adjust_frame_for_plc(struct ast_channel *chan, struct ast_frame *frame, struct ast_datastore *datastore)
03610 {
03611    int num_new_samples = frame->samples;
03612    struct plc_ds *plc = datastore->data;
03613 
03614    /* As a general note, let me explain the somewhat odd calculations used when taking
03615     * the frame offset into account here. According to documentation in frame.h, the frame's
03616     * offset field indicates the number of bytes that the audio is offset. The plc->samples_buf
03617     * is not an array of bytes, but rather an array of 16-bit integers since it holds SLIN
03618     * samples. So I had two choices to make here with the offset.
03619     * 
03620     * 1. Make the offset AST_FRIENDLY_OFFSET bytes. The main downside for this is that
03621     *    I can't just add AST_FRIENDLY_OFFSET to the plc->samples_buf and have the pointer
03622     *    arithmetic come out right. I would have to do some odd casting or division for this to
03623     *    work as I wanted.
03624     * 2. Make the offset AST_FRIENDLY_OFFSET * 2 bytes. This allows the pointer arithmetic
03625     *    to work out better with the plc->samples_buf. The downside here is that the buffer's
03626     *    allocation contains an extra 64 bytes of unused space.
03627     * 
03628     * I decided to go with option 2. This is why in the calloc statement and the statement that
03629     * sets the frame's offset, AST_FRIENDLY_OFFSET is multiplied by 2.
03630     */
03631 
03632    /* If this audio frame has no samples to fill in, ignore it */
03633    if (!num_new_samples) {
03634       return;
03635    }
03636 
03637    /* First, we need to be sure that our buffer is large enough to accomodate
03638     * the samples we need to fill in. This will likely only occur on the first
03639     * frame we write.
03640     */
03641    if (plc->num_samples < num_new_samples) {
03642       ast_free(plc->samples_buf);
03643       plc->samples_buf = ast_calloc(1, (num_new_samples * sizeof(*plc->samples_buf)) + (AST_FRIENDLY_OFFSET * 2));
03644       if (!plc->samples_buf) {
03645          ast_channel_datastore_remove(chan, datastore);
03646          ast_datastore_free(datastore);
03647          return;
03648       }
03649       plc->num_samples = num_new_samples;
03650    }
03651 
03652    if (frame->datalen == 0) {
03653       plc_fillin(&plc->plc_state, plc->samples_buf + AST_FRIENDLY_OFFSET, frame->samples);
03654       frame->data.ptr = plc->samples_buf + AST_FRIENDLY_OFFSET;
03655       frame->datalen = num_new_samples * 2;
03656       frame->offset = AST_FRIENDLY_OFFSET * 2;
03657    } else {
03658       plc_rx(&plc->plc_state, frame->data.ptr, frame->samples);
03659    }
03660 }
03661 
03662 static void apply_plc(struct ast_channel *chan, struct ast_frame *frame)
03663 {
03664    struct ast_datastore *datastore;
03665    struct plc_ds *plc;
03666 
03667    datastore = ast_channel_datastore_find(chan, &plc_ds_info, NULL);
03668    if (datastore) {
03669       plc = datastore->data;
03670       adjust_frame_for_plc(chan, frame, datastore);
03671       return;
03672    }
03673 
03674    datastore = ast_datastore_alloc(&plc_ds_info, NULL);
03675    if (!datastore) {
03676       return;
03677    }
03678    plc = ast_calloc(1, sizeof(*plc));
03679    if (!plc) {
03680       ast_datastore_free(datastore);
03681       return;
03682    }
03683    datastore->data = plc;
03684    ast_channel_datastore_add(chan, datastore);
03685    adjust_frame_for_plc(chan, frame, datastore);
03686 }
03687 
03688 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
03689 {
03690    int res = -1;
03691    struct ast_frame *f = NULL;
03692    int count = 0;
03693 
03694    /*Deadlock avoidance*/
03695    while(ast_channel_trylock(chan)) {
03696       /*cannot goto done since the channel is not locked*/
03697       if(count++ > 10) {
03698          ast_debug(1, "Deadlock avoided for write to channel '%s'\n", chan->name);
03699          return 0;
03700       }
03701       usleep(1);
03702    }
03703    /* Stop if we're a zombie or need a soft hangup */
03704    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
03705       goto done;
03706 
03707    /* Handle any pending masquerades */
03708    if (chan->masq && ast_do_masquerade(chan)) {
03709       ast_log(LOG_WARNING, "Failed to perform masquerade\n");
03710       goto done;
03711    }
03712    if (chan->masqr) {
03713       res = 0; /* XXX explain, why 0 ? */
03714       goto done;
03715    }
03716    if (chan->generatordata && (!fr->src || strcasecmp(fr->src, "ast_prod"))) {
03717       if (ast_test_flag(chan, AST_FLAG_WRITE_INT)) {
03718             ast_deactivate_generator(chan);
03719       } else {
03720          if (fr->frametype == AST_FRAME_DTMF_END) {
03721             /* There is a generator running while we're in the middle of a digit.
03722              * It's probably inband DTMF, so go ahead and pass it so it can
03723              * stop the generator */
03724             ast_clear_flag(chan, AST_FLAG_BLOCKING);
03725             ast_channel_unlock(chan);
03726             res = ast_senddigit_end(chan, fr->subclass, fr->len);
03727             ast_channel_lock(chan);
03728             CHECK_BLOCKING(chan);
03729          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
03730             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
03731             res = (chan->tech->indicate == NULL) ? 0 :
03732                chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
03733          }
03734          res = 0; /* XXX explain, why 0 ? */
03735          goto done;
03736       }
03737    }
03738    /* High bit prints debugging */
03739    if (chan->fout & DEBUGCHAN_FLAG)
03740       ast_frame_dump(chan->name, fr, ">>");
03741    CHECK_BLOCKING(chan);
03742    switch (fr->frametype) {
03743    case AST_FRAME_CONTROL:
03744       res = (chan->tech->indicate == NULL) ? 0 :
03745          chan->tech->indicate(chan, fr->subclass, fr->data.ptr, fr->datalen);
03746       break;
03747    case AST_FRAME_DTMF_BEGIN:
03748       if (chan->audiohooks) {
03749          struct ast_frame *old_frame = fr;
03750          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
03751          if (old_frame != fr)
03752             f = fr;
03753       }
03754       send_dtmf_event(chan, "Sent", fr->subclass, "Yes", "No");
03755       ast_clear_flag(chan, AST_FLAG_BLOCKING);
03756       ast_channel_unlock(chan);
03757       res = ast_senddigit_begin(chan, fr->subclass);
03758       ast_channel_lock(chan);
03759       CHECK_BLOCKING(chan);
03760       break;
03761    case AST_FRAME_DTMF_END:
03762       if (chan->audiohooks) {
03763          struct ast_frame *new_frame = fr;
03764 
03765          new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
03766          if (new_frame != fr) {
03767             ast_frfree(new_frame);
03768          }
03769       }
03770       send_dtmf_event(chan, "Sent", fr->subclass, "No", "Yes");
03771       ast_clear_flag(chan, AST_FLAG_BLOCKING);
03772       ast_channel_unlock(chan);
03773       res = ast_senddigit_end(chan, fr->subclass, fr->len);
03774       ast_channel_lock(chan);
03775       CHECK_BLOCKING(chan);
03776       break;
03777    case AST_FRAME_TEXT:
03778       if (fr->subclass == AST_FORMAT_T140) {
03779          res = (chan->tech->write_text == NULL) ? 0 :
03780             chan->tech->write_text(chan, fr);
03781       } else {
03782          res = (chan->tech->send_text == NULL) ? 0 :
03783             chan->tech->send_text(chan, (char *) fr->data.ptr);
03784       }
03785       break;
03786    case AST_FRAME_HTML:
03787       res = (chan->tech->send_html == NULL) ? 0 :
03788          chan->tech->send_html(chan, fr->subclass, (char *) fr->data.ptr, fr->datalen);
03789       break;
03790    case AST_FRAME_VIDEO:
03791       /* XXX Handle translation of video codecs one day XXX */
03792       res = (chan->tech->write_video == NULL) ? 0 :
03793          chan->tech->write_video(chan, fr);
03794       break;
03795    case AST_FRAME_MODEM:
03796       res = (chan->tech->write == NULL) ? 0 :
03797          chan->tech->write(chan, fr);
03798       break;
03799    case AST_FRAME_VOICE:
03800       if (chan->tech->write == NULL)
03801          break;   /*! \todo XXX should return 0 maybe ? */
03802 
03803       if (ast_opt_generic_plc && fr->subclass == AST_FORMAT_SLINEAR) {
03804          apply_plc(chan, fr);
03805       }
03806 
03807       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
03808       if (fr->subclass == chan->rawwriteformat)
03809          f = fr;
03810       else
03811          f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
03812 
03813       if (!f) {
03814          res = 0;
03815          break;
03816       }
03817 
03818       if (chan->audiohooks) {
03819          struct ast_frame *prev = NULL, *new_frame, *cur, *dup;
03820          int freeoldlist = 0;
03821 
03822          if (f != fr) {
03823             freeoldlist = 1;
03824          }
03825 
03826          /* Since ast_audiohook_write may return a new frame, and the cur frame is
03827           * an item in a list of frames, create a new list adding each cur frame back to it
03828           * regardless if the cur frame changes or not. */
03829          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
03830             new_frame = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, cur);
03831 
03832             /* if this frame is different than cur, preserve the end of the list,
03833              * free the old frames, and set cur to be the new frame */
03834             if (new_frame != cur) {
03835 
03836                /* doing an ast_frisolate here seems silly, but we are not guaranteed the new_frame
03837                 * isn't part of local storage, meaning if ast_audiohook_write is called multiple
03838                 * times it may override the previous frame we got from it unless we dup it */
03839                if ((dup = ast_frisolate(new_frame))) {
03840                   AST_LIST_NEXT(dup, frame_list) = AST_LIST_NEXT(cur, frame_list);
03841                   if (freeoldlist) {
03842                      AST_LIST_NEXT(cur, frame_list) = NULL;
03843                      ast_frfree(cur);
03844                   }
03845                   if (new_frame != dup) {
03846                      ast_frfree(new_frame);
03847                   }
03848                   cur = dup;
03849                }
03850             }
03851 
03852             /* now, regardless if cur is new or not, add it to the new list,
03853              * if the new list has not started, cur will become the first item. */
03854             if (prev) {
03855                AST_LIST_NEXT(prev, frame_list) = cur;
03856             } else {
03857                f = cur; /* set f to be the beginning of our new list */
03858             }
03859             prev = cur;
03860          }
03861       }
03862       
03863       /* If Monitor is running on this channel, then we have to write frames out there too */
03864       /* the translator on chan->writetrans may have returned multiple frames
03865          from the single frame we passed in; if so, feed each one of them to the
03866          monitor */
03867       if (chan->monitor && chan->monitor->write_stream) {
03868          struct ast_frame *cur;
03869 
03870          for (cur = f; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
03871          /* XXX must explain this code */
03872 #ifndef MONITOR_CONSTANT_DELAY
03873             int jump = chan->insmpl - chan->outsmpl - 4 * cur->samples;
03874             if (jump >= 0) {
03875                jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03876                if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
03877                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
03878                chan->outsmpl += (chan->insmpl - chan->outsmpl) + cur->samples;
03879             } else {
03880                chan->outsmpl += cur->samples;
03881             }
03882 #else
03883             int jump = calc_monitor_jump((chan->insmpl - chan->outsmpl), ast_format_rate(f->subclass), ast_format_rate(chan->monitor->read_stream->fmt->format));
03884             if (jump - MONITOR_DELAY >= 0) {
03885                if (ast_seekstream(chan->monitor->write_stream, jump - cur->samples, SEEK_FORCECUR) == -1)
03886                   ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
03887                chan->outsmpl += chan->insmpl - chan->outsmpl;
03888             } else {
03889                chan->outsmpl += cur->samples;
03890             }
03891 #endif
03892             if (chan->monitor->state == AST_MONITOR_RUNNING) {
03893                if (ast_writestream(chan->monitor->write_stream, cur) < 0)
03894                   ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
03895             }
03896          }
03897       }
03898 
03899       /* the translator on chan->writetrans may have returned multiple frames
03900          from the single frame we passed in; if so, feed each one of them to the
03901          channel, freeing each one after it has been written */
03902       if ((f != fr) && AST_LIST_NEXT(f, frame_list)) {
03903          struct ast_frame *cur, *next;
03904          unsigned int skip = 0;
03905 
03906          for (cur = f, next = AST_LIST_NEXT(cur, frame_list);
03907               cur;
03908               cur = next, next = cur ? AST_LIST_NEXT(cur, frame_list) : NULL) {
03909             if (!skip) {
03910                if ((res = chan->tech->write(chan, cur)) < 0) {
03911                   chan->_softhangup |= AST_SOFTHANGUP_DEV;
03912                   skip = 1;
03913                } else if (next) {
03914                   /* don't do this for the last frame in the list,
03915                      as the code outside the loop will do it once
03916                   */
03917                   chan->fout = FRAMECOUNT_INC(chan->fout);
03918                }
03919             }
03920             ast_frfree(cur);
03921          }
03922 
03923          /* reset f so the code below doesn't attempt to free it */
03924          f = NULL;
03925       } else {
03926          res = chan->tech->write(chan, f);
03927       }
03928       break;
03929    case AST_FRAME_NULL:
03930    case AST_FRAME_IAX:
03931       /* Ignore these */
03932       res = 0;
03933       break;
03934    default:
03935       /* At this point, fr is the incoming frame and f is NULL.  Channels do
03936        * not expect to get NULL as a frame pointer and will segfault.  Hence,
03937        * we output the original frame passed in. */
03938       res = chan->tech->write(chan, fr);
03939       break;
03940    }
03941 
03942    if (f && f != fr)
03943       ast_frfree(f);
03944    ast_clear_flag(chan, AST_FLAG_BLOCKING);
03945 
03946    /* Consider a write failure to force a soft hangup */
03947    if (res < 0) {
03948       chan->_softhangup |= AST_SOFTHANGUP_DEV;
03949    } else {
03950       chan->fout = FRAMECOUNT_INC(chan->fout);
03951    }
03952 done:
03953    if (chan->audiohooks && ast_audiohook_write_list_empty(chan->audiohooks)) {
03954       /* The list gets recreated if audiohooks are added again later */
03955       ast_audiohook_detach_list(chan->audiohooks);
03956       chan->audiohooks = NULL;
03957    }
03958    ast_channel_unlock(chan);
03959    return res;
03960 }
03961 
03962 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
03963             struct ast_trans_pvt **trans, const int direction)
03964 {
03965    int native;
03966    int res;
03967    char from[200], to[200];
03968    
03969    /* Make sure we only consider audio */
03970    fmt &= AST_FORMAT_AUDIO_MASK;
03971    
03972    native = chan->nativeformats;
03973 
03974    if (!fmt || !native) /* No audio requested */
03975       return 0;   /* Let's try a call without any sounds (video, text) */
03976    
03977    /* Find a translation path from the native format to one of the desired formats */
03978    if (!direction)
03979       /* reading */
03980       res = ast_translator_best_choice(&fmt, &native);
03981    else
03982       /* writing */
03983       res = ast_translator_best_choice(&native, &fmt);
03984 
03985    if (res < 0) {
03986       ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
03987          ast_getformatname_multiple(from, sizeof(from), native),
03988          ast_getformatname_multiple(to, sizeof(to), fmt));
03989       return -1;
03990    }
03991    
03992    /* Now we have a good choice for both. */
03993    ast_channel_lock(chan);
03994 
03995    if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
03996       /* the channel is already in these formats, so nothing to do */
03997       ast_channel_unlock(chan);
03998       return 0;
03999    }
04000 
04001    *rawformat = native;
04002    /* User perspective is fmt */
04003    *format = fmt;
04004    /* Free any read translation we have right now */
04005    if (*trans) {
04006       ast_translator_free_path(*trans);
04007       *trans = NULL;
04008    }
04009    /* Build a translation path from the raw format to the desired format */
04010    if (*format == *rawformat) {
04011       /*
04012        * If we were able to swap the native format to the format that
04013        * has been requested, then there is no need to try to build
04014        * a translation path.
04015        */
04016       res = 0;
04017    } else {
04018       if (!direction) {
04019          /* reading */
04020          *trans = ast_translator_build_path(*format, *rawformat);
04021       } else {
04022          /* writing */
04023          *trans = ast_translator_build_path(*rawformat, *format);
04024       }
04025       res = *trans ? 0 : -1;
04026    }
04027    ast_channel_unlock(chan);
04028    ast_debug(1, "Set channel %s to %s format %s\n", chan->name,
04029       direction ? "write" : "read", ast_getformatname(fmt));
04030    return res;
04031 }
04032 
04033 int ast_set_read_format(struct ast_channel *chan, int fmt)
04034 {
04035    return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
04036            &chan->readtrans, 0);
04037 }
04038 
04039 int ast_set_write_format(struct ast_channel *chan, int fmt)
04040 {
04041    return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
04042            &chan->writetrans, 1);
04043 }
04044 
04045 const char *ast_channel_reason2str(int reason)
04046 {
04047    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
04048    {
04049    case 0:
04050       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
04051    case AST_CONTROL_HANGUP:
04052       return "Hangup";
04053    case AST_CONTROL_RING:
04054       return "Local Ring";
04055    case AST_CONTROL_RINGING:
04056       return "Remote end Ringing";
04057    case AST_CONTROL_ANSWER:
04058       return "Remote end has Answered";
04059    case AST_CONTROL_BUSY:
04060       return "Remote end is Busy";
04061    case AST_CONTROL_CONGESTION:
04062       return "Congestion (circuits busy)";
04063    default:
04064       return "Unknown Reason!!";
04065    }
04066 }
04067 
04068 static void handle_cause(int cause, int *outstate)
04069 {
04070    if (outstate) {
04071       /* compute error and return */
04072       if (cause == AST_CAUSE_BUSY)
04073          *outstate = AST_CONTROL_BUSY;
04074       else if (cause == AST_CAUSE_CONGESTION)
04075          *outstate = AST_CONTROL_CONGESTION;
04076       else
04077          *outstate = 0;
04078    }
04079 }
04080 
04081 struct ast_channel *ast_call_forward(struct ast_channel *caller, struct ast_channel *orig, int *timeout, int format, struct outgoing_helper *oh, int *outstate)
04082 {
04083    char tmpchan[256];
04084    struct ast_channel *new = NULL;
04085    char *data, *type;
04086    int cause = 0;
04087    int res;
04088 
04089    /* gather data and request the new forward channel */
04090    ast_copy_string(tmpchan, orig->call_forward, sizeof(tmpchan));
04091    if ((data = strchr(tmpchan, '/'))) {
04092       *data++ = '\0';
04093       type = tmpchan;
04094    } else {
04095       const char *forward_context;
04096       ast_channel_lock(orig);
04097       forward_context = pbx_builtin_getvar_helper(orig, "FORWARD_CONTEXT");
04098       snprintf(tmpchan, sizeof(tmpchan), "%s@%s", orig->call_forward, S_OR(forward_context, orig->context));
04099       ast_channel_unlock(orig);
04100       data = tmpchan;
04101       type = "Local";
04102    }
04103    if (!(new = ast_request(type, format, data, &cause))) {
04104       ast_log(LOG_NOTICE, "Unable to create channel for call forward to '%s/%s' (cause = %d)\n", type, data, cause);
04105       handle_cause(cause, outstate);
04106       ast_hangup(orig);
04107       return NULL;
04108    }
04109 
04110    /* Copy/inherit important information into new channel */
04111    if (oh) {
04112       if (oh->vars) {
04113          ast_set_variables(new, oh->vars);
04114       }
04115       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name)) {
04116          ast_set_callerid(new, oh->cid_num, oh->cid_name, oh->cid_num);
04117       }
04118       if (oh->parent_channel) {
04119          ast_channel_inherit_variables(oh->parent_channel, new);
04120          ast_channel_datastore_inherit(oh->parent_channel, new);
04121       }
04122       if (oh->account) {
04123          ast_cdr_setaccount(new, oh->account);
04124       }
04125    } else if (caller) { /* no outgoing helper so use caller if avaliable */
04126       ast_channel_inherit_variables(caller, new);
04127       ast_channel_datastore_inherit(caller, new);
04128    }
04129 
04130    ast_channel_lock(orig);
04131    while (ast_channel_trylock(new)) {
04132       CHANNEL_DEADLOCK_AVOIDANCE(orig);
04133    }
04134    ast_copy_flags(new->cdr, orig->cdr, AST_CDR_FLAG_ORIGINATED);
04135    ast_string_field_set(new, accountcode, orig->accountcode);
04136    if (!ast_strlen_zero(orig->cid.cid_num) && !ast_strlen_zero(new->cid.cid_name)) {
04137       ast_set_callerid(new, orig->cid.cid_num, orig->cid.cid_name, orig->cid.cid_num);
04138    }
04139    ast_channel_unlock(new);
04140    ast_channel_unlock(orig);
04141 
04142    /* call new channel */
04143    res = ast_call(new, data, 0);
04144    if (timeout) {
04145       *timeout = res;
04146    }
04147    if (res) {
04148       ast_log(LOG_NOTICE, "Unable to call forward to channel %s/%s\n", type, (char *)data);
04149       ast_hangup(orig);
04150       ast_hangup(new);
04151       return NULL;
04152    }
04153    ast_hangup(orig);
04154 
04155    return new;
04156 }
04157 
04158 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)
04159 {
04160    int dummy_outstate;
04161    int cause = 0;
04162    struct ast_channel *chan;
04163    int res = 0;
04164    int last_subclass = 0;
04165    
04166    if (outstate)
04167       *outstate = 0;
04168    else
04169       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
04170 
04171    chan = ast_request(type, format, data, &cause);
04172    if (!chan) {
04173       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
04174       handle_cause(cause, outstate);
04175       return NULL;
04176    }
04177 
04178    if (oh) {
04179       if (oh->vars)  
04180          ast_set_variables(chan, oh->vars);
04181       /* XXX why is this necessary, for the parent_channel perhaps ? */
04182       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
04183          ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
04184       if (oh->parent_channel) {
04185          ast_channel_inherit_variables(oh->parent_channel, chan);
04186          ast_channel_datastore_inherit(oh->parent_channel, chan);
04187       }
04188       if (oh->account)
04189          ast_cdr_setaccount(chan, oh->account); 
04190    }
04191    ast_set_callerid(chan, cid_num, cid_name, cid_num);
04192    ast_set_flag(chan->cdr, AST_CDR_FLAG_ORIGINATED);
04193 
04194    if (ast_call(chan, data, 0)) {   /* ast_call failed... */
04195       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
04196    } else {
04197       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
04198       while (timeout && chan->_state != AST_STATE_UP) {
04199          struct ast_frame *f;
04200          res = ast_waitfor(chan, timeout);
04201          if (res == 0) { /* timeout, treat it like ringing */
04202             *outstate = AST_CONTROL_RINGING;
04203             break;
04204          }
04205          if (res < 0) /* error or done */
04206             break;
04207          if (timeout > -1)
04208             timeout = res;
04209          if (!ast_strlen_zero(chan->call_forward)) {
04210             if (!(chan = ast_call_forward(NULL, chan, NULL, format, oh, outstate))) {
04211                return NULL;
04212             }
04213             continue;
04214          }
04215 
04216          f = ast_read(chan);
04217          if (!f) {
04218             *outstate = AST_CONTROL_HANGUP;
04219             res = 0;
04220             break;
04221          }
04222          if (f->frametype == AST_FRAME_CONTROL) {
04223             switch (f->subclass) {
04224             case AST_CONTROL_RINGING:  /* record but keep going */
04225                *outstate = f->subclass;
04226                break;
04227 
04228             case AST_CONTROL_BUSY:
04229                ast_cdr_busy(chan->cdr);
04230                *outstate = f->subclass;
04231                timeout = 0;
04232                break;
04233 
04234             case AST_CONTROL_CONGESTION:
04235                ast_cdr_failed(chan->cdr);
04236                *outstate = f->subclass;
04237                timeout = 0;
04238                break;
04239 
04240             case AST_CONTROL_ANSWER:
04241                ast_cdr_answer(chan->cdr);
04242                *outstate = f->subclass;
04243                timeout = 0;      /* trick to force exit from the while() */
04244                break;
04245 
04246             /* Ignore these */
04247             case AST_CONTROL_PROGRESS:
04248             case AST_CONTROL_PROCEEDING:
04249             case AST_CONTROL_HOLD:
04250             case AST_CONTROL_UNHOLD:
04251             case AST_CONTROL_VIDUPDATE:
04252             case AST_CONTROL_SRCUPDATE:
04253             case AST_CONTROL_SRCCHANGE:
04254             case -1:       /* Ignore -- just stopping indications */
04255                break;
04256 
04257             default:
04258                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
04259             }
04260             last_subclass = f->subclass;
04261          }
04262          ast_frfree(f);
04263       }
04264    }
04265 
04266    /* Final fixups */
04267    if (oh) {
04268       if (!ast_strlen_zero(oh->context))
04269          ast_copy_string(chan->context, oh->context, sizeof(chan->context));
04270       if (!ast_strlen_zero(oh->exten))
04271          ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
04272       if (oh->priority) 
04273          chan->priority = oh->priority;
04274    }
04275    if (chan->_state == AST_STATE_UP)
04276       *outstate = AST_CONTROL_ANSWER;
04277 
04278    if (res <= 0) {
04279       if ( AST_CONTROL_RINGING == last_subclass ) 
04280          chan->hangupcause = AST_CAUSE_NO_ANSWER;
04281       if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
04282          ast_cdr_init(chan->cdr, chan);
04283       if (chan->cdr) {
04284          char tmp[256];
04285          snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
04286          ast_cdr_setapp(chan->cdr,"Dial",tmp);
04287          ast_cdr_update(chan);
04288          ast_cdr_start(chan->cdr);
04289          ast_cdr_end(chan->cdr);
04290          /* If the cause wasn't handled properly */
04291          if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
04292             ast_cdr_failed(chan->cdr);
04293       }
04294       ast_hangup(chan);
04295       chan = NULL;
04296    }
04297    return chan;
04298 }
04299 
04300 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
04301 {
04302    return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
04303 }
04304 
04305 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
04306 {
04307    struct chanlist *chan;
04308    struct ast_channel *c;
04309    int capabilities;
04310    int fmt;
04311    int res;
04312    int foo;
04313    int videoformat = format & AST_FORMAT_VIDEO_MASK;
04314    int textformat = format & AST_FORMAT_TEXT_MASK;
04315 
04316    if (!cause)
04317       cause = &foo;
04318    *cause = AST_CAUSE_NOTDEFINED;
04319 
04320    if (AST_RWLIST_RDLOCK(&channels)) {
04321       ast_log(LOG_WARNING, "Unable to lock channel list\n");
04322       return NULL;
04323    }
04324 
04325    AST_LIST_TRAVERSE(&backends, chan, list) {
04326       if (strcasecmp(type, chan->tech->type))
04327          continue;
04328 
04329       capabilities = chan->tech->capabilities;
04330       fmt = format & AST_FORMAT_AUDIO_MASK;
04331       if (fmt) {
04332          /* We have audio - is it possible to connect the various calls to each other? 
04333             (Avoid this check for calls without audio, like text+video calls)
04334          */
04335          res = ast_translator_best_choice(&fmt, &capabilities);
04336          if (res < 0) {
04337             ast_log(LOG_WARNING, "No translator path exists for channel type %s (native 0x%x) to 0x%x\n", type, chan->tech->capabilities, format);
04338             *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
04339             AST_RWLIST_UNLOCK(&channels);
04340             return NULL;
04341          }
04342       }
04343       AST_RWLIST_UNLOCK(&channels);
04344       if (!chan->tech->requester)
04345          return NULL;
04346       
04347       if (!(c = chan->tech->requester(type, capabilities | videoformat | textformat, data, cause)))
04348          return NULL;
04349       
04350       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
04351       return c;
04352    }
04353 
04354    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
04355    *cause = AST_CAUSE_NOSUCHDRIVER;
04356    AST_RWLIST_UNLOCK(&channels);
04357 
04358    return NULL;
04359 }
04360 
04361 int ast_call(struct ast_channel *chan, char *addr, int timeout)
04362 {
04363    /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
04364       If the remote end does not answer within the timeout, then do NOT hang up, but
04365       return anyway.  */
04366    int res = -1;
04367    /* Stop if we're a zombie or need a soft hangup */
04368    ast_channel_lock(chan);
04369    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
04370       if (chan->cdr) {
04371          ast_set_flag(chan->cdr, AST_CDR_FLAG_DIALED);
04372       }
04373       if (chan->tech->call)
04374          res = chan->tech->call(chan, addr, timeout);
04375       ast_set_flag(chan, AST_FLAG_OUTGOING);
04376    }
04377    ast_channel_unlock(chan);
04378    return res;
04379 }
04380 
04381 /*!
04382   \brief Transfer a call to dest, if the channel supports transfer
04383 
04384   Called by:
04385    \arg app_transfer
04386    \arg the manager interface
04387 */
04388 int ast_transfer(struct ast_channel *chan, char *dest)
04389 {
04390    int res = -1;
04391 
04392    /* Stop if we're a zombie or need a soft hangup */
04393    ast_channel_lock(chan);
04394    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
04395       if (chan->tech->transfer) {
04396          res = chan->tech->transfer(chan, dest);
04397          if (!res)
04398             res = 1;
04399       } else
04400          res = 0;
04401    }
04402    ast_channel_unlock(chan);
04403    return res;
04404 }
04405 
04406 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
04407 {
04408    return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
04409 }
04410 
04411 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
04412 {
04413    int pos = 0;   /* index in the buffer where we accumulate digits */
04414    int to = ftimeout;
04415 
04416    struct ast_silence_generator *silgen = NULL;
04417 
04418    /* Stop if we're a zombie or need a soft hangup */
04419    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
04420       return -1;
04421    if (!len)
04422       return -1;
04423    for (;;) {
04424       int d;
04425       if (c->stream) {
04426          d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
04427          ast_stopstream(c);
04428          if (!silgen && ast_opt_transmit_silence)
04429             silgen = ast_channel_start_silence_generator(c);
04430          usleep(1000);
04431          if (!d)
04432             d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
04433       } else {
04434          if (!silgen && ast_opt_transmit_silence)
04435             silgen = ast_channel_start_silence_generator(c);
04436          d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
04437       }
04438       if (d < 0) {
04439          ast_channel_stop_silence_generator(c, silgen);
04440          return AST_GETDATA_FAILED;
04441       }
04442       if (d == 0) {
04443          s[pos] = '\0';
04444          ast_channel_stop_silence_generator(c, silgen);
04445          return AST_GETDATA_TIMEOUT;
04446       }
04447       if (d == 1) {
04448          s[pos] = '\0';
04449          ast_channel_stop_silence_generator(c, silgen);
04450          return AST_GETDATA_INTERRUPTED;
04451       }
04452       if (strchr(enders, d) && (pos == 0)) {
04453          s[pos] = '\0';
04454          ast_channel_stop_silence_generator(c, silgen);
04455          return AST_GETDATA_EMPTY_END_TERMINATED;
04456       }
04457       if (!strchr(enders, d)) {
04458          s[pos++] = d;
04459       }
04460       if (strchr(enders, d) || (pos >= len)) {
04461          s[pos] = '\0';
04462          ast_channel_stop_silence_generator(c, silgen);
04463          return AST_GETDATA_COMPLETE;
04464       }
04465       to = timeout;
04466    }
04467    /* Never reached */
04468    return 0;
04469 }
04470 
04471 int ast_channel_supports_html(struct ast_channel *chan)
04472 {
04473    return (chan->tech->send_html) ? 1 : 0;
04474 }
04475 
04476 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04477 {
04478    if (chan->tech->send_html)
04479       return chan->tech->send_html(chan, subclass, data, datalen);
04480    return -1;
04481 }
04482 
04483 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
04484 {
04485    return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
04486 }
04487 
04488 /*! \brief Set up translation from one channel to another */
04489 static int ast_channel_make_compatible_helper(struct ast_channel *from, struct ast_channel *to)
04490 {
04491    int src;
04492    int dst;
04493    int use_slin;
04494 
04495    if (from->readformat == to->writeformat && from->writeformat == to->readformat) {
04496       /* Already compatible!  Moving on ... */
04497       return 0;
04498    }
04499 
04500    /* Set up translation from the 'from' channel to the 'to' channel */
04501    src = from->nativeformats;
04502    dst = to->nativeformats;
04503 
04504    /* If there's no audio in this call, don't bother with trying to find a translation path */
04505    if ((src & AST_FORMAT_AUDIO_MASK) == 0 || (dst & AST_FORMAT_AUDIO_MASK) == 0)
04506       return 0;
04507 
04508    if (ast_translator_best_choice(&dst, &src) < 0) {
04509       ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", from->name, src, to->name, dst);
04510       return -1;
04511    }
04512 
04513    /* if the best path is not 'pass through', then
04514     * transcoding is needed; if desired, force transcode path
04515     * to use SLINEAR between channels, but only if there is
04516     * no direct conversion available. If generic PLC is
04517     * desired, then transcoding via SLINEAR is a requirement
04518     */
04519    use_slin = (src == AST_FORMAT_SLINEAR || dst == AST_FORMAT_SLINEAR);
04520    if ((src != dst) && (ast_opt_generic_plc || ast_opt_transcode_via_slin) &&
04521        (ast_translate_path_steps(dst, src) != 1 || use_slin))
04522       dst = AST_FORMAT_SLINEAR;
04523    if (ast_set_read_format(from, dst) < 0) {
04524       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", from->name, dst);
04525       return -1;
04526    }
04527    if (ast_set_write_format(to, dst) < 0) {
04528       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", to->name, dst);
04529       return -1;
04530    }
04531    return 0;
04532 }
04533 
04534 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
04535 {
04536    /* Some callers do not check return code, and we must try to set all call legs correctly */
04537    int rc = 0;
04538 
04539    /* Set up translation from the chan to the peer */
04540    rc = ast_channel_make_compatible_helper(chan, peer);
04541 
04542    if (rc < 0)
04543       return rc;
04544 
04545    /* Set up translation from the peer to the chan */
04546    rc = ast_channel_make_compatible_helper(peer, chan);
04547 
04548    return rc;
04549 }
04550 
04551 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clonechan)
04552 {
04553    int res = -1;
04554    struct ast_channel *final_orig, *final_clone, *base;
04555 
04556 retrymasq:
04557    final_orig = original;
04558    final_clone = clonechan;
04559 
04560    ast_channel_lock(original);
04561    while (ast_channel_trylock(clonechan)) {
04562       ast_channel_unlock(original);
04563       usleep(1);
04564       ast_channel_lock(original);
04565    }
04566 
04567    /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
04568       and if so, we don't really want to masquerade it, but its proxy */
04569    if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
04570       final_orig = original->_bridge;
04571 
04572    if (clonechan->_bridge && (clonechan->_bridge != ast_bridged_channel(clonechan)) && (clonechan->_bridge->_bridge != clonechan))
04573       final_clone = clonechan->_bridge;
04574    
04575    if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
04576       final_clone = base;
04577    }
04578 
04579    if ((final_orig != original) || (final_clone != clonechan)) {
04580       /* Lots and lots of deadlock avoidance.  The main one we're competing with
04581        * is ast_write(), which locks channels recursively, when working with a
04582        * proxy channel. */
04583       if (ast_channel_trylock(final_orig)) {
04584          ast_channel_unlock(clonechan);
04585          ast_channel_unlock(original);
04586          goto retrymasq;
04587       }
04588       if (ast_channel_trylock(final_clone)) {
04589          ast_channel_unlock(final_orig);
04590          ast_channel_unlock(clonechan);
04591          ast_channel_unlock(original);
04592          goto retrymasq;
04593       }
04594       ast_channel_unlock(clonechan);
04595       ast_channel_unlock(original);
04596       original = final_orig;
04597       clonechan = final_clone;
04598    }
04599 
04600    if (original == clonechan) {
04601       ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
04602       ast_channel_unlock(clonechan);
04603       ast_channel_unlock(original);
04604       return -1;
04605    }
04606 
04607    ast_debug(1, "Planning to masquerade channel %s into the structure of %s\n",
04608       clonechan->name, original->name);
04609 
04610    if (!original->masqr && !original->masq && !clonechan->masq && !clonechan->masqr) {
04611       original->masq = clonechan;
04612       clonechan->masqr = original;
04613       ast_queue_frame(original, &ast_null_frame);
04614       ast_queue_frame(clonechan, &ast_null_frame);
04615       ast_debug(1, "Done planning to masquerade channel %s into the structure of %s\n", clonechan->name, original->name);
04616       res = 0;
04617    } else if (original->masq) {
04618       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04619          original->masq->name, original->name);
04620    } else if (original->masqr) {
04621       /* not yet as a previously planned masq hasn't yet happened */
04622       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04623          original->name, original->masqr->name);
04624    } else if (clonechan->masq) {
04625       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04626          clonechan->masq->name, clonechan->name);
04627    } else { /* (clonechan->masqr) */
04628       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
04629       clonechan->name, clonechan->masqr->name);
04630    }
04631 
04632    ast_channel_unlock(clonechan);
04633    ast_channel_unlock(original);
04634 
04635    return res;
04636 }
04637 
04638 void ast_change_name(struct ast_channel *chan, char *newname)
04639 {
04640    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
04641    ast_string_field_set(chan, name, newname);
04642 }
04643 
04644 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
04645 {
04646    struct ast_var_t *current, *newvar;
04647    const char *varname;
04648 
04649    AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
04650       int vartype = 0;
04651 
04652       varname = ast_var_full_name(current);
04653       if (!varname)
04654          continue;
04655 
04656       if (varname[0] == '_') {
04657          vartype = 1;
04658          if (varname[1] == '_')
04659             vartype = 2;
04660       }
04661 
04662       switch (vartype) {
04663       case 1:
04664          newvar = ast_var_assign(&varname[1], ast_var_value(current));
04665          if (newvar) {
04666             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
04667             ast_debug(1, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
04668          }
04669          break;
04670       case 2:
04671          newvar = ast_var_assign(varname, ast_var_value(current));
04672          if (newvar) {
04673             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
04674             ast_debug(1, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
04675          }
04676          break;
04677       default:
04678          ast_debug(1, "Not copying variable %s.\n", ast_var_name(current));
04679          break;
04680       }
04681    }
04682 }
04683 
04684 /*!
04685   \brief Clone channel variables from 'clone' channel into 'original' channel
04686 
04687   All variables except those related to app_groupcount are cloned.
04688   Variables are actually _removed_ from 'clone' channel, presumably
04689   because it will subsequently be destroyed.
04690 
04691   \note Assumes locks will be in place on both channels when called.
04692 */
04693 static void clone_variables(struct ast_channel *original, struct ast_channel *clonechan)
04694 {
04695    struct ast_var_t *current, *newvar;
04696    /* Append variables from clone channel into original channel */
04697    /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
04698    if (AST_LIST_FIRST(&clonechan->varshead))
04699       AST_LIST_APPEND_LIST(&original->varshead, &clonechan->varshead, entries);
04700 
04701    /* then, dup the varshead list into the clone */
04702    
04703    AST_LIST_TRAVERSE(&original->varshead, current, entries) {
04704       newvar = ast_var_assign(current->name, current->value);
04705       if (newvar)
04706          AST_LIST_INSERT_TAIL(&clonechan->varshead, newvar, entries);
04707    }
04708 }
04709 
04710 /*!
04711  * \pre chan is locked
04712  */
04713 static void report_new_callerid(const struct ast_channel *chan)
04714 {
04715    manager_event(EVENT_FLAG_CALL, "NewCallerid",
04716             "Channel: %s\r\n"
04717             "CallerIDNum: %s\r\n"
04718             "CallerIDName: %s\r\n"
04719             "Uniqueid: %s\r\n"
04720             "CID-CallingPres: %d (%s)\r\n",
04721             chan->name,
04722             S_OR(chan->cid.cid_num, ""),
04723             S_OR(chan->cid.cid_name, ""),
04724             chan->uniqueid,
04725             chan->cid.cid_pres,
04726             ast_describe_caller_presentation(chan->cid.cid_pres)
04727             );
04728 }
04729 
04730 /*!
04731   \brief Masquerade a channel
04732 
04733   \note Assumes channel will be locked when called
04734 */
04735 int ast_do_masquerade(struct ast_channel *original)
04736 {
04737    int x,i;
04738    int res=0;
04739    int origstate;
04740    struct ast_frame *current;
04741    const struct ast_channel_tech *t;
04742    void *t_pvt;
04743    struct ast_callerid tmpcid;
04744    struct ast_channel *clonechan = original->masq;
04745    struct ast_channel *bridged;
04746    struct ast_cdr *cdr;
04747    int rformat = original->readformat;
04748    int wformat = original->writeformat;
04749    char newn[AST_CHANNEL_NAME];
04750    char orig[AST_CHANNEL_NAME];
04751    char masqn[AST_CHANNEL_NAME];
04752    char zombn[AST_CHANNEL_NAME];
04753 
04754    ast_debug(4, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
04755       clonechan->name, clonechan->_state, original->name, original->_state);
04756 
04757    manager_event(EVENT_FLAG_CALL, "Masquerade", "Clone: %s\r\nCloneState: %s\r\nOriginal: %s\r\nOriginalState: %s\r\n",
04758             clonechan->name, ast_state2str(clonechan->_state), original->name, ast_state2str(original->_state));
04759 
04760    /* XXX This operation is a bit odd.  We're essentially putting the guts of
04761     * the clone channel into the original channel.  Start by killing off the
04762     * original channel's backend.  While the features are nice, which is the
04763     * reason we're keeping it, it's still awesomely weird. XXX */
04764 
04765    /* We need the clone's lock, too */
04766    ast_channel_lock(clonechan);
04767 
04768    ast_debug(2, "Got clone lock for masquerade on '%s' at %p\n", clonechan->name, &clonechan->lock_dont_use);
04769 
04770    /* Having remembered the original read/write formats, we turn off any translation on either
04771       one */
04772    free_translation(clonechan);
04773    free_translation(original);
04774 
04775 
04776    /* Unlink the masquerade */
04777    original->masq = NULL;
04778    clonechan->masqr = NULL;
04779    
04780    /* Save the original name */
04781    ast_copy_string(orig, original->name, sizeof(orig));
04782    /* Save the new name */
04783    ast_copy_string(newn, clonechan->name, sizeof(newn));
04784    /* Create the masq name */
04785    snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
04786       
04787    /* Copy the name from the clone channel */
04788    ast_string_field_set(original, name, newn);
04789 
04790    /* Mangle the name of the clone channel */
04791    ast_string_field_set(clonechan, name, masqn);
04792    
04793    /* Notify any managers of the change, first the masq then the other */
04794    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clonechan->uniqueid);
04795    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
04796 
04797    /* Swap the technologies */   
04798    t = original->tech;
04799    original->tech = clonechan->tech;
04800    clonechan->tech = t;
04801 
04802    /* Swap the cdrs */
04803    cdr = original->cdr;
04804    original->cdr = clonechan->cdr;
04805    clonechan->cdr = cdr;
04806 
04807    t_pvt = original->tech_pvt;
04808    original->tech_pvt = clonechan->tech_pvt;
04809    clonechan->tech_pvt = t_pvt;
04810 
04811    /* Swap the alertpipes */
04812    for (i = 0; i < 2; i++) {
04813       x = original->alertpipe[i];
04814       original->alertpipe[i] = clonechan->alertpipe[i];
04815       clonechan->alertpipe[i] = x;
04816    }
04817 
04818    /* 
04819     * Swap the readq's.  The end result should be this:
04820     *
04821     *  1) All frames should be on the new (original) channel.
04822     *  2) Any frames that were already on the new channel before this
04823     *     masquerade need to be at the end of the readq, after all of the
04824     *     frames on the old (clone) channel.
04825     *  3) The alertpipe needs to get poked for every frame that was already
04826     *     on the new channel, since we are now using the alert pipe from the
04827     *     old (clone) channel.
04828     */
04829    {
04830       AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
04831       AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
04832 
04833       AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
04834       AST_LIST_APPEND_LIST(&original->readq, &clonechan->readq, frame_list);
04835 
04836       while ((current = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
04837          AST_LIST_INSERT_TAIL(&original->readq, current, frame_list);
04838          if (original->alertpipe[1] > -1) {
04839             int poke = 0;
04840 
04841             if (write(original->alertpipe[1], &poke, sizeof(poke)) < 0) {
04842                ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
04843             }
04844          }
04845       }
04846    }
04847 
04848    /* Swap the raw formats */
04849    x = original->rawreadformat;
04850    original->rawreadformat = clonechan->rawreadformat;
04851    clonechan->rawreadformat = x;
04852    x = original->rawwriteformat;
04853    original->rawwriteformat = clonechan->rawwriteformat;
04854    clonechan->rawwriteformat = x;
04855 
04856    clonechan->_softhangup = AST_SOFTHANGUP_DEV;
04857 
04858    /* And of course, so does our current state.  Note we need not
04859       call ast_setstate since the event manager doesn't really consider
04860       these separate.  We do this early so that the clone has the proper
04861       state of the original channel. */
04862    origstate = original->_state;
04863    original->_state = clonechan->_state;
04864    clonechan->_state = origstate;
04865 
04866    if (clonechan->tech->fixup){
04867       res = clonechan->tech->fixup(original, clonechan);
04868       if (res)
04869          ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clonechan->name);
04870    }
04871 
04872    /* Start by disconnecting the original's physical side */
04873    if (clonechan->tech->hangup)
04874       res = clonechan->tech->hangup(clonechan);
04875    if (res) {
04876       ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
04877       ast_channel_unlock(clonechan);
04878       return -1;
04879    }
04880 
04881    snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
04882    /* Mangle the name of the clone channel */
04883    ast_string_field_set(clonechan, name, zombn);
04884    manager_event(EVENT_FLAG_CALL, "Rename", "Channel: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clonechan->uniqueid);
04885 
04886    /* Update the type. */
04887    t_pvt = original->monitor;
04888    original->monitor = clonechan->monitor;
04889    clonechan->monitor = t_pvt;
04890 
04891    /* Keep the same language.  */
04892    ast_string_field_set(original, language, clonechan->language);
04893    /* Copy the FD's other than the generator fd */
04894    for (x = 0; x < AST_MAX_FDS; x++) {
04895       if (x != AST_GENERATOR_FD)
04896          ast_channel_set_fd(original, x, clonechan->fds[x]);
04897    }
04898 
04899    ast_app_group_update(clonechan, original);
04900 
04901    /* Move data stores over */
04902    if (AST_LIST_FIRST(&clonechan->datastores)) {
04903       struct ast_datastore *ds;
04904       /* We use a safe traversal here because some fixup routines actually
04905        * remove the datastore from the list and free them.
04906        */
04907       AST_LIST_TRAVERSE_SAFE_BEGIN(&clonechan->datastores, ds, entry) {
04908          if (ds->info->chan_fixup)
04909             ds->info->chan_fixup(ds->data, clonechan, original);
04910       }
04911       AST_LIST_TRAVERSE_SAFE_END;
04912       AST_LIST_APPEND_LIST(&original->datastores, &clonechan->datastores, entry);
04913    }
04914 
04915    clone_variables(original, clonechan);
04916    /* Presense of ADSI capable CPE follows clone */
04917    original->adsicpe = clonechan->adsicpe;
04918    /* Bridge remains the same */
04919    /* CDR fields remain the same */
04920    /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
04921    /* Application and data remain the same */
04922    /* Clone exception  becomes real one, as with fdno */
04923    ast_set_flag(original, ast_test_flag(clonechan, AST_FLAG_OUTGOING | AST_FLAG_EXCEPTION));
04924    original->fdno = clonechan->fdno;
04925    /* Schedule context remains the same */
04926    /* Stream stuff stays the same */
04927    /* Keep the original state.  The fixup code will need to work with it most likely */
04928 
04929    /* Just swap the whole structures, nevermind the allocations, they'll work themselves
04930       out. */
04931    tmpcid = original->cid;
04932    original->cid = clonechan->cid;
04933    clonechan->cid = tmpcid;
04934    report_new_callerid(original);
04935 
04936    /* Restore original timing file descriptor */
04937    ast_channel_set_fd(original, AST_TIMING_FD, original->timingfd);
04938 
04939    /* Our native formats are different now */
04940    original->nativeformats = clonechan->nativeformats;
04941 
04942    /* Context, extension, priority, app data, jump table,  remain the same */
04943    /* pvt switches.  pbx stays the same, as does next */
04944 
04945    /* Set the write format */
04946    ast_set_write_format(original, wformat);
04947 
04948    /* Set the read format */
04949    ast_set_read_format(original, rformat);
04950 
04951    /* Copy the music class */
04952    ast_string_field_set(original, musicclass, clonechan->musicclass);
04953 
04954    ast_debug(1, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
04955 
04956    /* Okay.  Last thing is to let the channel driver know about all this mess, so he
04957       can fix up everything as best as possible */
04958    if (original->tech->fixup) {
04959       res = original->tech->fixup(clonechan, original);
04960       if (res) {
04961          ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
04962             original->tech->type, original->name);
04963          ast_channel_unlock(clonechan);
04964          return -1;
04965       }
04966    } else
04967       ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
04968          original->tech->type, original->name);
04969 
04970    /* 
04971     * If an indication is currently playing, maintain it on the channel 
04972     * that is taking the place of original 
04973     *
04974     * This is needed because the masquerade is swapping out in the internals
04975     * of this channel, and the new channel private data needs to be made
04976     * aware of the current visible indication (RINGING, CONGESTION, etc.)
04977     */
04978    if (original->visible_indication) {
04979       ast_indicate(original, original->visible_indication);
04980    }
04981    
04982    /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
04983       a zombie so nothing tries to touch it.  If it's already been marked as a
04984       zombie, then free it now (since it already is considered invalid). */
04985    if (ast_test_flag(clonechan, AST_FLAG_ZOMBIE)) {
04986       ast_debug(1, "Destroying channel clone '%s'\n", clonechan->name);
04987       ast_channel_unlock(clonechan);
04988       manager_event(EVENT_FLAG_CALL, "Hangup",
04989          "Channel: %s\r\n"
04990          "Uniqueid: %s\r\n"
04991          "Cause: %d\r\n"
04992          "Cause-txt: %s\r\n",
04993          clonechan->name,
04994          clonechan->uniqueid,
04995          clonechan->hangupcause,
04996          ast_cause2str(clonechan->hangupcause)
04997          );
04998       ast_channel_free(clonechan);
04999    } else {
05000       ast_debug(1, "Released clone lock on '%s'\n", clonechan->name);
05001       ast_set_flag(clonechan, AST_FLAG_ZOMBIE);
05002       ast_queue_frame(clonechan, &ast_null_frame);
05003       ast_channel_unlock(clonechan);
05004    }
05005 
05006    /* Signal any blocker */
05007    if (ast_test_flag(original, AST_FLAG_BLOCKING))
05008       pthread_kill(original->blocker, SIGURG);
05009    ast_debug(1, "Done Masquerading %s (%d)\n", original->name, original->_state);
05010 
05011    if ((bridged = ast_bridged_channel(original))) {
05012       ast_channel_lock(bridged);
05013       ast_indicate(bridged, AST_CONTROL_SRCCHANGE);
05014       ast_channel_unlock(bridged);
05015    }
05016 
05017    ast_indicate(original, AST_CONTROL_SRCCHANGE);
05018 
05019    return 0;
05020 }
05021 
05022 void ast_set_callerid(struct ast_channel *chan, const char *cid_num, const char *cid_name, const char *cid_ani)
05023 {
05024    ast_channel_lock(chan);
05025 
05026    if (cid_num) {
05027       if (chan->cid.cid_num)
05028          ast_free(chan->cid.cid_num);
05029       chan->cid.cid_num = ast_strdup(cid_num);
05030    }
05031    if (cid_name) {
05032       if (chan->cid.cid_name)
05033          ast_free(chan->cid.cid_name);
05034       chan->cid.cid_name = ast_strdup(cid_name);
05035    }
05036    if (cid_ani) {
05037       if (chan->cid.cid_ani)
05038          ast_free(chan->cid.cid_ani);
05039       chan->cid.cid_ani = ast_strdup(cid_ani);
05040    }
05041    if (chan->cdr) {
05042       ast_cdr_setcid(chan->cdr, chan);
05043    }
05044 
05045    report_new_callerid(chan);
05046 
05047    ast_channel_unlock(chan);
05048 }
05049 
05050 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
05051 {
05052    int oldstate = chan->_state;
05053    char name[AST_CHANNEL_NAME], *dashptr;
05054 
05055    if (oldstate == state)
05056       return 0;
05057 
05058    ast_copy_string(name, chan->name, sizeof(name));
05059    if ((dashptr = strrchr(name, '-'))) {
05060       *dashptr = '\0';
05061    }
05062 
05063    chan->_state = state;
05064 
05065    /* We have to pass AST_DEVICE_UNKNOWN here because it is entirely possible that the channel driver
05066     * for this channel is using the callback method for device state. If we pass in an actual state here
05067     * we override what they are saying the state is and things go amuck. */
05068    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, name);
05069 
05070    /* setstate used to conditionally report Newchannel; this is no more */
05071    manager_event(EVENT_FLAG_CALL,
05072             "Newstate",
05073             "Channel: %s\r\n"
05074             "ChannelState: %d\r\n"
05075             "ChannelStateDesc: %s\r\n"
05076             "CallerIDNum: %s\r\n"
05077             "CallerIDName: %s\r\n"
05078             "Uniqueid: %s\r\n",
05079             chan->name, chan->_state, ast_state2str(chan->_state),
05080             S_OR(chan->cid.cid_num, ""),
05081             S_OR(chan->cid.cid_name, ""),
05082             chan->uniqueid);
05083 
05084    return 0;
05085 }
05086 
05087 /*! \brief Find bridged channel */
05088 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
05089 {
05090    struct ast_channel *bridged;
05091    bridged = chan->_bridge;
05092    if (bridged && bridged->tech->bridged_channel)
05093       bridged = bridged->tech->bridged_channel(chan, bridged);
05094    return bridged;
05095 }
05096 
05097 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
05098 {
05099    int min = 0, sec = 0, check;
05100 
05101    check = ast_autoservice_start(peer);
05102    if (check)
05103       return;
05104 
05105    if (remain > 0) {
05106       if (remain / 60 > 1) {
05107          min = remain / 60;
05108          sec = remain % 60;
05109       } else {
05110          sec = remain;
05111       }
05112    }
05113    
05114    if (!strcmp(sound,"timeleft")) { /* Queue support */
05115       ast_stream_and_wait(chan, "vm-youhave", "");
05116       if (min) {
05117          ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
05118          ast_stream_and_wait(chan, "queue-minutes", "");
05119       }
05120       if (sec) {
05121          ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
05122          ast_stream_and_wait(chan, "queue-seconds", "");
05123       }
05124    } else {
05125       ast_stream_and_wait(chan, sound, "");
05126    }
05127 
05128    ast_autoservice_stop(peer);
05129 }
05130 
05131 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
05132                    struct ast_bridge_config *config, struct ast_frame **fo,
05133                    struct ast_channel **rc, struct timeval bridge_end)
05134 {
05135    /* Copy voice back and forth between the two channels. */
05136    struct ast_channel *cs[3];
05137    struct ast_frame *f;
05138    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
05139    int o0nativeformats;
05140    int o1nativeformats;
05141    int watch_c0_dtmf;
05142    int watch_c1_dtmf;
05143    void *pvt0, *pvt1;
05144    /* Indicates whether a frame was queued into a jitterbuffer */
05145    int frame_put_in_jb = 0;
05146    int jb_in_use;
05147    int to;
05148    
05149    cs[0] = c0;
05150    cs[1] = c1;
05151    pvt0 = c0->tech_pvt;
05152    pvt1 = c1->tech_pvt;
05153    o0nativeformats = c0->nativeformats;
05154    o1nativeformats = c1->nativeformats;
05155    watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
05156    watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
05157 
05158    /* Check the need of a jitterbuffer for each channel */
05159    jb_in_use = ast_jb_do_usecheck(c0, c1);
05160    if (jb_in_use)
05161       ast_jb_empty_and_reset(c0, c1);
05162 
05163    ast_poll_channel_add(c0, c1);
05164 
05165    if (config->feature_timer > 0 && ast_tvzero(config->nexteventts)) {
05166       /* calculate when the bridge should possibly break
05167        * if a partial feature match timed out */
05168       config->partialfeature_timer = ast_tvadd(ast_tvnow(), ast_samp2tv(config->feature_timer, 1000));
05169    } else {
05170       memset(&config->partialfeature_timer, 0, sizeof(config->partialfeature_timer));
05171    }
05172 
05173    for (;;) {
05174       struct ast_channel *who, *other;
05175 
05176       if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
05177           (o0nativeformats != c0->nativeformats) ||
05178           (o1nativeformats != c1->nativeformats)) {
05179          /* Check for Masquerade, codec changes, etc */
05180          res = AST_BRIDGE_RETRY;
05181          break;
05182       }
05183       if (bridge_end.tv_sec) {
05184          to = ast_tvdiff_ms(bridge_end, ast_tvnow());
05185          if (to <= 0) {
05186             if (config->timelimit) {
05187                res = AST_BRIDGE_RETRY;
05188                /* generic bridge ending to play warning */
05189                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
05190             } else {
05191                res = AST_BRIDGE_COMPLETE;
05192             }
05193             break;
05194          }
05195       } else {
05196          /* If a feature has been started and the bridge is configured to 
05197           * to not break, leave the channel bridge when the feature timer
05198           * time has elapsed so the DTMF will be sent to the other side. 
05199           */
05200          if (!ast_tvzero(config->partialfeature_timer)) {
05201             int diff = ast_tvdiff_ms(config->partialfeature_timer, ast_tvnow());
05202             if (diff <= 0) {
05203                res = AST_BRIDGE_RETRY;
05204                break;
05205             }
05206          }
05207          to = -1;
05208       }
05209       /* Calculate the appropriate max sleep interval - in general, this is the time,
05210          left to the closest jb delivery moment */
05211       if (jb_in_use)
05212          to = ast_jb_get_when_to_wakeup(c0, c1, to);
05213       who = ast_waitfor_n(cs, 2, &to);
05214       if (!who) {
05215          /* No frame received within the specified timeout - check if we have to deliver now */
05216          if (jb_in_use)
05217             ast_jb_get_and_deliver(c0, c1);
05218          if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
05219             if (c0->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
05220                ast_channel_clear_softhangup(c0, AST_SOFTHANGUP_UNBRIDGE);
05221             }
05222             if (c1->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
05223                ast_channel_clear_softhangup(c1, AST_SOFTHANGUP_UNBRIDGE);
05224             }
05225             c0->_bridge = c1;
05226             c1->_bridge = c0;
05227          }
05228          continue;
05229       }
05230       f = ast_read(who);
05231       if (!f) {
05232          *fo = NULL;
05233          *rc = who;
05234          ast_debug(1, "Didn't get a frame from channel: %s\n",who->name);
05235          break;
05236       }
05237 
05238       other = (who == c0) ? c1 : c0; /* the 'other' channel */
05239       /* Try add the frame info the who's bridged channel jitterbuff */
05240       if (jb_in_use)
05241          frame_put_in_jb = !ast_jb_put(other, f);
05242 
05243       if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
05244          int bridge_exit = 0;
05245 
05246          switch (f->subclass) {
05247          case AST_CONTROL_HOLD:
05248          case AST_CONTROL_UNHOLD:
05249          case AST_CONTROL_VIDUPDATE:
05250          case AST_CONTROL_SRCUPDATE:
05251          case AST_CONTROL_SRCCHANGE:
05252          case AST_CONTROL_T38_PARAMETERS:
05253             ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
05254             if (jb_in_use) {
05255                ast_jb_empty_and_reset(c0, c1);
05256             }
05257             break;
05258          default:
05259             *fo = f;
05260             *rc = who;
05261             bridge_exit = 1;
05262             ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
05263             break;
05264          }
05265          if (bridge_exit)
05266             break;
05267       }
05268       if ((f->frametype == AST_FRAME_VOICE) ||
05269           (f->frametype == AST_FRAME_DTMF_BEGIN) ||
05270           (f->frametype == AST_FRAME_DTMF) ||
05271           (f->frametype == AST_FRAME_VIDEO) ||
05272           (f->frametype == AST_FRAME_IMAGE) ||
05273           (f->frametype == AST_FRAME_HTML) ||
05274           (f->frametype == AST_FRAME_MODEM) ||
05275           (f->frametype == AST_FRAME_TEXT)) {
05276          /* monitored dtmf causes exit from bridge */
05277          int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
05278 
05279          if (monitored_source && 
05280             (f->frametype == AST_FRAME_DTMF_END || 
05281             f->frametype == AST_FRAME_DTMF_BEGIN)) {
05282             *fo = f;
05283             *rc = who;
05284             ast_debug(1, "Got DTMF %s on channel (%s)\n", 
05285                f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
05286                who->name);
05287 
05288             break;
05289          }
05290          /* Write immediately frames, not passed through jb */
05291          if (!frame_put_in_jb)
05292             ast_write(other, f);
05293             
05294          /* Check if we have to deliver now */
05295          if (jb_in_use)
05296             ast_jb_get_and_deliver(c0, c1);
05297       }
05298       /* XXX do we want to pass on also frames not matched above ? */
05299       ast_frfree(f);
05300 
05301 #ifndef HAVE_EPOLL
05302       /* Swap who gets priority */
05303       cs[2] = cs[0];
05304       cs[0] = cs[1];
05305       cs[1] = cs[2];
05306 #endif
05307    }
05308 
05309    ast_poll_channel_del(c0, c1);
05310 
05311    return res;
05312 }
05313 
05314 /*! \brief Bridge two channels together (early) */
05315 int ast_channel_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
05316 {
05317    /* Make sure we can early bridge, if not error out */
05318    if (!c0->tech->early_bridge || (c1 && (!c1->tech->early_bridge || c0->tech->early_bridge != c1->tech->early_bridge)))
05319       return -1;
05320 
05321    return c0->tech->early_bridge(c0, c1);
05322 }
05323 
05324 /*! \brief Send manager event for bridge link and unlink events.
05325  * \param onoff Link/Unlinked 
05326  * \param type 1 for core, 2 for native
05327  * \param c0 first channel in bridge
05328  * \param c1 second channel in bridge
05329 */
05330 static void manager_bridge_event(int onoff, int type, struct ast_channel *c0, struct ast_channel *c1)
05331 {
05332    manager_event(EVENT_FLAG_CALL, "Bridge",
05333          "Bridgestate: %s\r\n"
05334            "Bridgetype: %s\r\n"
05335             "Channel1: %s\r\n"
05336             "Channel2: %s\r\n"
05337             "Uniqueid1: %s\r\n"
05338             "Uniqueid2: %s\r\n"
05339             "CallerID1: %s\r\n"
05340             "CallerID2: %s\r\n",
05341          onoff ? "Link" : "Unlink",
05342          type == 1 ? "core" : "native",
05343          c0->name, c1->name, c0->uniqueid, c1->uniqueid, 
05344          S_OR(c0->cid.cid_num, ""), 
05345          S_OR(c1->cid.cid_num, ""));
05346 }
05347 
05348 static void update_bridge_vars(struct ast_channel *c0, struct ast_channel *c1)
05349 {
05350    const char *c0_name;
05351    const char *c1_name;
05352    const char *c0_pvtid = NULL;
05353    const char *c1_pvtid = NULL;
05354 
05355    ast_channel_lock(c1);
05356    c1_name = ast_strdupa(c1->name);
05357    if (c1->tech->get_pvt_uniqueid) {
05358       c1_pvtid = ast_strdupa(c1->tech->get_pvt_uniqueid(c1));
05359    }
05360    ast_channel_unlock(c1);
05361 
05362    ast_channel_lock(c0);
05363    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER"))) {
05364       pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1_name);
05365    }
05366    if (c1_pvtid) {
05367       pbx_builtin_setvar_helper(c0, "BRIDGEPVTCALLID", c1_pvtid);
05368    }
05369    c0_name = ast_strdupa(c0->name);
05370    if (c0->tech->get_pvt_uniqueid) {
05371       c0_pvtid = ast_strdupa(c0->tech->get_pvt_uniqueid(c0));
05372    }
05373    ast_channel_unlock(c0);
05374 
05375    ast_channel_lock(c1);
05376    if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER"))) {
05377       pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0_name);
05378    }
05379    if (c0_pvtid) {
05380       pbx_builtin_setvar_helper(c1, "BRIDGEPVTCALLID", c0_pvtid);
05381    }
05382    ast_channel_unlock(c1);
05383 }
05384 
05385 static void bridge_play_sounds(struct ast_channel *c0, struct ast_channel *c1)
05386 {
05387    const char *s, *sound;
05388 
05389    /* See if we need to play an audio file to any side of the bridge */
05390 
05391    ast_channel_lock(c0);
05392    if ((s = pbx_builtin_getvar_helper(c0, "BRIDGE_PLAY_SOUND"))) {
05393       sound = ast_strdupa(s);
05394       ast_channel_unlock(c0);
05395       bridge_playfile(c0, c1, sound, 0);
05396       pbx_builtin_setvar_helper(c0, "BRIDGE_PLAY_SOUND", NULL);
05397    } else {
05398       ast_channel_unlock(c0);
05399    }
05400 
05401    ast_channel_lock(c1);
05402    if ((s = pbx_builtin_getvar_helper(c1, "BRIDGE_PLAY_SOUND"))) {
05403       sound = ast_strdupa(s);
05404       ast_channel_unlock(c1);
05405       bridge_playfile(c1, c0, sound, 0);
05406       pbx_builtin_setvar_helper(c1, "BRIDGE_PLAY_SOUND", NULL);
05407    } else {
05408       ast_channel_unlock(c1);
05409    }
05410 }
05411 
05412 /*! \brief Bridge two channels together */
05413 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
05414                  struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
05415 {
05416    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
05417    int nativefailed=0;
05418    int firstpass;
05419    int o0nativeformats;
05420    int o1nativeformats;
05421    long time_left_ms=0;
05422    char caller_warning = 0;
05423    char callee_warning = 0;
05424 
05425    if (c0->_bridge) {
05426       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
05427          c0->name, c0->_bridge->name);
05428       return -1;
05429    }
05430    if (c1->_bridge) {
05431       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
05432          c1->name, c1->_bridge->name);
05433       return -1;
05434    }
05435    
05436    /* Stop if we're a zombie or need a soft hangup */
05437    if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
05438        ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
05439       return -1;
05440 
05441    *fo = NULL;
05442    firstpass = config->firstpass;
05443    config->firstpass = 0;
05444 
05445    if (ast_tvzero(config->start_time))
05446       config->start_time = ast_tvnow();
05447    time_left_ms = config->timelimit;
05448 
05449    caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
05450    callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
05451 
05452    if (config->start_sound && firstpass) {
05453       if (caller_warning)
05454          bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
05455       if (callee_warning)
05456          bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
05457    }
05458 
05459    /* Keep track of bridge */
05460    c0->_bridge = c1;
05461    c1->_bridge = c0;
05462 
05463 
05464    o0nativeformats = c0->nativeformats;
05465    o1nativeformats = c1->nativeformats;
05466 
05467    if (config->feature_timer && !ast_tvzero(config->nexteventts)) {
05468       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
05469    } else if (config->timelimit && firstpass) {
05470       config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
05471       if (caller_warning || callee_warning)
05472          config->nexteventts = ast_tvsub(config->nexteventts, ast_samp2tv(config->play_warning, 1000));
05473    }
05474 
05475    if (!c0->tech->send_digit_begin)
05476       ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
05477    if (!c1->tech->send_digit_begin)
05478       ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
05479    manager_bridge_event(1, 1, c0, c1);
05480 
05481    /* Before we enter in and bridge these two together tell them both the source of audio has changed */
05482    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
05483    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
05484 
05485    for (/* ever */;;) {
05486       struct timeval now = { 0, };
05487       int to;
05488 
05489       to = -1;
05490 
05491       if (!ast_tvzero(config->nexteventts)) {
05492          now = ast_tvnow();
05493          to = ast_tvdiff_ms(config->nexteventts, now);
05494          if (to <= 0) {
05495             if (!config->timelimit) {
05496                res = AST_BRIDGE_COMPLETE;
05497                break;
05498             }
05499             to = 0;
05500          }
05501       }
05502 
05503       if (config->timelimit) {
05504          time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
05505          if (time_left_ms < to)
05506             to = time_left_ms;
05507 
05508          if (time_left_ms <= 0) {
05509             if (caller_warning && config->end_sound)
05510                bridge_playfile(c0, c1, config->end_sound, 0);
05511             if (callee_warning && config->end_sound)
05512                bridge_playfile(c1, c0, config->end_sound, 0);
05513             *fo = NULL;
05514             res = 0;
05515             break;
05516          }
05517 
05518          if (!to) {
05519             if (time_left_ms >= 5000 && config->warning_sound && config->play_warning && ast_test_flag(config, AST_FEATURE_WARNING_ACTIVE)) {
05520                int t = (time_left_ms + 500) / 1000; /* round to nearest second */
05521                if (caller_warning)
05522                   bridge_playfile(c0, c1, config->warning_sound, t);
05523                if (callee_warning)
05524                   bridge_playfile(c1, c0, config->warning_sound, t);
05525             }
05526             if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
05527                config->nexteventts = ast_tvadd(config->nexteventts, ast_samp2tv(config->warning_freq, 1000));
05528             else
05529                config->nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
05530          }
05531          ast_clear_flag(config, AST_FEATURE_WARNING_ACTIVE);
05532       }
05533 
05534       if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
05535          if (c0->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
05536             ast_channel_clear_softhangup(c0, AST_SOFTHANGUP_UNBRIDGE);
05537          }
05538          if (c1->_softhangup & AST_SOFTHANGUP_UNBRIDGE) {
05539             ast_channel_clear_softhangup(c1, AST_SOFTHANGUP_UNBRIDGE);
05540          }
05541          c0->_bridge = c1;
05542          c1->_bridge = c0;
05543          ast_debug(1, "Unbridge signal received. Ending native bridge.\n");
05544          continue;
05545       }
05546 
05547       /* Stop if we're a zombie or need a soft hangup */
05548       if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
05549           ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
05550          *fo = NULL;
05551          res = 0;
05552          ast_debug(1, "Bridge stops because we're zombie or need a soft hangup: c0=%s, c1=%s, flags: %s,%s,%s,%s\n",
05553             c0->name, c1->name,
05554             ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
05555             ast_check_hangup(c0) ? "Yes" : "No",
05556             ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
05557             ast_check_hangup(c1) ? "Yes" : "No");
05558          break;
05559       }
05560 
05561       update_bridge_vars(c0, c1);
05562 
05563       bridge_play_sounds(c0, c1);
05564 
05565       if (c0->tech->bridge &&
05566          /* if < 1 ms remains use generic bridging for accurate timing */
05567          (!config->timelimit || to > 1000 || to == 0) &&
05568           (c0->tech->bridge == c1->tech->bridge) &&
05569           !nativefailed && !c0->monitor && !c1->monitor &&
05570           !c0->audiohooks && !c1->audiohooks &&
05571           !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
05572          int timeoutms = to - 1000 > 0 ? to - 1000 : to;
05573          /* Looks like they share a bridge method and nothing else is in the way */
05574          ast_set_flag(c0, AST_FLAG_NBRIDGE);
05575          ast_set_flag(c1, AST_FLAG_NBRIDGE);
05576          if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, timeoutms)) == AST_BRIDGE_COMPLETE) {
05577             /* \todo  XXX here should check that cid_num is not NULL */
05578             manager_event(EVENT_FLAG_CALL, "Unlink",
05579                      "Channel1: %s\r\n"
05580                      "Channel2: %s\r\n"
05581                      "Uniqueid1: %s\r\n"
05582                      "Uniqueid2: %s\r\n"
05583                      "CallerID1: %s\r\n"
05584                      "CallerID2: %s\r\n",
05585                      c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
05586             ast_debug(1, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
05587 
05588             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
05589             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
05590 
05591             if ((c0->_softhangup | c1->_softhangup) & AST_SOFTHANGUP_UNBRIDGE) {/* Bit operators are intentional. */
05592                continue;
05593             }
05594 
05595             c0->_bridge = NULL;
05596             c1->_bridge = NULL;
05597 
05598             return res;
05599          } else {
05600             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
05601             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
05602          }
05603          switch (res) {
05604          case AST_BRIDGE_RETRY:
05605             if (config->play_warning) {
05606                ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
05607             }
05608             continue;
05609          default:
05610             ast_verb(3, "Native bridging %s and %s ended\n", c0->name, c1->name);
05611             /* fallthrough */
05612          case AST_BRIDGE_FAILED_NOWARN:
05613             nativefailed++;
05614             break;
05615          }
05616       }
05617 
05618       if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
05619           (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
05620           !(c0->generator || c1->generator)) {
05621          if (ast_channel_make_compatible(c0, c1)) {
05622             ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
05623             manager_bridge_event(0, 1, c0, c1);
05624             return AST_BRIDGE_FAILED;
05625          }
05626          o0nativeformats = c0->nativeformats;
05627          o1nativeformats = c1->nativeformats;
05628       }
05629 
05630       update_bridge_vars(c0, c1);
05631 
05632       res = ast_generic_bridge(c0, c1, config, fo, rc, config->nexteventts);
05633       if (res != AST_BRIDGE_RETRY) {
05634          break;
05635       } else if (config->feature_timer) {
05636          /* feature timer expired but has not been updated, sending to ast_bridge_call to do so */
05637          break;
05638       }
05639    }
05640 
05641    ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
05642    ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
05643 
05644    /* Now that we have broken the bridge the source will change yet again */
05645    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
05646    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
05647 
05648    c0->_bridge = NULL;
05649    c1->_bridge = NULL;
05650 
05651    /* \todo  XXX here should check that cid_num is not NULL */
05652    manager_event(EVENT_FLAG_CALL, "Unlink",
05653             "Channel1: %s\r\n"
05654             "Channel2: %s\r\n"
05655             "Uniqueid1: %s\r\n"
05656             "Uniqueid2: %s\r\n"
05657             "CallerID1: %s\r\n"
05658             "CallerID2: %s\r\n",
05659             c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
05660    ast_debug(1, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
05661 
05662    return res;
05663 }
05664 
05665 /*! \brief Sets an option on a channel */
05666 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
05667 {
05668    if (!chan->tech->setoption) {
05669       errno = ENOSYS;
05670       return -1;
05671    }
05672 
05673    if (block)
05674       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
05675 
05676    return chan->tech->setoption(chan, option, data, datalen);
05677 }
05678 
05679 int ast_channel_queryoption(struct ast_channel *chan, int option, void *data, int *datalen, int block)
05680 {
05681    if (!chan->tech->queryoption) {
05682       errno = ENOSYS;
05683       return -1;
05684    }
05685 
05686    if (block)
05687       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
05688 
05689    return chan->tech->queryoption(chan, option, data, datalen);
05690 }
05691 
05692 struct tonepair_def {
05693    int freq1;
05694    int freq2;
05695    int duration;
05696    int vol;
05697 };
05698 
05699 struct tonepair_state {
05700    int fac1;
05701    int fac2;
05702    int v1_1;
05703    int v2_1;
05704    int v3_1;
05705    int v1_2;
05706    int v2_2;
05707    int v3_2;
05708    int origwfmt;
05709    int pos;
05710    int duration;
05711    int modulate;
05712    struct ast_frame f;
05713    unsigned char offset[AST_FRIENDLY_OFFSET];
05714    short data[4000];
05715 };
05716 
05717 static void tonepair_release(struct ast_channel *chan, void *params)
05718 {
05719    struct tonepair_state *ts = params;
05720 
05721    if (chan)
05722       ast_set_write_format(chan, ts->origwfmt);
05723    ast_free(ts);
05724 }
05725 
05726 static void *tonepair_alloc(struct ast_channel *chan, void *params)
05727 {
05728    struct tonepair_state *ts;
05729    struct tonepair_def *td = params;
05730 
05731    if (!(ts = ast_calloc(1, sizeof(*ts))))
05732       return NULL;
05733    ts->origwfmt = chan->writeformat;
05734    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
05735       ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
05736       tonepair_release(NULL, ts);
05737       ts = NULL;
05738    } else {
05739       ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
05740       ts->v1_1 = 0;
05741       ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
05742       ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
05743       ts->v2_1 = 0;
05744       ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
05745       ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
05746       ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
05747       ts->duration = td->duration;
05748       ts->modulate = 0;
05749    }
05750    /* Let interrupts interrupt :) */
05751    ast_set_flag(chan, AST_FLAG_WRITE_INT);
05752    return ts;
05753 }
05754 
05755 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
05756 {
05757    struct tonepair_state *ts = data;
05758    int x;
05759 
05760    /* we need to prepare a frame with 16 * timelen samples as we're
05761     * generating SLIN audio
05762     */
05763    len = samples * 2;
05764 
05765    if (len > sizeof(ts->data) / 2 - 1) {
05766       ast_log(LOG_WARNING, "Can't generate that much data!\n");
05767       return -1;
05768    }
05769    memset(&ts->f, 0, sizeof(ts->f));
05770    for (x=0;x<len/2;x++) {
05771       ts->v1_1 = ts->v2_1;
05772       ts->v2_1 = ts->v3_1;
05773       ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
05774       
05775       ts->v1_2 = ts->v2_2;
05776       ts->v2_2 = ts->v3_2;
05777       ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
05778       if (ts->modulate) {
05779          int p;
05780          p = ts->v3_2 - 32768;
05781          if (p < 0) p = -p;
05782          p = ((p * 9) / 10) + 1;
05783          ts->data[x] = (ts->v3_1 * p) >> 15;
05784       } else
05785          ts->data[x] = ts->v3_1 + ts->v3_2; 
05786    }
05787    ts->f.frametype = AST_FRAME_VOICE;
05788    ts->f.subclass = AST_FORMAT_SLINEAR;
05789    ts->f.datalen = len;
05790    ts->f.samples = samples;
05791    ts->f.offset = AST_FRIENDLY_OFFSET;
05792    ts->f.data.ptr = ts->data;
05793    ast_write(chan, &ts->f);
05794    ts->pos += x;
05795    if (ts->duration > 0) {
05796       if (ts->pos >= ts->duration * 8)
05797          return -1;
05798    }
05799    return 0;
05800 }
05801 
05802 static struct ast_generator tonepair = {
05803    alloc: tonepair_alloc,
05804    release: tonepair_release,
05805    generate: tonepair_generator,
05806 };
05807 
05808 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
05809 {
05810    struct tonepair_def d = { 0, };
05811 
05812    d.freq1 = freq1;
05813    d.freq2 = freq2;
05814    d.duration = duration;
05815    d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
05816    if (ast_activate_generator(chan, &tonepair, &d))
05817       return -1;
05818    return 0;
05819 }
05820 
05821 void ast_tonepair_stop(struct ast_channel *chan)
05822 {
05823    ast_deactivate_generator(chan);
05824 }
05825 
05826 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
05827 {
05828    int res;
05829 
05830    if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
05831       return res;
05832 
05833    /* Give us some wiggle room */
05834    while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
05835       struct ast_frame *f = ast_read(chan);
05836       if (f)
05837          ast_frfree(f);
05838       else
05839          return -1;
05840    }
05841    return 0;
05842 }
05843 
05844 ast_group_t ast_get_group(const char *s)
05845 {
05846    char *piece;
05847    char *c;
05848    int start=0, finish=0, x;
05849    ast_group_t group = 0;
05850 
05851    if (ast_strlen_zero(s))
05852       return 0;
05853 
05854    c = ast_strdupa(s);
05855    
05856    while ((piece = strsep(&c, ","))) {
05857       if (sscanf(piece, "%30d-%30d", &start, &finish) == 2) {
05858          /* Range */
05859       } else if (sscanf(piece, "%30d", &start)) {
05860          /* Just one */
05861          finish = start;
05862       } else {
05863          ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
05864          continue;
05865       }
05866       for (x = start; x <= finish; x++) {
05867          if ((x > 63) || (x < 0)) {
05868             ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
05869          } else
05870             group |= ((ast_group_t) 1 << x);
05871       }
05872    }
05873    return group;
05874 }
05875 
05876 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
05877 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
05878 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
05879 
05880 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
05881              void (*stop_ptr)(struct ast_channel *),
05882              void (*cleanup_ptr)(struct ast_channel *))
05883 {
05884    ast_moh_start_ptr = start_ptr;
05885    ast_moh_stop_ptr = stop_ptr;
05886    ast_moh_cleanup_ptr = cleanup_ptr;
05887 }
05888 
05889 void ast_uninstall_music_functions(void)
05890 {
05891    ast_moh_start_ptr = NULL;
05892    ast_moh_stop_ptr = NULL;
05893    ast_moh_cleanup_ptr = NULL;
05894 }
05895 
05896 /*! \brief Turn on music on hold on a given channel */
05897 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
05898 {
05899    if (ast_moh_start_ptr)
05900       return ast_moh_start_ptr(chan, mclass, interpclass);
05901 
05902    ast_verb(3, "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : (interpclass ? interpclass : "default"));
05903 
05904    return 0;
05905 }
05906 
05907 /*! \brief Turn off music on hold on a given channel */
05908 void ast_moh_stop(struct ast_channel *chan)
05909 {
05910    if (ast_moh_stop_ptr)
05911       ast_moh_stop_ptr(chan);
05912 }
05913 
05914 void ast_moh_cleanup(struct ast_channel *chan)
05915 {
05916    if (ast_moh_cleanup_ptr)
05917       ast_moh_cleanup_ptr(chan);
05918 }
05919 
05920 int ast_plc_reload(void)
05921 {
05922    struct ast_variable *var;
05923    struct ast_flags config_flags = { 0 };
05924    struct ast_config *cfg = ast_config_load2("codecs.conf", "channel", config_flags);
05925    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID)
05926       return 0;
05927    for (var = ast_variable_browse(cfg, "plc"); var; var = var->next) {
05928       if (!strcasecmp(var->name, "genericplc")) {
05929          ast_set2_flag(&ast_options, ast_true(var->value), AST_OPT_FLAG_GENERIC_PLC);
05930       }
05931    }
05932    ast_config_destroy(cfg);
05933    return 0;
05934 }
05935 
05936 void ast_channels_init(void)
05937 {
05938    ast_cli_register_multiple(cli_channel, ARRAY_LEN(cli_channel));
05939 
05940    ast_plc_reload();
05941 }
05942 
05943 /*! \brief Print call group and pickup group ---*/
05944 char *ast_print_group(char *buf, int buflen, ast_group_t group)
05945 {
05946    unsigned int i;
05947    int first = 1;
05948    char num[3];
05949 
05950    buf[0] = '\0';
05951    
05952    if (!group) /* Return empty string if no group */
05953       return buf;
05954 
05955    for (i = 0; i <= 63; i++) {   /* Max group is 63 */
05956       if (group & ((ast_group_t) 1 << i)) {
05957             if (!first) {
05958             strncat(buf, ", ", buflen - strlen(buf) - 1);
05959          } else {
05960             first = 0;
05961          }
05962          snprintf(num, sizeof(num), "%u", i);
05963          strncat(buf, num, buflen - strlen(buf) - 1);
05964       }
05965    }
05966    return buf;
05967 }
05968 
05969 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
05970 {
05971    struct ast_variable *cur;
05972 
05973    for (cur = vars; cur; cur = cur->next)
05974       pbx_builtin_setvar_helper(chan, cur->name, cur->value);  
05975 }
05976 
05977 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
05978 {
05979    /* just store the data pointer in the channel structure */
05980    return data;
05981 }
05982 
05983 static void silence_generator_release(struct ast_channel *chan, void *data)
05984 {
05985    /* nothing to do */
05986 }
05987 
05988 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
05989 {
05990    short buf[samples];
05991    struct ast_frame frame = {
05992       .frametype = AST_FRAME_VOICE,
05993       .subclass = AST_FORMAT_SLINEAR,
05994       .data.ptr = buf,
05995       .samples = samples,
05996       .datalen = sizeof(buf),
05997    };
05998 
05999    memset(buf, 0, sizeof(buf));
06000 
06001    if (ast_write(chan, &frame))
06002       return -1;
06003 
06004    return 0;
06005 }
06006 
06007 static struct ast_generator silence_generator = {
06008    .alloc = silence_generator_alloc,
06009    .release = silence_generator_release,
06010    .generate = silence_generator_generate,
06011 };
06012 
06013 struct ast_silence_generator {
06014    int old_write_format;
06015 };
06016 
06017 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
06018 {
06019    struct ast_silence_generator *state;
06020 
06021    if (!(state = ast_calloc(1, sizeof(*state)))) {
06022       return NULL;
06023    }
06024 
06025    state->old_write_format = chan->writeformat;
06026 
06027    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
06028       ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
06029       ast_free(state);
06030       return NULL;
06031    }
06032 
06033    ast_activate_generator(chan, &silence_generator, state);
06034 
06035    ast_debug(1, "Started silence generator on '%s'\n", chan->name);
06036 
06037    return state;
06038 }
06039 
06040 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
06041 {
06042    if (!state)
06043       return;
06044 
06045    ast_deactivate_generator(chan);
06046 
06047    ast_debug(1, "Stopped silence generator on '%s'\n", chan->name);
06048 
06049    if (ast_set_write_format(chan, state->old_write_format) < 0)
06050       ast_log(LOG_ERROR, "Could not return write format to its original state\n");
06051 
06052    ast_free(state);
06053 }
06054 
06055 
06056 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
06057 const char *channelreloadreason2txt(enum channelreloadreason reason)
06058 {
06059    switch (reason) {
06060    case CHANNEL_MODULE_LOAD:
06061       return "LOAD (Channel module load)";
06062 
06063    case CHANNEL_MODULE_RELOAD:
06064       return "RELOAD (Channel module reload)";
06065 
06066    case CHANNEL_CLI_RELOAD:
06067       return "CLIRELOAD (Channel module reload by CLI command)";
06068 
06069    default:
06070       return "MANAGERRELOAD (Channel module reload by manager)";
06071    }
06072 };
06073 
06074 #ifdef DEBUG_CHANNEL_LOCKS
06075 
06076 /*! \brief Unlock AST channel (and print debugging output) 
06077 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
06078 */
06079 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
06080 {
06081    int res = 0;
06082    ast_debug(3, "::::==== Unlocking AST channel %s\n", chan->name);
06083    
06084    if (!chan) {
06085       ast_debug(1, "::::==== Unlocking non-existing channel \n");
06086       return 0;
06087    }
06088 #ifdef DEBUG_THREADS
06089    res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
06090 #else
06091    res = ast_mutex_unlock(&chan->lock_dont_use);
06092 #endif
06093 
06094    if (option_debug > 2) {
06095 #ifdef DEBUG_THREADS
06096       int count = 0;
06097       if ((count = chan->lock_dont_use.track.reentrancy))
06098          ast_debug(3, ":::=== Still have %d locks (recursive)\n", count);
06099 #endif
06100       if (!res)
06101          ast_debug(3, "::::==== Channel %s was unlocked\n", chan->name);
06102       if (res == EINVAL) {
06103          ast_debug(3, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
06104       }
06105    }
06106    if (res == EPERM) {
06107       /* We had no lock, so okay any way*/
06108       ast_debug(4, "::::==== Channel %s was not locked at all \n", chan->name);
06109       res = 0;
06110    }
06111    return res;
06112 }
06113 
06114 /*! \brief Lock AST channel (and print debugging output)
06115 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
06116 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
06117 {
06118    int res;
06119 
06120    ast_debug(4, "====:::: Locking AST channel %s\n", chan->name);
06121 
06122 #ifdef DEBUG_THREADS
06123    res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
06124 #else
06125    res = ast_mutex_lock(&chan->lock_dont_use);
06126 #endif
06127 
06128    if (option_debug > 3) {
06129 #ifdef DEBUG_THREADS
06130       int count = 0;
06131       if ((count = chan->lock_dont_use.track.reentrancy))
06132          ast_debug(4, ":::=== Now have %d locks (recursive)\n", count);
06133 #endif
06134       if (!res)
06135          ast_debug(4, "::::==== Channel %s was locked\n", chan->name);
06136       if (res == EDEADLK) {
06137          /* We had no lock, so okey any way */
06138          ast_debug(4, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
06139       }
06140       if (res == EINVAL) {
06141          ast_debug(4, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
06142       }
06143    }
06144    return res;
06145 }
06146 
06147 /*! \brief Lock AST channel (and print debugging output)
06148 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
06149 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
06150 {
06151    int res;
06152 
06153    ast_debug(3, "====:::: Trying to lock AST channel %s\n", chan->name);
06154 #ifdef DEBUG_THREADS
06155    res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock_dont_use);
06156 #else
06157    res = ast_mutex_trylock(&chan->lock_dont_use);
06158 #endif
06159 
06160    if (option_debug > 2) {
06161 #ifdef DEBUG_THREADS
06162       int count = 0;
06163       if ((count = chan->lock_dont_use.track.reentrancy))
06164          ast_debug(3, ":::=== Now have %d locks (recursive)\n", count);
06165 #endif
06166       if (!res)
06167          ast_debug(3, "::::==== Channel %s was locked\n", chan->name);
06168       if (res == EBUSY) {
06169          /* We failed to lock */
06170          ast_debug(3, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
06171       }
06172       if (res == EDEADLK) {
06173          /* We had no lock, so okey any way*/
06174          ast_debug(3, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
06175       }
06176       if (res == EINVAL)
06177          ast_debug(3, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
06178    }
06179    return res;
06180 }
06181 
06182 #endif
06183 
06184 /*
06185  * Wrappers for various ast_say_*() functions that call the full version
06186  * of the same functions.
06187  * The proper place would be say.c, but that file is optional and one
06188  * must be able to build asterisk even without it (using a loadable 'say'
06189  * implementation that only supplies the 'full' version of the functions.
06190  */
06191 
06192 int ast_say_number(struct ast_channel *chan, int num,
06193    const char *ints, const char *language, const char *options)
06194 {
06195    return ast_say_number_full(chan, num, ints, language, options, -1, -1);
06196 }
06197 
06198 int ast_say_enumeration(struct ast_channel *chan, int num,
06199    const char *ints, const char *language, const char *options)
06200 {
06201    return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
06202 }
06203 
06204 int ast_say_digits(struct ast_channel *chan, int num,
06205    const char *ints, const char *lang)
06206 {
06207    return ast_say_digits_full(chan, num, ints, lang, -1, -1);
06208 }
06209 
06210 int ast_say_digit_str(struct ast_channel *chan, const char *str,
06211    const char *ints, const char *lang)
06212 {
06213    return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
06214 }
06215 
06216 int ast_say_character_str(struct ast_channel *chan, const char *str,
06217    const char *ints, const char *lang)
06218 {
06219    return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
06220 }
06221 
06222 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
06223    const char *ints, const char *lang)
06224 {
06225    return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
06226 }
06227 
06228 int ast_say_digits_full(struct ast_channel *chan, int num,
06229    const char *ints, const char *lang, int audiofd, int ctrlfd)
06230 {
06231    char buf[256];
06232 
06233    snprintf(buf, sizeof(buf), "%d", num);
06234 
06235    return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
06236 }
06237 
06238 /* DO NOT PUT ADDITIONAL FUNCTIONS BELOW THIS BOUNDARY
06239  *
06240  * ONLY FUNCTIONS FOR PROVIDING BACKWARDS ABI COMPATIBILITY BELONG HERE
06241  *
06242  */
06243 
06244 /* Provide binary compatibility for modules that call ast_channel_alloc() directly;
06245  * newly compiled modules will call __ast_channel_alloc() via the macros in channel.h
06246  */
06247 #undef ast_channel_alloc
06248 struct ast_channel __attribute__((format(printf, 9, 10)))
06249    *ast_channel_alloc(int needqueue, int state, const char *cid_num,
06250             const char *cid_name, const char *acctcode,
06251             const char *exten, const char *context,
06252             const int amaflag, const char *name_fmt, ...);
06253 struct ast_channel *ast_channel_alloc(int needqueue, int state, const char *cid_num,
06254                   const char *cid_name, const char *acctcode,
06255                   const char *exten, const char *context,
06256                   const int amaflag, const char *name_fmt, ...)
06257 {
06258    va_list ap1, ap2;
06259    struct ast_channel *result;
06260 
06261 
06262    va_start(ap1, name_fmt);
06263    va_start(ap2, name_fmt);
06264    result = __ast_channel_alloc_ap(needqueue, state, cid_num, cid_name, acctcode, exten, context,
06265                amaflag, __FILE__, __LINE__, __FUNCTION__, name_fmt, ap1, ap2);
06266    va_end(ap1);
06267    va_end(ap2);
06268 
06269    return result;
06270 }