Fri Jan 29 14:25:14 2010

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

Generated on Fri Jan 29 14:25:14 2010 for Asterisk - the Open Source PBX by  doxygen 1.4.7