Tue Nov 4 13:20:18 2008

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: 116463 $")
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 #ifdef HAVE_ZAPTEL
00041 #include <sys/ioctl.h>
00042 #include <zaptel/zaptel.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_ZAPTEL
00745    tmp->timingfd = open("/dev/zap/timer", O_RDWR);
00746    if (tmp->timingfd > -1) {
00747       /* Check if timing interface supports new
00748          ping/pong scheme */
00749       flags = 1;
00750       if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
00751          needqueue = 0;
00752    }
00753 #else
00754    tmp->timingfd = -1;              
00755 #endif               
00756 
00757    if (needqueue) {
00758       if (pipe(tmp->alertpipe)) {
00759          ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
00760 #ifdef HAVE_ZAPTEL
00761          if (tmp->timingfd > -1)
00762             close(tmp->timingfd);
00763 #endif
00764          sched_context_destroy(tmp->sched);
00765          ast_string_field_free_memory(tmp);
00766          free(tmp);
00767          return NULL;
00768       } else {
00769          flags = fcntl(tmp->alertpipe[0], F_GETFL);
00770          fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
00771          flags = fcntl(tmp->alertpipe[1], F_GETFL);
00772          fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
00773       }
00774    } else   /* Make sure we've got it done right if they don't */
00775       tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
00776 
00777    /* Always watch the alertpipe */
00778    tmp->fds[AST_ALERT_FD] = tmp->alertpipe[0];
00779    /* And timing pipe */
00780    tmp->fds[AST_TIMING_FD] = tmp->timingfd;
00781    ast_string_field_set(tmp, name, "**Unknown**");
00782 
00783    /* Initial state */
00784    tmp->_state = state;
00785 
00786    tmp->streamid = -1;
00787    
00788    tmp->fin = global_fin;
00789    tmp->fout = global_fout;
00790 
00791    if (ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
00792       ast_string_field_build(tmp, uniqueid, "%li.%d", (long) time(NULL), 
00793          ast_atomic_fetchadd_int(&uniqueint, 1));
00794    } else {
00795       ast_string_field_build(tmp, uniqueid, "%s-%li.%d", ast_config_AST_SYSTEM_NAME, 
00796          (long) time(NULL), ast_atomic_fetchadd_int(&uniqueint, 1));
00797    }
00798 
00799    tmp->cid.cid_name = ast_strdup(cid_name);
00800    tmp->cid.cid_num = ast_strdup(cid_num);
00801    
00802    if (!ast_strlen_zero(name_fmt)) {
00803       /* Almost every channel is calling this function, and setting the name via the ast_string_field_build() call.
00804        * And they all use slightly different formats for their name string.
00805        * This means, to set the name here, we have to accept variable args, and call the string_field_build from here.
00806        * This means, that the stringfields must have a routine that takes the va_lists directly, and 
00807        * uses them to build the string, instead of forming the va_lists internally from the vararg ... list.
00808        * This new function was written so this can be accomplished.
00809        */
00810       va_start(ap1, name_fmt);
00811       va_start(ap2, name_fmt);
00812       ast_string_field_build_va(tmp, name, name_fmt, ap1, ap2);
00813       va_end(ap1);
00814       va_end(ap2);
00815    }
00816 
00817    /* Reminder for the future: under what conditions do we NOT want to track cdrs on channels? */
00818 
00819    /* These 4 variables need to be set up for the cdr_init() to work right */
00820    if (amaflag)
00821       tmp->amaflags = amaflag;
00822    else
00823       tmp->amaflags = ast_default_amaflags;
00824    
00825    if (!ast_strlen_zero(acctcode))
00826       ast_string_field_set(tmp, accountcode, acctcode);
00827    else
00828       ast_string_field_set(tmp, accountcode, ast_default_accountcode);
00829       
00830    if (!ast_strlen_zero(context))
00831       ast_copy_string(tmp->context, context, sizeof(tmp->context));
00832    else
00833       strcpy(tmp->context, "default");
00834 
00835    if (!ast_strlen_zero(exten))
00836       ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
00837    else
00838       strcpy(tmp->exten, "s");
00839 
00840    tmp->priority = 1;
00841       
00842    tmp->cdr = ast_cdr_alloc();
00843    ast_cdr_init(tmp->cdr, tmp);
00844    ast_cdr_start(tmp->cdr);
00845    
00846    headp = &tmp->varshead;
00847    AST_LIST_HEAD_INIT_NOLOCK(headp);
00848    
00849    ast_mutex_init(&tmp->lock);
00850    
00851    AST_LIST_HEAD_INIT_NOLOCK(&tmp->datastores);
00852    
00853    ast_string_field_set(tmp, language, defaultlanguage);
00854 
00855    tmp->tech = &null_tech;
00856 
00857    AST_LIST_LOCK(&channels);
00858    AST_LIST_INSERT_HEAD(&channels, tmp, chan_list);
00859    AST_LIST_UNLOCK(&channels);
00860 
00861    /*\!note
00862     * and now, since the channel structure is built, and has its name, let's
00863     * call the manager event generator with this Newchannel event. This is the
00864     * proper and correct place to make this call, but you sure do have to pass
00865     * a lot of data into this func to do it here!
00866     */
00867    if (!ast_strlen_zero(name_fmt)) {
00868       manager_event(EVENT_FLAG_CALL, "Newchannel",
00869             "Channel: %s\r\n"
00870             "State: %s\r\n"
00871             "CallerIDNum: %s\r\n"
00872             "CallerIDName: %s\r\n"
00873             "Uniqueid: %s\r\n",
00874             tmp->name, ast_state2str(state),
00875             S_OR(cid_num, "<unknown>"),
00876             S_OR(cid_name, "<unknown>"),
00877             tmp->uniqueid);
00878    }
00879 
00880    return tmp;
00881 }
00882 
00883 /*! \brief Queue an outgoing media frame */
00884 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
00885 {
00886    struct ast_frame *f;
00887    struct ast_frame *cur;
00888    int blah = 1;
00889    int qlen = 0;
00890 
00891    /* Build us a copy and free the original one */
00892    if (!(f = ast_frdup(fin))) {
00893       ast_log(LOG_WARNING, "Unable to duplicate frame\n");
00894       return -1;
00895    }
00896    ast_channel_lock(chan);
00897 
00898    /* See if the last frame on the queue is a hangup, if so don't queue anything */
00899    if ((cur = AST_LIST_LAST(&chan->readq)) && (cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
00900       ast_frfree(f);
00901       ast_channel_unlock(chan);
00902       return 0;
00903    }
00904 
00905    /* Count how many frames exist on the queue */
00906    AST_LIST_TRAVERSE(&chan->readq, cur, frame_list) {
00907       qlen++;
00908    }
00909 
00910    /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
00911    if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
00912       if (fin->frametype != AST_FRAME_VOICE) {
00913          ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
00914          ast_assert(0);
00915       } else {
00916          if (option_debug)
00917             ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
00918          ast_frfree(f);
00919          ast_channel_unlock(chan);
00920          return 0;
00921       }
00922    }
00923    AST_LIST_INSERT_TAIL(&chan->readq, f, frame_list);
00924    if (chan->alertpipe[1] > -1) {
00925       if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
00926          ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
00927             chan->name, f->frametype, f->subclass, qlen, strerror(errno));
00928 #ifdef HAVE_ZAPTEL
00929    } else if (chan->timingfd > -1) {
00930       ioctl(chan->timingfd, ZT_TIMERPING, &blah);
00931 #endif            
00932    } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
00933       pthread_kill(chan->blocker, SIGURG);
00934    }
00935    ast_channel_unlock(chan);
00936    return 0;
00937 }
00938 
00939 /*! \brief Queue a hangup frame for channel */
00940 int ast_queue_hangup(struct ast_channel *chan)
00941 {
00942    struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
00943    /* Yeah, let's not change a lock-critical value without locking */
00944    if (!ast_channel_trylock(chan)) {
00945       chan->_softhangup |= AST_SOFTHANGUP_DEV;
00946       ast_channel_unlock(chan);
00947    }
00948    return ast_queue_frame(chan, &f);
00949 }
00950 
00951 /*! \brief Queue a control frame */
00952 int ast_queue_control(struct ast_channel *chan, enum ast_control_frame_type control)
00953 {
00954    struct ast_frame f = { AST_FRAME_CONTROL, };
00955 
00956    f.subclass = control;
00957 
00958    return ast_queue_frame(chan, &f);
00959 }
00960 
00961 /*! \brief Queue a control frame with payload */
00962 int ast_queue_control_data(struct ast_channel *chan, enum ast_control_frame_type control,
00963             const void *data, size_t datalen)
00964 {
00965    struct ast_frame f = { AST_FRAME_CONTROL, };
00966 
00967    f.subclass = control;
00968    f.data = (void *) data;
00969    f.datalen = datalen;
00970 
00971    return ast_queue_frame(chan, &f);
00972 }
00973 
00974 /*! \brief Set defer DTMF flag on channel */
00975 int ast_channel_defer_dtmf(struct ast_channel *chan)
00976 {
00977    int pre = 0;
00978 
00979    if (chan) {
00980       pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
00981       ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
00982    }
00983    return pre;
00984 }
00985 
00986 /*! \brief Unset defer DTMF flag on channel */
00987 void ast_channel_undefer_dtmf(struct ast_channel *chan)
00988 {
00989    if (chan)
00990       ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
00991 }
00992 
00993 /*!
00994  * \brief Helper function to find channels.
00995  *
00996  * It supports these modes:
00997  *
00998  * prev != NULL : get channel next in list after prev
00999  * name != NULL : get channel with matching name
01000  * name != NULL && namelen != 0 : get channel whose name starts with prefix
01001  * exten != NULL : get channel whose exten or macroexten matches
01002  * context != NULL && exten != NULL : get channel whose context or macrocontext
01003  *
01004  * It returns with the channel's lock held. If getting the individual lock fails,
01005  * unlock and retry quickly up to 10 times, then give up.
01006  *
01007  * \note XXX Note that this code has cost O(N) because of the need to verify
01008  * that the object is still on the global list.
01009  *
01010  * \note XXX also note that accessing fields (e.g. c->name in ast_log())
01011  * can only be done with the lock held or someone could delete the
01012  * object while we work on it. This causes some ugliness in the code.
01013  * Note that removing the first ast_log() may be harmful, as it would
01014  * shorten the retry period and possibly cause failures.
01015  * We should definitely go for a better scheme that is deadlock-free.
01016  */
01017 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
01018                       const char *name, const int namelen,
01019                       const char *context, const char *exten)
01020 {
01021    const char *msg = prev ? "deadlock" : "initial deadlock";
01022    int retries;
01023    struct ast_channel *c;
01024    const struct ast_channel *_prev = prev;
01025 
01026    for (retries = 0; retries < 200; retries++) {
01027       int done;
01028       AST_LIST_LOCK(&channels);
01029       AST_LIST_TRAVERSE(&channels, c, chan_list) {
01030          prev = _prev;
01031          if (prev) { /* look for next item */
01032             if (c != prev) /* not this one */
01033                continue;
01034             /* found, prepare to return c->next */
01035             if ((c = AST_LIST_NEXT(c, chan_list)) == NULL) break;
01036             /* If prev was the last item on the channel list, then we just
01037              * want to return NULL, instead of trying to deref NULL in the
01038              * next section.
01039              */
01040             prev = NULL;
01041             /* We want prev to be NULL in case we end up doing more searching through
01042              * the channel list to find the channel (ie: name searching). If we didn't
01043              * set this to NULL the logic would just blow up
01044              * XXX Need a better explanation for this ...
01045              */
01046          }
01047          if (name) { /* want match by name */
01048             if ((!namelen && strcasecmp(c->name, name)) ||
01049                 (namelen && strncasecmp(c->name, name, namelen)))
01050                continue;   /* name match failed */
01051          } else if (exten) {
01052             if (context && strcasecmp(c->context, context) &&
01053                 strcasecmp(c->macrocontext, context))
01054                continue;   /* context match failed */
01055             if (strcasecmp(c->exten, exten) &&
01056                 strcasecmp(c->macroexten, exten))
01057                continue;   /* exten match failed */
01058          }
01059          /* if we get here, c points to the desired record */
01060          break;
01061       }
01062       /* exit if chan not found or mutex acquired successfully */
01063       /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
01064       done = c == NULL || ast_channel_trylock(c) == 0;
01065       if (!done) {
01066          if (option_debug)
01067             ast_log(LOG_DEBUG, "Avoiding %s for channel '%p'\n", msg, c);
01068          if (retries == 199) {
01069             /* We are about to fail due to a deadlock, so report this
01070              * while we still have the list lock.
01071              */
01072             if (option_debug)
01073                ast_log(LOG_DEBUG, "Failure, could not lock '%p' after %d retries!\n", c, retries);
01074             /* As we have deadlocked, we will skip this channel and
01075              * see if there is another match.
01076              * NOTE: No point doing this for a full-name match,
01077              * as there can be no more matches.
01078              */
01079             if (!(name && !namelen)) {
01080                prev = c;
01081                retries = -1;
01082             }
01083          }
01084       }
01085       AST_LIST_UNLOCK(&channels);
01086       if (done)
01087          return c;
01088       /* If we reach this point we basically tried to lock a channel and failed. Instead of
01089        * starting from the beginning of the list we can restore our saved pointer to the previous
01090        * channel and start from there.
01091        */
01092       prev = _prev;
01093       usleep(1);  /* give other threads a chance before retrying */
01094    }
01095 
01096    return NULL;
01097 }
01098 
01099 /*! \brief Browse channels in use */
01100 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
01101 {
01102    return channel_find_locked(prev, NULL, 0, NULL, NULL);
01103 }
01104 
01105 /*! \brief Get channel by name and lock it */
01106 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
01107 {
01108    return channel_find_locked(NULL, name, 0, NULL, NULL);
01109 }
01110 
01111 /*! \brief Get channel by name prefix and lock it */
01112 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
01113 {
01114    return channel_find_locked(NULL, name, namelen, NULL, NULL);
01115 }
01116 
01117 /*! \brief Get next channel by name prefix and lock it */
01118 struct ast_channel *ast_walk_channel_by_name_prefix_locked(const struct ast_channel *chan, const char *name,
01119                         const int namelen)
01120 {
01121    return channel_find_locked(chan, name, namelen, NULL, NULL);
01122 }
01123 
01124 /*! \brief Get channel by exten (and optionally context) and lock it */
01125 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
01126 {
01127    return channel_find_locked(NULL, NULL, 0, context, exten);
01128 }
01129 
01130 /*! \brief Get next channel by exten (and optionally context) and lock it */
01131 struct ast_channel *ast_walk_channel_by_exten_locked(const struct ast_channel *chan, const char *exten,
01132                        const char *context)
01133 {
01134    return channel_find_locked(chan, NULL, 0, context, exten);
01135 }
01136 
01137 /*! \brief Wait, look for hangups and condition arg */
01138 int ast_safe_sleep_conditional(struct ast_channel *chan, int ms, int (*cond)(void*), void *data)
01139 {
01140    struct ast_frame *f;
01141 
01142    while (ms > 0) {
01143       if (cond && ((*cond)(data) == 0))
01144          return 0;
01145       ms = ast_waitfor(chan, ms);
01146       if (ms < 0)
01147          return -1;
01148       if (ms > 0) {
01149          f = ast_read(chan);
01150          if (!f)
01151             return -1;
01152          ast_frfree(f);
01153       }
01154    }
01155    return 0;
01156 }
01157 
01158 /*! \brief Wait, look for hangups */
01159 int ast_safe_sleep(struct ast_channel *chan, int ms)
01160 {
01161    return ast_safe_sleep_conditional(chan, ms, NULL, NULL);
01162 }
01163 
01164 static void free_cid(struct ast_callerid *cid)
01165 {
01166    if (cid->cid_dnid)
01167       free(cid->cid_dnid);
01168    if (cid->cid_num)
01169       free(cid->cid_num);  
01170    if (cid->cid_name)
01171       free(cid->cid_name); 
01172    if (cid->cid_ani)
01173       free(cid->cid_ani);
01174    if (cid->cid_rdnis)
01175       free(cid->cid_rdnis);
01176 }
01177 
01178 /*! \brief Free a channel structure */
01179 void ast_channel_free(struct ast_channel *chan)
01180 {
01181    int fd;
01182    struct ast_var_t *vardata;
01183    struct ast_frame *f;
01184    struct varshead *headp;
01185    struct ast_datastore *datastore = NULL;
01186    char name[AST_CHANNEL_NAME];
01187    
01188    headp=&chan->varshead;
01189    
01190    AST_LIST_LOCK(&channels);
01191    if (!AST_LIST_REMOVE(&channels, chan, chan_list)) {
01192       AST_LIST_UNLOCK(&channels);
01193       ast_log(LOG_ERROR, "Unable to find channel in list to free. Assuming it has already been done.\n");
01194    }
01195    /* Lock and unlock the channel just to be sure nobody has it locked still
01196       due to a reference retrieved from the channel list. */
01197    ast_channel_lock(chan);
01198    ast_channel_unlock(chan);
01199 
01200    /* Get rid of each of the data stores on the channel */
01201    while ((datastore = AST_LIST_REMOVE_HEAD(&chan->datastores, entry)))
01202       /* Free the data store */
01203       ast_channel_datastore_free(datastore);
01204 
01205    /* Lock and unlock the channel just to be sure nobody has it locked still
01206       due to a reference that was stored in a datastore. (i.e. app_chanspy) */
01207    ast_channel_lock(chan);
01208    ast_channel_unlock(chan);
01209 
01210    if (chan->tech_pvt) {
01211       ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
01212       free(chan->tech_pvt);
01213    }
01214 
01215    if (chan->sched)
01216       sched_context_destroy(chan->sched);
01217 
01218    ast_copy_string(name, chan->name, sizeof(name));
01219 
01220    /* Stop monitoring */
01221    if (chan->monitor)
01222       chan->monitor->stop( chan, 0 );
01223 
01224    /* If there is native format music-on-hold state, free it */
01225    if (chan->music_state)
01226       ast_moh_cleanup(chan);
01227 
01228    /* Free translators */
01229    if (chan->readtrans)
01230       ast_translator_free_path(chan->readtrans);
01231    if (chan->writetrans)
01232       ast_translator_free_path(chan->writetrans);
01233    if (chan->pbx)
01234       ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
01235    free_cid(&chan->cid);
01236    /* Close pipes if appropriate */
01237    if ((fd = chan->alertpipe[0]) > -1)
01238       close(fd);
01239    if ((fd = chan->alertpipe[1]) > -1)
01240       close(fd);
01241    if ((fd = chan->timingfd) > -1)
01242       close(fd);
01243    while ((f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list)))
01244       ast_frfree(f);
01245    
01246    /* loop over the variables list, freeing all data and deleting list items */
01247    /* no need to lock the list, as the channel is already locked */
01248    
01249    while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries)))
01250       ast_var_delete(vardata);
01251 
01252    ast_app_group_discard(chan);
01253 
01254    /* Destroy the jitterbuffer */
01255    ast_jb_destroy(chan);
01256    
01257    ast_mutex_destroy(&chan->lock);
01258 
01259    ast_string_field_free_memory(chan);
01260    free(chan);
01261    AST_LIST_UNLOCK(&channels);
01262 
01263    ast_device_state_changed_literal(name);
01264 }
01265 
01266 struct ast_datastore *ast_channel_datastore_alloc(const struct ast_datastore_info *info, char *uid)
01267 {
01268    struct ast_datastore *datastore = NULL;
01269 
01270    /* Make sure we at least have type so we can identify this */
01271    if (info == NULL) {
01272       return NULL;
01273    }
01274 
01275    /* Allocate memory for datastore and clear it */
01276    datastore = ast_calloc(1, sizeof(*datastore));
01277    if (datastore == NULL) {
01278       return NULL;
01279    }
01280 
01281    datastore->info = info;
01282 
01283    datastore->uid = ast_strdup(uid);
01284 
01285    return datastore;
01286 }
01287 
01288 int ast_channel_datastore_free(struct ast_datastore *datastore)
01289 {
01290    int res = 0;
01291 
01292    /* Using the destroy function (if present) destroy the data */
01293    if (datastore->info->destroy != NULL && datastore->data != NULL) {
01294       datastore->info->destroy(datastore->data);
01295       datastore->data = NULL;
01296    }
01297 
01298    /* Free allocated UID memory */
01299    if (datastore->uid != NULL) {
01300       free(datastore->uid);
01301       datastore->uid = NULL;
01302    }
01303 
01304    /* Finally free memory used by ourselves */
01305    free(datastore);
01306 
01307    return res;
01308 }
01309 
01310 int ast_channel_datastore_inherit(struct ast_channel *from, struct ast_channel *to)
01311 {
01312    struct ast_datastore *datastore = NULL, *datastore2;
01313 
01314    AST_LIST_TRAVERSE(&from->datastores, datastore, entry) {
01315       if (datastore->inheritance > 0) {
01316          datastore2 = ast_channel_datastore_alloc(datastore->info, datastore->uid);
01317          if (datastore2) {
01318             datastore2->data = datastore->info->duplicate(datastore->data);
01319             datastore2->inheritance = datastore->inheritance == DATASTORE_INHERIT_FOREVER ? DATASTORE_INHERIT_FOREVER : datastore->inheritance - 1;
01320             AST_LIST_INSERT_TAIL(&to->datastores, datastore2, entry);
01321          }
01322       }
01323    }
01324    return 0;
01325 }
01326 
01327 int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
01328 {
01329    int res = 0;
01330 
01331    AST_LIST_INSERT_HEAD(&chan->datastores, datastore, entry);
01332 
01333    return res;
01334 }
01335 
01336 int ast_channel_datastore_remove(struct ast_channel *chan, struct ast_datastore *datastore)
01337 {
01338    struct ast_datastore *datastore2 = NULL;
01339    int res = -1;
01340 
01341    /* Find our position and remove ourselves */
01342    AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore2, entry) {
01343       if (datastore2 == datastore) {
01344          AST_LIST_REMOVE_CURRENT(&chan->datastores, entry);
01345          res = 0;
01346          break;
01347       }
01348    }
01349    AST_LIST_TRAVERSE_SAFE_END
01350 
01351    return res;
01352 }
01353 
01354 struct ast_datastore *ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, char *uid)
01355 {
01356    struct ast_datastore *datastore = NULL;
01357    
01358    if (info == NULL)
01359       return NULL;
01360 
01361    AST_LIST_TRAVERSE_SAFE_BEGIN(&chan->datastores, datastore, entry) {
01362       if (datastore->info == info) {
01363          if (uid != NULL && datastore->uid != NULL) {
01364             if (!strcasecmp(uid, datastore->uid)) {
01365                /* Matched by type AND uid */
01366                break;
01367             }
01368          } else {
01369             /* Matched by type at least */
01370             break;
01371          }
01372       }
01373    }
01374    AST_LIST_TRAVERSE_SAFE_END
01375 
01376    return datastore;
01377 }
01378 
01379 /*! \brief Softly hangup a channel, don't lock */
01380 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
01381 {
01382    if (option_debug)
01383       ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
01384    /* Inform channel driver that we need to be hung up, if it cares */
01385    chan->_softhangup |= cause;
01386    ast_queue_frame(chan, &ast_null_frame);
01387    /* Interrupt any poll call or such */
01388    if (ast_test_flag(chan, AST_FLAG_BLOCKING))
01389       pthread_kill(chan->blocker, SIGURG);
01390    return 0;
01391 }
01392 
01393 /*! \brief Softly hangup a channel, lock */
01394 int ast_softhangup(struct ast_channel *chan, int cause)
01395 {
01396    int res;
01397    ast_channel_lock(chan);
01398    res = ast_softhangup_nolock(chan, cause);
01399    ast_channel_unlock(chan);
01400    return res;
01401 }
01402 
01403 static void free_translation(struct ast_channel *clone)
01404 {
01405    if (clone->writetrans)
01406       ast_translator_free_path(clone->writetrans);
01407    if (clone->readtrans)
01408       ast_translator_free_path(clone->readtrans);
01409    clone->writetrans = NULL;
01410    clone->readtrans = NULL;
01411    clone->rawwriteformat = clone->nativeformats;
01412    clone->rawreadformat = clone->nativeformats;
01413 }
01414 
01415 /*! \brief Hangup a channel */
01416 int ast_hangup(struct ast_channel *chan)
01417 {
01418    int res = 0;
01419    struct ast_cdr *cdr = NULL;
01420 
01421    /* Don't actually hang up a channel that will masquerade as someone else, or
01422       if someone is going to masquerade as us */
01423    ast_channel_lock(chan);
01424 
01425    if (chan->audiohooks) {
01426       ast_audiohook_detach_list(chan->audiohooks);
01427       chan->audiohooks = NULL;
01428    }
01429 
01430    ast_autoservice_stop(chan);
01431 
01432    if (chan->masq) {
01433       if (ast_do_masquerade(chan))
01434          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
01435    }
01436 
01437    if (chan->masq) {
01438       ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
01439       ast_channel_unlock(chan);
01440       return 0;
01441    }
01442    /* If this channel is one which will be masqueraded into something,
01443       mark it as a zombie already, so we know to free it later */
01444    if (chan->masqr) {
01445       ast_set_flag(chan, AST_FLAG_ZOMBIE);
01446       ast_channel_unlock(chan);
01447       return 0;
01448    }
01449    free_translation(chan);
01450    /* Close audio stream */
01451    if (chan->stream) {
01452       ast_closestream(chan->stream);
01453       chan->stream = NULL;
01454    }
01455    /* Close video stream */
01456    if (chan->vstream) {
01457       ast_closestream(chan->vstream);
01458       chan->vstream = NULL;
01459    }
01460    if (chan->sched) {
01461       sched_context_destroy(chan->sched);
01462       chan->sched = NULL;
01463    }
01464    
01465    if (chan->generatordata)   /* Clear any tone stuff remaining */
01466       chan->generator->release(chan, chan->generatordata);
01467    chan->generatordata = NULL;
01468    chan->generator = NULL;
01469    if (chan->cdr) {     /* End the CDR if it hasn't already */
01470       ast_cdr_end(chan->cdr);
01471       cdr = chan->cdr;
01472       chan->cdr = NULL;
01473    }
01474    if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
01475       ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
01476                "is blocked by thread %ld in procedure %s!  Expect a failure\n",
01477                (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
01478       ast_assert(0);
01479    }
01480    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
01481       if (option_debug)
01482          ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
01483       if (chan->tech->hangup)
01484          res = chan->tech->hangup(chan);
01485    } else {
01486       if (option_debug)
01487          ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
01488    }
01489          
01490    ast_channel_unlock(chan);
01491    manager_event(EVENT_FLAG_CALL, "Hangup",
01492          "Channel: %s\r\n"
01493          "Uniqueid: %s\r\n"
01494          "Cause: %d\r\n"
01495          "Cause-txt: %s\r\n",
01496          chan->name,
01497          chan->uniqueid,
01498          chan->hangupcause,
01499          ast_cause2str(chan->hangupcause)
01500          );
01501    ast_channel_free(chan);
01502 
01503    if (cdr)
01504       ast_cdr_detach(cdr);
01505 
01506    return res;
01507 }
01508 
01509 int ast_answer(struct ast_channel *chan)
01510 {
01511    int res = 0;
01512    ast_channel_lock(chan);
01513    /* You can't answer an outbound call */
01514    if (ast_test_flag(chan, AST_FLAG_OUTGOING)) {
01515       ast_channel_unlock(chan);
01516       return 0;
01517    }
01518    /* Stop if we're a zombie or need a soft hangup */
01519    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
01520       ast_channel_unlock(chan);
01521       return -1;
01522    }
01523    switch(chan->_state) {
01524    case AST_STATE_RINGING:
01525    case AST_STATE_RING:
01526       if (chan->tech->answer)
01527          res = chan->tech->answer(chan);
01528       ast_setstate(chan, AST_STATE_UP);
01529       ast_cdr_answer(chan->cdr);
01530       break;
01531    case AST_STATE_UP:
01532       ast_cdr_answer(chan->cdr);
01533       break;
01534    default:
01535       break;
01536    }
01537    chan->visible_indication = 0;
01538    ast_channel_unlock(chan);
01539    return res;
01540 }
01541 
01542 void ast_deactivate_generator(struct ast_channel *chan)
01543 {
01544    ast_channel_lock(chan);
01545    if (chan->generatordata) {
01546       if (chan->generator && chan->generator->release)
01547          chan->generator->release(chan, chan->generatordata);
01548       chan->generatordata = NULL;
01549       chan->generator = NULL;
01550       chan->fds[AST_GENERATOR_FD] = -1;
01551       ast_clear_flag(chan, AST_FLAG_WRITE_INT);
01552       ast_settimeout(chan, 0, NULL, NULL);
01553    }
01554    ast_channel_unlock(chan);
01555 }
01556 
01557 static int generator_force(const void *data)
01558 {
01559    /* Called if generator doesn't have data */
01560    void *tmp;
01561    int res;
01562    int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
01563    struct ast_channel *chan = (struct ast_channel *)data;
01564 
01565    ast_channel_lock(chan);
01566    tmp = chan->generatordata;
01567    chan->generatordata = NULL;
01568    if (chan->generator)
01569       generate = chan->generator->generate;
01570    ast_channel_unlock(chan);
01571 
01572    if (!tmp || !generate)
01573       return 0;
01574 
01575    res = generate(chan, tmp, 0, ast_format_rate(chan->writeformat & AST_FORMAT_AUDIO_MASK) / 50);
01576 
01577    chan->generatordata = tmp;
01578 
01579    if (res) {
01580       if (option_debug)
01581          ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
01582       ast_deactivate_generator(chan);
01583    }
01584 
01585    return 0;
01586 }
01587 
01588 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
01589 {
01590    int res = 0;
01591 
01592    ast_channel_lock(chan);
01593 
01594    if (chan->generatordata) {
01595       if (chan->generator && chan->generator->release)
01596          chan->generator->release(chan, chan->generatordata);
01597       chan->generatordata = NULL;
01598    }
01599 
01600    ast_prod(chan);
01601    if (gen->alloc && !(chan->generatordata = gen->alloc(chan, params))) {
01602       res = -1;
01603    }
01604    
01605    if (!res) {
01606       ast_settimeout(chan, 160, generator_force, chan);
01607       chan->generator = gen;
01608    }
01609 
01610    ast_channel_unlock(chan);
01611 
01612    return res;
01613 }
01614 
01615 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
01616 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
01617 {
01618    int winner = -1;
01619    ast_waitfor_nandfds(NULL, 0, fds, n, exception, &winner, ms);
01620    return winner;
01621 }
01622 
01623 /*! \brief Wait for x amount of time on a file descriptor to have input.  */
01624 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds,
01625    int *exception, int *outfd, int *ms)
01626 {
01627    struct timeval start = { 0 , 0 };
01628    struct pollfd *pfds = NULL;
01629    int res;
01630    long rms;
01631    int x, y, max;
01632    int sz;
01633    time_t now = 0;
01634    long whentohangup = 0, diff;
01635    struct ast_channel *winner = NULL;
01636    struct fdmap {
01637       int chan;
01638       int fdno;
01639    } *fdmap = NULL;
01640 
01641    if ((sz = n * AST_MAX_FDS + nfds)) {
01642       pfds = alloca(sizeof(*pfds) * sz);
01643       fdmap = alloca(sizeof(*fdmap) * sz);
01644    }
01645 
01646    if (outfd)
01647       *outfd = -99999;
01648    if (exception)
01649       *exception = 0;
01650    
01651    /* Perform any pending masquerades */
01652    for (x=0; x < n; x++) {
01653       ast_channel_lock(c[x]);
01654       if (c[x]->masq) {
01655          if (ast_do_masquerade(c[x])) {
01656             ast_log(LOG_WARNING, "Masquerade failed\n");
01657             *ms = -1;
01658             ast_channel_unlock(c[x]);
01659             return NULL;
01660          }
01661       }
01662       if (c[x]->whentohangup) {
01663          if (!whentohangup)
01664             time(&now);
01665          diff = c[x]->whentohangup - now;
01666          if (diff < 1) {
01667             /* Should already be hungup */
01668             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
01669             ast_channel_unlock(c[x]);
01670             return c[x];
01671          }
01672          if (!whentohangup || (diff < whentohangup))
01673             whentohangup = diff;
01674       }
01675       ast_channel_unlock(c[x]);
01676    }
01677    /* Wait full interval */
01678    rms = *ms;
01679    if (whentohangup) {
01680       rms = whentohangup * 1000;              /* timeout in milliseconds */
01681       if (*ms >= 0 && *ms < rms)    /* original *ms still smaller */
01682          rms =  *ms;
01683    }
01684    /*
01685     * Build the pollfd array, putting the channels' fds first,
01686     * followed by individual fds. Order is important because
01687     * individual fd's must have priority over channel fds.
01688     */
01689    max = 0;
01690    for (x=0; x<n; x++) {
01691       for (y=0; y<AST_MAX_FDS; y++) {
01692          fdmap[max].fdno = y;  /* fd y is linked to this pfds */
01693          fdmap[max].chan = x;  /* channel x is linked to this pfds */
01694          max += ast_add_fd(&pfds[max], c[x]->fds[y]);
01695       }
01696       CHECK_BLOCKING(c[x]);
01697    }
01698    /* Add the individual fds */
01699    for (x=0; x<nfds; x++) {
01700       fdmap[max].chan = -1;
01701       max += ast_add_fd(&pfds[max], fds[x]);
01702    }
01703 
01704    if (*ms > 0)
01705       start = ast_tvnow();
01706    
01707    if (sizeof(int) == 4) { /* XXX fix timeout > 600000 on linux x86-32 */
01708       do {
01709          int kbrms = rms;
01710          if (kbrms > 600000)
01711             kbrms = 600000;
01712          res = poll(pfds, max, kbrms);
01713          if (!res)
01714             rms -= kbrms;
01715       } while (!res && (rms > 0));
01716    } else {
01717       res = poll(pfds, max, rms);
01718    }
01719    for (x=0; x<n; x++)
01720       ast_clear_flag(c[x], AST_FLAG_BLOCKING);
01721    if (res < 0) { /* Simulate a timeout if we were interrupted */
01722       if (errno != EINTR)
01723          *ms = -1;
01724       return NULL;
01725    }
01726    if (whentohangup) {   /* if we have a timeout, check who expired */
01727       time(&now);
01728       for (x=0; x<n; x++) {
01729          if (c[x]->whentohangup && now >= c[x]->whentohangup) {
01730             c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
01731             if (winner == NULL)
01732                winner = c[x];
01733          }
01734       }
01735    }
01736    if (res == 0) { /* no fd ready, reset timeout and done */
01737       *ms = 0; /* XXX use 0 since we may not have an exact timeout. */
01738       return winner;
01739    }
01740    /*
01741     * Then check if any channel or fd has a pending event.
01742     * Remember to check channels first and fds last, as they
01743     * must have priority on setting 'winner'
01744     */
01745    for (x = 0; x < max; x++) {
01746       res = pfds[x].revents;
01747       if (res == 0)
01748          continue;
01749       if (fdmap[x].chan >= 0) {  /* this is a channel */
01750          winner = c[fdmap[x].chan]; /* override previous winners */
01751          if (res & POLLPRI)
01752             ast_set_flag(winner, AST_FLAG_EXCEPTION);
01753          else
01754             ast_clear_flag(winner, AST_FLAG_EXCEPTION);
01755          winner->fdno = fdmap[x].fdno;
01756       } else {       /* this is an fd */
01757          if (outfd)
01758             *outfd = pfds[x].fd;
01759          if (exception)
01760             *exception = (res & POLLPRI) ? -1 : 0;
01761          winner = NULL;
01762       }
01763    }
01764    if (*ms > 0) {
01765       *ms -= ast_tvdiff_ms(ast_tvnow(), start);
01766       if (*ms < 0)
01767          *ms = 0;
01768    }
01769    return winner;
01770 }
01771 
01772 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
01773 {
01774    return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
01775 }
01776 
01777 int ast_waitfor(struct ast_channel *c, int ms)
01778 {
01779    int oldms = ms;   /* -1 if no timeout */
01780 
01781    ast_waitfor_nandfds(&c, 1, NULL, 0, NULL, NULL, &ms);
01782    if ((ms < 0) && (oldms < 0))
01783       ms = 0;
01784    return ms;
01785 }
01786 
01787 /* XXX never to be called with ms = -1 */
01788 int ast_waitfordigit(struct ast_channel *c, int ms)
01789 {
01790    return ast_waitfordigit_full(c, ms, -1, -1);
01791 }
01792 
01793 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(const void *data), void *data)
01794 {
01795    int res = -1;
01796 #ifdef HAVE_ZAPTEL
01797    if (c->timingfd > -1) {
01798       if (!func) {
01799          samples = 0;
01800          data = 0;
01801       }
01802       if (option_debug)
01803          ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
01804       res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
01805       c->timingfunc = func;
01806       c->timingdata = data;
01807    }
01808 #endif   
01809    return res;
01810 }
01811 
01812 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
01813 {
01814    /* Stop if we're a zombie or need a soft hangup */
01815    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
01816       return -1;
01817 
01818    /* Only look for the end of DTMF, don't bother with the beginning and don't emulate things */
01819    ast_set_flag(c, AST_FLAG_END_DTMF_ONLY);
01820 
01821    /* Wait for a digit, no more than ms milliseconds total. */
01822    while (ms) {
01823       struct ast_channel *rchan;
01824       int outfd;
01825 
01826       errno = 0;
01827       rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
01828       if (!rchan && outfd < 0 && ms) {
01829          if (errno == 0 || errno == EINTR)
01830             continue;
01831          ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
01832          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
01833          return -1;
01834       } else if (outfd > -1) {
01835          /* The FD we were watching has something waiting */
01836          ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
01837          return 1;
01838       } else if (rchan) {
01839          int res;
01840          struct ast_frame *f = ast_read(c);
01841          if (!f)
01842             return -1;
01843 
01844          switch(f->frametype) {
01845          case AST_FRAME_DTMF_BEGIN:
01846             break;
01847          case AST_FRAME_DTMF_END:
01848             res = f->subclass;
01849             ast_frfree(f);
01850             ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
01851             return res;
01852          case AST_FRAME_CONTROL:
01853             switch(f->subclass) {
01854             case AST_CONTROL_HANGUP:
01855                ast_frfree(f);
01856                ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
01857                return -1;
01858             case AST_CONTROL_RINGING:
01859             case AST_CONTROL_ANSWER:
01860             case AST_CONTROL_SRCUPDATE:
01861                /* Unimportant */
01862                break;
01863             default:
01864                ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
01865                break;
01866             }
01867             break;
01868          case AST_FRAME_VOICE:
01869             /* Write audio if appropriate */
01870             if (audiofd > -1)
01871                write(audiofd, f->data, f->datalen);
01872          default:
01873             /* Ignore */
01874             break;
01875          }
01876          ast_frfree(f);
01877       }
01878    }
01879 
01880    ast_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
01881 
01882    return 0; /* Time is up */
01883 }
01884 
01885 static void ast_read_generator_actions(struct ast_channel *chan, struct ast_frame *f)
01886 {
01887    if (chan->generatordata &&  !ast_internal_timing_enabled(chan)) {
01888       void *tmp = chan->generatordata;
01889       int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples) = NULL;
01890       int res;
01891       int samples;
01892 
01893       if (chan->timingfunc) {
01894          if (option_debug > 1)
01895             ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
01896          ast_settimeout(chan, 0, NULL, NULL);
01897       }
01898 
01899       chan->generatordata = NULL;     /* reset, to let writes go through */
01900 
01901       if (f->subclass != chan->writeformat) {
01902          float factor;
01903          factor = ((float) ast_format_rate(chan->writeformat)) / ((float) ast_format_rate(f->subclass));
01904          samples = (int) ( ((float) f->samples) * factor );
01905       } else {
01906          samples = f->samples;
01907       }
01908 
01909       if (chan->generator->generate) {
01910          generate = chan->generator->generate;
01911       }
01912       /* This unlock is here based on two assumptions that hold true at this point in the
01913        * code. 1) this function is only called from within __ast_read() and 2) all generators
01914        * call ast_write() in their generate callback.
01915        *
01916        * The reason this is added is so that when ast_write is called, the lock that occurs 
01917        * there will not recursively lock the channel. Doing this will cause intended deadlock 
01918        * avoidance not to work in deeper functions
01919        */
01920       ast_channel_unlock(chan);
01921       res = generate(chan, tmp, f->datalen, samples);
01922       ast_channel_lock(chan);
01923       chan->generatordata = tmp;
01924       if (res) {
01925          if (option_debug > 1)
01926             ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
01927          ast_deactivate_generator(chan);
01928       }
01929 
01930    } else if (f->frametype == AST_FRAME_CNG) {
01931       if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
01932          if (option_debug > 1)
01933             ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
01934          ast_settimeout(chan, 160, generator_force, chan);
01935       }
01936    }
01937 }
01938 
01939 static struct ast_frame *__ast_read(struct ast_channel *chan, int dropaudio)
01940 {
01941    struct ast_frame *f = NULL;   /* the return value */
01942    int blah;
01943    int prestate;
01944    int count = 0;
01945 
01946    /* this function is very long so make sure there is only one return
01947     * point at the end (there are only two exceptions to this).
01948     */
01949    while(ast_channel_trylock(chan)) {
01950       if(count++ > 10) 
01951          /*cannot goto done since the channel is not locked*/
01952          return &ast_null_frame;
01953       usleep(1);
01954    }
01955 
01956    if (chan->masq) {
01957       if (ast_do_masquerade(chan))
01958          ast_log(LOG_WARNING, "Failed to perform masquerade\n");
01959       else
01960          f =  &ast_null_frame;
01961       goto done;
01962    }
01963 
01964    /* Stop if we're a zombie or need a soft hangup */
01965    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
01966       if (chan->generator)
01967          ast_deactivate_generator(chan);
01968       goto done;
01969    }
01970    prestate = chan->_state;
01971 
01972    if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_EMULATE_DTMF | AST_FLAG_IN_DTMF) && 
01973        !ast_strlen_zero(chan->dtmfq) && 
01974       (ast_tvzero(chan->dtmf_tv) || ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) > AST_MIN_DTMF_GAP) ) {
01975       /* We have DTMF that has been deferred.  Return it now */
01976       chan->dtmff.subclass = chan->dtmfq[0];
01977       /* Drop first digit from the buffer */
01978       memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
01979       f = &chan->dtmff;
01980       if (ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) {
01981          ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
01982          chan->dtmff.frametype = AST_FRAME_DTMF_END;
01983       } else {
01984          ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %d queued on %s\n", f->subclass, AST_DEFAULT_EMULATE_DTMF_DURATION, chan->name);
01985          chan->dtmff.frametype = AST_FRAME_DTMF_BEGIN;
01986          ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
01987          chan->emulate_dtmf_digit = f->subclass;
01988          chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
01989       }
01990       chan->dtmf_tv = ast_tvnow();
01991       goto done;
01992    }
01993    
01994    /* Read and ignore anything on the alertpipe, but read only
01995       one sizeof(blah) per frame that we send from it */
01996    if (chan->alertpipe[0] > -1)
01997       read(chan->alertpipe[0], &blah, sizeof(blah));
01998 
01999 #ifdef HAVE_ZAPTEL
02000    if (chan->timingfd > -1 && chan->fdno == AST_TIMING_FD && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
02001       int res;
02002 
02003       ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02004       blah = -1;
02005       /* IF we can't get event, assume it's an expired as-per the old interface */
02006       res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
02007       if (res)
02008          blah = ZT_EVENT_TIMER_EXPIRED;
02009 
02010       if (blah == ZT_EVENT_TIMER_PING) {
02011          if (AST_LIST_EMPTY(&chan->readq) || !AST_LIST_NEXT(AST_LIST_FIRST(&chan->readq), frame_list)) {
02012             /* Acknowledge PONG unless we need it again */
02013             if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
02014                ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
02015             }
02016          }
02017       } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
02018          ioctl(chan->timingfd, ZT_TIMERACK, &blah);
02019          if (chan->timingfunc) {
02020             /* save a copy of func/data before unlocking the channel */
02021             int (*func)(const void *) = chan->timingfunc;
02022             void *data = chan->timingdata;
02023             ast_channel_unlock(chan);
02024             func(data);
02025          } else {
02026             blah = 0;
02027             ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
02028             chan->timingdata = NULL;
02029             ast_channel_unlock(chan);
02030          }
02031          /* cannot 'goto done' because the channel is already unlocked */
02032          return &ast_null_frame;
02033       } else
02034          ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
02035    } else
02036 #endif
02037    if (chan->fds[AST_GENERATOR_FD] > -1 && chan->fdno == AST_GENERATOR_FD) {
02038       /* if the AST_GENERATOR_FD is set, call the generator with args
02039        * set to -1 so it can do whatever it needs to.
02040        */
02041       void *tmp = chan->generatordata;
02042       chan->generatordata = NULL;     /* reset to let ast_write get through */
02043       chan->generator->generate(chan, tmp, -1, -1);
02044       chan->generatordata = tmp;
02045       f = &ast_null_frame;
02046       goto done;
02047    }
02048 
02049    /* Check for pending read queue */
02050    if (!AST_LIST_EMPTY(&chan->readq)) {
02051       f = AST_LIST_REMOVE_HEAD(&chan->readq, frame_list);
02052       /* Interpret hangup and return NULL */
02053       /* XXX why not the same for frames from the channel ? */
02054       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
02055          ast_frfree(f);
02056          f = NULL;
02057       }
02058    } else {
02059       chan->blocker = pthread_self();
02060       if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
02061          if (chan->tech->exception)
02062             f = chan->tech->exception(chan);
02063          else {
02064             ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
02065             f = &ast_null_frame;
02066          }
02067          /* Clear the exception flag */
02068          ast_clear_flag(chan, AST_FLAG_EXCEPTION);
02069       } else if (chan->tech->read)
02070          f = chan->tech->read(chan);
02071       else
02072          ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
02073    }
02074 
02075    if (f) {
02076       /* if the channel driver returned more than one frame, stuff the excess
02077          into the readq for the next ast_read call (note that we can safely assume
02078          that the readq is empty, because otherwise we would not have called into
02079          the channel driver and f would be only a single frame)
02080       */
02081       if (AST_LIST_NEXT(f, frame_list)) {
02082          AST_LIST_HEAD_SET_NOLOCK(&chan->readq, AST_LIST_NEXT(f, frame_list));
02083          AST_LIST_NEXT(f, frame_list) = NULL;
02084       }
02085 
02086       switch (f->frametype) {
02087       case AST_FRAME_CONTROL:
02088          if (f->subclass == AST_CONTROL_ANSWER) {
02089             if (!ast_test_flag(chan, AST_FLAG_OUTGOING)) {
02090                if (option_debug)
02091                   ast_log(LOG_DEBUG, "Ignoring answer on an inbound call!\n");
02092                ast_frfree(f);
02093                f = &ast_null_frame;
02094             } else if (prestate == AST_STATE_UP) {
02095                if (option_debug)
02096                   ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
02097                ast_frfree(f);
02098                f = &ast_null_frame;
02099             } else {
02100                /* Answer the CDR */
02101                ast_setstate(chan, AST_STATE_UP);
02102                if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
02103                                to keep from throwing off the basic order of the universe,
02104                                we will try to keep this cdr from getting posted. */
02105                   chan->cdr = ast_cdr_alloc();
02106                   ast_cdr_init(chan->cdr, chan);
02107                   ast_cdr_start(chan->cdr);
02108                }
02109                
02110                ast_cdr_answer(chan->cdr);
02111             }
02112          }
02113          break;
02114       case AST_FRAME_DTMF_END:
02115          ast_log(LOG_DTMF, "DTMF end '%c' received on %s, duration %ld ms\n", f->subclass, chan->name, f->len);
02116          /* Queue it up if DTMF is deffered, or if DTMF emulation is forced.
02117           * However, only let emulation be forced if the other end cares about BEGIN frames */
02118          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF) ||
02119             (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_END_DTMF_ONLY)) ) {
02120             if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
02121                ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
02122                chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
02123             } else
02124                ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
02125             ast_frfree(f);
02126             f = &ast_null_frame;
02127          } else if (!ast_test_flag(chan, AST_FLAG_IN_DTMF | AST_FLAG_END_DTMF_ONLY)) {
02128             if (!ast_tvzero(chan->dtmf_tv) && 
02129                 ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) {
02130                /* If it hasn't been long enough, defer this digit */
02131                if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2) {
02132                   ast_log(LOG_DTMF, "DTMF end '%c' put into dtmf queue on %s\n", f->subclass, chan->name);
02133                   chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
02134                } else
02135                   ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
02136                ast_frfree(f);
02137                f = &ast_null_frame;
02138             } else {
02139                /* There was no begin, turn this into a begin and send the end later */
02140                f->frametype = AST_FRAME_DTMF_BEGIN;
02141                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
02142                chan->emulate_dtmf_digit = f->subclass;
02143                chan->dtmf_tv = ast_tvnow();
02144                if (f->len) {
02145                   if (f->len > AST_MIN_DTMF_DURATION)
02146                      chan->emulate_dtmf_duration = f->len;
02147                   else 
02148                      chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION;
02149                } else
02150                   chan->emulate_dtmf_duration = AST_DEFAULT_EMULATE_DTMF_DURATION;
02151                ast_log(LOG_DTMF, "DTMF begin emulation of '%c' with duration %u queued on %s\n", f->subclass, chan->emulate_dtmf_duration, chan->name);
02152             }
02153             if (chan->audiohooks) {
02154                struct ast_frame *old_frame = f;
02155                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02156                if (old_frame != f)
02157                   ast_frfree(old_frame);
02158                                 }
02159          } else {
02160             struct timeval now = ast_tvnow();
02161             if (ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02162                ast_log(LOG_DTMF, "DTMF end accepted with begin '%c' on %s\n", f->subclass, chan->name);
02163                ast_clear_flag(chan, AST_FLAG_IN_DTMF);
02164                if (!f->len)
02165                   f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02166             } else if (!f->len) {
02167                ast_log(LOG_DTMF, "DTMF end accepted without begin '%c' on %s\n", f->subclass, chan->name);
02168                f->len = AST_MIN_DTMF_DURATION;
02169             }
02170             if (f->len < AST_MIN_DTMF_DURATION) {
02171                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);
02172                ast_set_flag(chan, AST_FLAG_EMULATE_DTMF);
02173                chan->emulate_dtmf_digit = f->subclass;
02174                chan->emulate_dtmf_duration = AST_MIN_DTMF_DURATION - f->len;
02175                ast_frfree(f);
02176                f = &ast_null_frame;
02177             } else {
02178                ast_log(LOG_DTMF, "DTMF end passthrough '%c' on %s\n", f->subclass, chan->name);
02179                chan->dtmf_tv = now;
02180             }
02181             if (chan->audiohooks) {
02182                struct ast_frame *old_frame = f;
02183                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02184                if (old_frame != f)
02185                   ast_frfree(old_frame);
02186             }
02187          }
02188          break;
02189       case AST_FRAME_DTMF_BEGIN:
02190          ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
02191          if ( ast_test_flag(chan, AST_FLAG_DEFER_DTMF | AST_FLAG_END_DTMF_ONLY | AST_FLAG_EMULATE_DTMF) || 
02192              (!ast_tvzero(chan->dtmf_tv) && 
02193                ast_tvdiff_ms(ast_tvnow(), chan->dtmf_tv) < AST_MIN_DTMF_GAP) ) {
02194             ast_log(LOG_DTMF, "DTMF begin ignored '%c' on %s\n", f->subclass, chan->name);
02195             ast_frfree(f);
02196             f = &ast_null_frame;
02197          } else {
02198             ast_set_flag(chan, AST_FLAG_IN_DTMF);
02199             chan->dtmf_tv = ast_tvnow();
02200             ast_log(LOG_DTMF, "DTMF begin passthrough '%c' on %s\n", f->subclass, chan->name);
02201          }
02202          break;
02203       case AST_FRAME_NULL:
02204          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
02205           * is reached , because we want to make sure we pass at least one
02206           * voice frame through before starting the next digit, to ensure a gap
02207           * between DTMF digits. */
02208          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF)) {
02209             struct timeval now = ast_tvnow();
02210             if (!chan->emulate_dtmf_duration) {
02211                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02212                chan->emulate_dtmf_digit = 0;
02213             } else if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
02214                chan->emulate_dtmf_duration = 0;
02215                ast_frfree(f);
02216                f = &chan->dtmff;
02217                f->frametype = AST_FRAME_DTMF_END;
02218                f->subclass = chan->emulate_dtmf_digit;
02219                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02220                chan->dtmf_tv = now;
02221                ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02222                chan->emulate_dtmf_digit = 0;
02223                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
02224             }
02225          }
02226          break;
02227       case AST_FRAME_VOICE:
02228          /* The EMULATE_DTMF flag must be cleared here as opposed to when the duration
02229           * is reached , because we want to make sure we pass at least one
02230           * voice frame through before starting the next digit, to ensure a gap
02231           * between DTMF digits. */
02232          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !chan->emulate_dtmf_duration) {
02233             ast_clear_flag(chan, AST_FLAG_EMULATE_DTMF);
02234             chan->emulate_dtmf_digit = 0;
02235          }
02236 
02237          if (dropaudio || ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02238             if (dropaudio)
02239                ast_read_generator_actions(chan, f);
02240             ast_frfree(f);
02241             f = &ast_null_frame;
02242          }
02243 
02244          if (ast_test_flag(chan, AST_FLAG_EMULATE_DTMF) && !ast_test_flag(chan, AST_FLAG_IN_DTMF)) {
02245             struct timeval now = ast_tvnow();
02246             if (ast_tvdiff_ms(now, chan->dtmf_tv) >= chan->emulate_dtmf_duration) {
02247                chan->emulate_dtmf_duration = 0;
02248                ast_frfree(f);
02249                f = &chan->dtmff;
02250                f->frametype = AST_FRAME_DTMF_END;
02251                f->subclass = chan->emulate_dtmf_digit;
02252                f->len = ast_tvdiff_ms(now, chan->dtmf_tv);
02253                chan->dtmf_tv = now;
02254                if (chan->audiohooks) {
02255                   struct ast_frame *old_frame = f;
02256                   f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02257                   if (old_frame != f)
02258                      ast_frfree(old_frame);
02259                }
02260                ast_log(LOG_DTMF, "DTMF end emulation of '%c' queued on %s\n", f->subclass, chan->name);
02261             } else {
02262                /* Drop voice frames while we're still in the middle of the digit */
02263                ast_frfree(f);
02264                f = &ast_null_frame;
02265             }
02266          } else if ((f->frametype == AST_FRAME_VOICE) && !(f->subclass & chan->nativeformats)) {
02267             /* This frame can't be from the current native formats -- drop it on the
02268                floor */
02269             ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
02270                chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
02271             ast_frfree(f);
02272             f = &ast_null_frame;
02273          } else if ((f->frametype == AST_FRAME_VOICE)) {
02274             if (chan->audiohooks) {
02275                struct ast_frame *old_frame = f;
02276                f = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_READ, f);
02277                if (old_frame != f)
02278                   ast_frfree(old_frame);
02279             }
02280             if (chan->monitor && chan->monitor->read_stream ) {
02281                /* XXX what does this do ? */
02282 #ifndef MONITOR_CONSTANT_DELAY
02283                int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
02284                if (jump >= 0) {
02285                   jump = chan->outsmpl - chan->insmpl;
02286                   if (ast_seekstream(chan->monitor->read_stream, jump, SEEK_FORCECUR) == -1)
02287                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
02288                   chan->insmpl += jump + f->samples;
02289                } else
02290                   chan->insmpl+= f->samples;
02291 #else
02292                int jump = chan->outsmpl - chan->insmpl;
02293                if (jump - MONITOR_DELAY >= 0) {
02294                   if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
02295                      ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
02296                   chan->insmpl += jump;
02297                } else
02298                   chan->insmpl += f->samples;
02299 #endif
02300                if (chan->monitor->state == AST_MONITOR_RUNNING) {
02301                   if (ast_writestream(chan->monitor->read_stream, f) < 0)
02302                      ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
02303                }
02304             }
02305 
02306             if (chan->readtrans && (f = ast_translate(chan->readtrans, f, 1)) == NULL)
02307                f = &ast_null_frame;
02308 
02309             /* Run generator sitting on the line if timing device not available
02310             * and synchronous generation of outgoing frames is necessary       */
02311             ast_read_generator_actions(chan, f);
02312          }
02313       default:
02314          /* Just pass it on! */
02315          break;
02316       }
02317    } else {
02318       /* Make sure we always return NULL in the future */
02319       chan->_softhangup |= AST_SOFTHANGUP_DEV;
02320       if (chan->generator)
02321          ast_deactivate_generator(chan);
02322       /* End the CDR if appropriate */
02323       if (chan->cdr)
02324          ast_cdr_end(chan->cdr);
02325    }
02326 
02327    /* High bit prints debugging */
02328    if (chan->fin & DEBUGCHAN_FLAG)
02329       ast_frame_dump(chan->name, f, "<<");
02330    chan->fin = FRAMECOUNT_INC(chan->fin);
02331 
02332 done:
02333    ast_channel_unlock(chan);
02334    return f;
02335 }
02336 
02337 int ast_internal_timing_enabled(struct ast_channel *chan)
02338 {
02339    int ret = ast_opt_internal_timing && chan->timingfd > -1;
02340    if (option_debug > 4)
02341       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);
02342    return ret;
02343 }
02344 
02345 struct ast_frame *ast_read(struct ast_channel *chan)
02346 {
02347    return __ast_read(chan, 0);
02348 }
02349 
02350 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
02351 {
02352    return __ast_read(chan, 1);
02353 }
02354 
02355 int ast_indicate(struct ast_channel *chan, int condition)
02356 {
02357    return ast_indicate_data(chan, condition, NULL, 0);
02358 }
02359 
02360 int ast_indicate_data(struct ast_channel *chan, int condition, const void *data, size_t datalen)
02361 {
02362    int res = -1;
02363 
02364    ast_channel_lock(chan);
02365    /* Stop if we're a zombie or need a soft hangup */
02366    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
02367       ast_channel_unlock(chan);
02368       return -1;
02369    }
02370    if (chan->tech->indicate)
02371       res = chan->tech->indicate(chan, condition, data, datalen);
02372    ast_channel_unlock(chan);
02373    if (!chan->tech->indicate || res) {
02374       /*
02375        * Device does not support (that) indication, lets fake
02376        * it by doing our own tone generation. (PM2002)
02377        */
02378       if (condition < 0)
02379          ast_playtones_stop(chan);
02380       else {
02381          const struct tone_zone_sound *ts = NULL;
02382          switch (condition) {
02383          case AST_CONTROL_RINGING:
02384             ts = ast_get_indication_tone(chan->zone, "ring");
02385             break;
02386          case AST_CONTROL_BUSY:
02387             ts = ast_get_indication_tone(chan->zone, "busy");
02388             break;
02389          case AST_CONTROL_CONGESTION:
02390             ts = ast_get_indication_tone(chan->zone, "congestion");
02391             break;
02392          }
02393          if (ts && ts->data[0]) {
02394             if (option_debug)
02395                ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
02396             ast_playtones_start(chan,0,ts->data, 1);
02397             res = 0;
02398             chan->visible_indication = condition;
02399          } else if (condition == AST_CONTROL_PROGRESS) {
02400             /* ast_playtones_stop(chan); */
02401          } else if (condition == AST_CONTROL_PROCEEDING) {
02402             /* Do nothing, really */
02403          } else if (condition == AST_CONTROL_HOLD) {
02404             /* Do nothing.... */
02405          } else if (condition == AST_CONTROL_UNHOLD) {
02406             /* Do nothing.... */
02407          } else if (condition == AST_CONTROL_VIDUPDATE) {
02408             /* Do nothing.... */
02409          } else if (condition == AST_CONTROL_SRCUPDATE) {
02410             /* Do nothing... */
02411          } else {
02412             /* not handled */
02413             ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
02414             res = -1;
02415          }
02416       }
02417    } else
02418       chan->visible_indication = condition;
02419 
02420    return res;
02421 }
02422 
02423 int ast_recvchar(struct ast_channel *chan, int timeout)
02424 {
02425    int c;
02426    char *buf = ast_recvtext(chan, timeout);
02427    if (buf == NULL)
02428       return -1;  /* error or timeout */
02429    c = *(unsigned char *)buf;
02430    free(buf);
02431    return c;
02432 }
02433 
02434 char *ast_recvtext(struct ast_channel *chan, int timeout)
02435 {
02436    int res, done = 0;
02437    char *buf = NULL;
02438    
02439    while (!done) {
02440       struct ast_frame *f;
02441       if (ast_check_hangup(chan))
02442          break;
02443       res = ast_waitfor(chan, timeout);
02444       if (res <= 0) /* timeout or error */
02445          break;
02446       timeout = res; /* update timeout */
02447       f = ast_read(chan);
02448       if (f == NULL)
02449          break; /* no frame */
02450       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
02451          done = 1;   /* force a break */
02452       else if (f->frametype == AST_FRAME_TEXT) {      /* what we want */
02453          buf = ast_strndup((char *) f->data, f->datalen);   /* dup and break */
02454          done = 1;
02455       }
02456       ast_frfree(f);
02457    }
02458    return buf;
02459 }
02460 
02461 int ast_sendtext(struct ast_channel *chan, const char *text)
02462 {
02463    int res = 0;
02464    /* Stop if we're a zombie or need a soft hangup */
02465    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
02466       return -1;
02467    CHECK_BLOCKING(chan);
02468    if (chan->tech->send_text)
02469       res = chan->tech->send_text(chan, text);
02470    ast_clear_flag(chan, AST_FLAG_BLOCKING);
02471    return res;
02472 }
02473 
02474 int ast_senddigit_begin(struct ast_channel *chan, char digit)
02475 {
02476    /* Device does not support DTMF tones, lets fake
02477     * it by doing our own generation. */
02478    static const char* dtmf_tones[] = {
02479       "941+1336", /* 0 */
02480       "697+1209", /* 1 */
02481       "697+1336", /* 2 */
02482       "697+1477", /* 3 */
02483       "770+1209", /* 4 */
02484       "770+1336", /* 5 */
02485       "770+1477", /* 6 */
02486       "852+1209", /* 7 */
02487       "852+1336", /* 8 */
02488       "852+1477", /* 9 */
02489       "697+1633", /* A */
02490       "770+1633", /* B */
02491       "852+1633", /* C */
02492       "941+1633", /* D */
02493       "941+1209", /* * */
02494       "941+1477"  /* # */
02495    };
02496 
02497    if (!chan->tech->send_digit_begin)
02498       return 0;
02499 
02500    if (!chan->tech->send_digit_begin(chan, digit))
02501       return 0;
02502 
02503    if (digit >= '0' && digit <='9')
02504       ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
02505    else if (digit >= 'A' && digit <= 'D')
02506       ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
02507    else if (digit == '*')
02508       ast_playtones_start(chan, 0, dtmf_tones[14], 0);
02509    else if (digit == '#')
02510       ast_playtones_start(chan, 0, dtmf_tones[15], 0);
02511    else {
02512       /* not handled */
02513       if (option_debug)
02514          ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
02515    }
02516 
02517    return 0;
02518 }
02519 
02520 int ast_senddigit_end(struct ast_channel *chan, char digit, unsigned int duration)
02521 {
02522    int res = -1;
02523 
02524    if (chan->tech->send_digit_end)
02525       res = chan->tech->send_digit_end(chan, digit, duration);
02526 
02527    if (res && chan->generator)
02528       ast_playtones_stop(chan);
02529    
02530    return 0;
02531 }
02532 
02533 int ast_senddigit(struct ast_channel *chan, char digit)
02534 {
02535    if (chan->tech->send_digit_begin) {
02536       ast_senddigit_begin(chan, digit);
02537       ast_safe_sleep(chan, AST_DEFAULT_EMULATE_DTMF_DURATION);
02538    }
02539    
02540    return ast_senddigit_end(chan, digit, AST_DEFAULT_EMULATE_DTMF_DURATION);
02541 }
02542 
02543 int ast_prod(struct ast_channel *chan)
02544 {
02545    struct ast_frame a = { AST_FRAME_VOICE };
02546    char nothing[128];
02547 
02548    /* Send an empty audio frame to get things moving */
02549    if (chan->_state != AST_STATE_UP) {
02550       if (option_debug)
02551          ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
02552       a.subclass = chan->rawwriteformat;
02553       a.data = nothing + AST_FRIENDLY_OFFSET;
02554       a.src = "ast_prod";
02555       if (ast_write(chan, &a))
02556          ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
02557    }
02558    return 0;
02559 }
02560 
02561 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
02562 {
02563    int res;
02564    if (!chan->tech->write_video)
02565       return 0;
02566    res = ast_write(chan, fr);
02567    if (!res)
02568       res = 1;
02569    return res;
02570 }
02571 
02572 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
02573 {
02574    int res = -1;
02575    int count = 0;
02576    struct ast_frame *f = NULL, *f2 = NULL;
02577 
02578    /*Deadlock avoidance*/
02579    while(ast_channel_trylock(chan)) {
02580       /*cannot goto done since the channel is not locked*/
02581       if(count++ > 10) {
02582          if(option_debug)
02583             ast_log(LOG_DEBUG, "Deadlock avoided for write to channel '%s'\n", chan->name);
02584          return 0;
02585       }
02586       usleep(1);
02587    }
02588    /* Stop if we're a zombie or need a soft hangup */
02589    if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))
02590       goto done;
02591 
02592    /* Handle any pending masquerades */
02593    if (chan->masq && ast_do_masquerade(chan)) {
02594       ast_log(LOG_WARNING, "Failed to perform masquerade\n");
02595       goto done;
02596    }
02597    if (chan->masqr) {
02598       res = 0; /* XXX explain, why 0 ? */
02599       goto done;
02600    }
02601    if (chan->generatordata) {
02602       if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
02603          ast_deactivate_generator(chan);
02604       else {
02605          if (fr->frametype == AST_FRAME_DTMF_END) {
02606             /* There is a generator running while we're in the middle of a digit.
02607              * It's probably inband DTMF, so go ahead and pass it so it can
02608              * stop the generator */
02609             ast_clear_flag(chan, AST_FLAG_BLOCKING);
02610             ast_channel_unlock(chan);
02611             res = ast_senddigit_end(chan, fr->subclass, fr->len);
02612             ast_channel_lock(chan);
02613             CHECK_BLOCKING(chan);
02614          } else if (fr->frametype == AST_FRAME_CONTROL && fr->subclass == AST_CONTROL_UNHOLD) {
02615             /* This is a side case where Echo is basically being called and the person put themselves on hold and took themselves off hold */
02616             res = (chan->tech->indicate == NULL) ? 0 :
02617                chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
02618          }
02619          res = 0; /* XXX explain, why 0 ? */
02620          goto done;
02621       }
02622    }
02623    /* High bit prints debugging */
02624    if (chan->fout & DEBUGCHAN_FLAG)
02625       ast_frame_dump(chan->name, fr, ">>");
02626    CHECK_BLOCKING(chan);
02627    switch(fr->frametype) {
02628    case AST_FRAME_CONTROL:
02629       res = (chan->tech->indicate == NULL) ? 0 :
02630          chan->tech->indicate(chan, fr->subclass, fr->data, fr->datalen);
02631       break;
02632    case AST_FRAME_DTMF_BEGIN:
02633       if (chan->audiohooks) {
02634          struct ast_frame *old_frame = fr;
02635          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
02636          if (old_frame != fr)
02637             f = fr;
02638       }
02639       ast_clear_flag(chan, AST_FLAG_BLOCKING);
02640       ast_channel_unlock(chan);
02641       res = ast_senddigit_begin(chan, fr->subclass);
02642       ast_channel_lock(chan);
02643       CHECK_BLOCKING(chan);
02644       break;
02645    case AST_FRAME_DTMF_END:
02646       if (chan->audiohooks) {
02647          struct ast_frame *old_frame = fr;
02648          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
02649          if (old_frame != fr)
02650             f = fr;
02651       }
02652       ast_clear_flag(chan, AST_FLAG_BLOCKING);
02653       ast_channel_unlock(chan);
02654       res = ast_senddigit_end(chan, fr->subclass, fr->len);
02655       ast_channel_lock(chan);
02656       CHECK_BLOCKING(chan);
02657       break;
02658    case AST_FRAME_TEXT:
02659       res = (chan->tech->send_text == NULL) ? 0 :
02660          chan->tech->send_text(chan, (char *) fr->data);
02661       break;
02662    case AST_FRAME_HTML:
02663       res = (chan->tech->send_html == NULL) ? 0 :
02664          chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
02665       break;
02666    case AST_FRAME_VIDEO:
02667       /* XXX Handle translation of video codecs one day XXX */
02668       res = (chan->tech->write_video == NULL) ? 0 :
02669          chan->tech->write_video(chan, fr);
02670       break;
02671    case AST_FRAME_MODEM:
02672       res = (chan->tech->write == NULL) ? 0 :
02673          chan->tech->write(chan, fr);
02674       break;
02675    case AST_FRAME_VOICE:
02676       if (chan->tech->write == NULL)
02677          break;   /*! \todo XXX should return 0 maybe ? */
02678 
02679       if (chan->audiohooks) {
02680          struct ast_frame *old_frame = fr;
02681          fr = ast_audiohook_write_list(chan, chan->audiohooks, AST_AUDIOHOOK_DIRECTION_WRITE, fr);
02682          if (old_frame != fr)
02683             f2 = fr;
02684       }
02685       
02686       /* If the frame is in the raw write format, then it's easy... just use the frame - otherwise we will have to translate */
02687       if (fr->subclass == chan->rawwriteformat)
02688          f = fr;
02689       else
02690          f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
02691 
02692       /* If we have no frame of audio, then we have to bail out */
02693       if (!f) {
02694          res = 0;
02695          break;
02696       }
02697 
02698       /* If Monitor is running on this channel, then we have to write frames out there too */
02699       if (chan->monitor && chan->monitor->write_stream) {
02700          /* XXX must explain this code */
02701 #ifndef MONITOR_CONSTANT_DELAY
02702          int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
02703          if (jump >= 0) {
02704             jump = chan->insmpl - chan->outsmpl;
02705             if (ast_seekstream(chan->monitor->write_stream, jump, SEEK_FORCECUR) == -1)
02706                ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
02707             chan->outsmpl += jump + f->samples;
02708          } else
02709             chan->outsmpl += f->samples;
02710 #else
02711          int jump = chan->insmpl - chan->outsmpl;
02712          if (jump - MONITOR_DELAY >= 0) {
02713             if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
02714                ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
02715             chan->outsmpl += jump;
02716          } else
02717             chan->outsmpl += f->samples;
02718 #endif
02719          if (chan->monitor->state == AST_MONITOR_RUNNING) {
02720             if (ast_writestream(chan->monitor->write_stream, f) < 0)
02721                ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
02722          }
02723       }
02724 
02725       if (f) 
02726          res = chan->tech->write(chan,f);
02727       else
02728          res = 0;
02729       break;
02730    case AST_FRAME_NULL:
02731    case AST_FRAME_IAX:
02732       /* Ignore these */
02733       res = 0;
02734       break;
02735    default:
02736       /* At this point, fr is the incoming frame and f is NULL.  Channels do
02737        * not expect to get NULL as a frame pointer and will segfault.  Hence,
02738        * we output the original frame passed in. */
02739       res = chan->tech->write(chan, fr);
02740       break;
02741    }
02742 
02743    if (f && f != fr)
02744       ast_frfree(f);
02745    if (f2)
02746       ast_frfree(f2);
02747    ast_clear_flag(chan, AST_FLAG_BLOCKING);
02748    /* Consider a write failure to force a soft hangup */
02749    if (res < 0)
02750       chan->_softhangup |= AST_SOFTHANGUP_DEV;
02751    else {
02752       chan->fout = FRAMECOUNT_INC(chan->fout);
02753    }
02754 done:
02755    ast_channel_unlock(chan);
02756    return res;
02757 }
02758 
02759 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
02760             struct ast_trans_pvt **trans, const int direction)
02761 {
02762    int native;
02763    int res;
02764    
02765    /* Make sure we only consider audio */
02766    fmt &= AST_FORMAT_AUDIO_MASK;
02767    
02768    native = chan->nativeformats;
02769    /* Find a translation path from the native format to one of the desired formats */
02770    if (!direction)
02771       /* reading */
02772       res = ast_translator_best_choice(&fmt, &native);
02773    else
02774       /* writing */
02775       res = ast_translator_best_choice(&native, &fmt);
02776 
02777    if (res < 0) {
02778       ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
02779          ast_getformatname(native), ast_getformatname(fmt));
02780       return -1;
02781    }
02782    
02783    /* Now we have a good choice for both. */
02784    ast_channel_lock(chan);
02785 
02786    if ((*rawformat == native) && (*format == fmt) && ((*rawformat == *format) || (*trans))) {
02787       /* the channel is already in these formats, so nothing to do */
02788       ast_channel_unlock(chan);
02789       return 0;
02790    }
02791 
02792    *rawformat = native;
02793    /* User perspective is fmt */
02794    *format = fmt;
02795    /* Free any read translation we have right now */
02796    if (*trans)
02797       ast_translator_free_path(*trans);
02798    /* Build a translation path from the raw format to the desired format */
02799    if (!direction)
02800       /* reading */
02801       *trans = ast_translator_build_path(*format, *rawformat);
02802    else
02803       /* writing */
02804       *trans = ast_translator_build_path(*rawformat, *format);
02805    ast_channel_unlock(chan);
02806    if (option_debug)
02807       ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
02808          direction ? "write" : "read", ast_getformatname(fmt));
02809    return 0;
02810 }
02811 
02812 int ast_set_read_format(struct ast_channel *chan, int fmt)
02813 {
02814    return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
02815            &chan->readtrans, 0);
02816 }
02817 
02818 int ast_set_write_format(struct ast_channel *chan, int fmt)
02819 {
02820    return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
02821            &chan->writetrans, 1);
02822 }
02823 
02824 char *ast_channel_reason2str(int reason)
02825 {
02826    switch (reason) /* the following appear to be the only ones actually returned by request_and_dial */
02827    {
02828    case 0:
02829       return "Call Failure (not BUSY, and not NO_ANSWER, maybe Circuit busy or down?)";
02830    case AST_CONTROL_HANGUP:
02831       return "Hangup";
02832    case AST_CONTROL_RING:
02833       return "Local Ring";
02834    case AST_CONTROL_RINGING:
02835       return "Remote end Ringing";
02836    case AST_CONTROL_ANSWER:
02837       return "Remote end has Answered";
02838    case AST_CONTROL_BUSY:
02839       return "Remote end is Busy";
02840    case AST_CONTROL_CONGESTION:
02841       return "Congestion (circuits busy)";
02842    default:
02843       return "Unknown Reason!!";
02844    }
02845 }
02846 
02847 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)
02848 {
02849    int dummy_outstate;
02850    int cause = 0;
02851    struct ast_channel *chan;
02852    int res = 0;
02853    int last_subclass = 0;
02854    
02855    if (outstate)
02856       *outstate = 0;
02857    else
02858       outstate = &dummy_outstate;   /* make outstate always a valid pointer */
02859 
02860    chan = ast_request(type, format, data, &cause);
02861    if (!chan) {
02862       ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
02863       /* compute error and return */
02864       if (cause == AST_CAUSE_BUSY)
02865          *outstate = AST_CONTROL_BUSY;
02866       else if (cause == AST_CAUSE_CONGESTION)
02867          *outstate = AST_CONTROL_CONGESTION;
02868       return NULL;
02869    }
02870 
02871    if (oh) {
02872       if (oh->vars)  
02873          ast_set_variables(chan, oh->vars);
02874       /* XXX why is this necessary, for the parent_channel perhaps ? */
02875       if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
02876          ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
02877       if (oh->parent_channel)
02878          ast_channel_inherit_variables(oh->parent_channel, chan);
02879       if (oh->account)
02880          ast_cdr_setaccount(chan, oh->account); 
02881    }
02882    ast_set_callerid(chan, cid_num, cid_name, cid_num);
02883 
02884    
02885 
02886    if (!chan->cdr) { /* up till now, this insertion hasn't been done. Therefore,
02887             to keep from throwing off the basic order of the universe,
02888             we will try to keep this cdr from getting posted. */
02889       chan->cdr = ast_cdr_alloc();
02890       ast_cdr_init(chan->cdr, chan);
02891       ast_cdr_start(chan->cdr);
02892    }
02893    if (ast_call(chan, data, 0)) {   /* ast_call failed... */
02894       ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
02895    } else {
02896       res = 1; /* mark success in case chan->_state is already AST_STATE_UP */
02897       while (timeout && chan->_state != AST_STATE_UP) {
02898          struct ast_frame *f;
02899          res = ast_waitfor(chan, timeout);
02900          if (res <= 0) /* error, timeout, or done */
02901             break;
02902          if (timeout > -1)
02903             timeout = res;
02904          f = ast_read(chan);
02905          if (!f) {
02906             *outstate = AST_CONTROL_HANGUP;
02907             res = 0;
02908             break;
02909          }
02910          if (f->frametype == AST_FRAME_CONTROL) {
02911             switch (f->subclass) {
02912             case AST_CONTROL_RINGING:  /* record but keep going */
02913                *outstate = f->subclass;
02914                break;
02915 
02916             case AST_CONTROL_BUSY:
02917             case AST_CONTROL_CONGESTION:
02918             case AST_CONTROL_ANSWER:
02919                *outstate = f->subclass;
02920                timeout = 0;      /* trick to force exit from the while() */
02921                break;
02922 
02923             /* Ignore these */
02924             case AST_CONTROL_PROGRESS:
02925             case AST_CONTROL_PROCEEDING:
02926             case AST_CONTROL_HOLD:
02927             case AST_CONTROL_UNHOLD:
02928             case AST_CONTROL_VIDUPDATE:
02929             case AST_CONTROL_SRCUPDATE:
02930             case -1:       /* Ignore -- just stopping indications */
02931                break;
02932 
02933             default:
02934                ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
02935             }
02936             last_subclass = f->subclass;
02937          }
02938          ast_frfree(f);
02939       }
02940    }
02941 
02942    /* Final fixups */
02943    if (oh) {
02944       if (!ast_strlen_zero(oh->context))
02945          ast_copy_string(chan->context, oh->context, sizeof(chan->context));
02946       if (!ast_strlen_zero(oh->exten))
02947          ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
02948       if (oh->priority) 
02949          chan->priority = oh->priority;
02950    }
02951    if (chan->_state == AST_STATE_UP)
02952       *outstate = AST_CONTROL_ANSWER;
02953 
02954    if (res <= 0) {
02955       if ( AST_CONTROL_RINGING == last_subclass ) 
02956          chan->hangupcause = AST_CAUSE_NO_ANSWER;
02957       if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
02958          ast_cdr_init(chan->cdr, chan);
02959       if (chan->cdr) {
02960          char tmp[256];
02961          snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
02962          ast_cdr_setapp(chan->cdr,"Dial",tmp);
02963          ast_cdr_update(chan);
02964          ast_cdr_start(chan->cdr);
02965          ast_cdr_end(chan->cdr);
02966          /* If the cause wasn't handled properly */
02967          if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
02968             ast_cdr_failed(chan->cdr);
02969       }
02970       ast_hangup(chan);
02971       chan = NULL;
02972    }
02973    return chan;
02974 }
02975 
02976 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
02977 {
02978    return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
02979 }
02980 
02981 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
02982 {
02983    struct chanlist *chan;
02984    struct ast_channel *c;
02985    int capabilities;
02986    int fmt;
02987    int res;
02988    int foo;
02989    int videoformat = format & AST_FORMAT_VIDEO_MASK;
02990 
02991    if (!cause)
02992       cause = &foo;
02993    *cause = AST_CAUSE_NOTDEFINED;
02994 
02995    if (AST_LIST_LOCK(&channels)) {
02996       ast_log(LOG_WARNING, "Unable to lock channel list\n");
02997       return NULL;
02998    }
02999 
03000    AST_LIST_TRAVERSE(&backends, chan, list) {
03001       if (strcasecmp(type, chan->tech->type))
03002          continue;
03003 
03004       capabilities = chan->tech->capabilities;
03005       fmt = format & AST_FORMAT_AUDIO_MASK;
03006       res = ast_translator_best_choice(&fmt, &capabilities);
03007       if (res < 0) {
03008          ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
03009          *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
03010          AST_LIST_UNLOCK(&channels);
03011          return NULL;
03012       }
03013       AST_LIST_UNLOCK(&channels);
03014       if (!chan->tech->requester)
03015          return NULL;
03016       
03017       if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
03018          return NULL;
03019 
03020       /* no need to generate a Newchannel event here; it is done in the channel_alloc call */
03021       return c;
03022    }
03023 
03024    ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
03025    *cause = AST_CAUSE_NOSUCHDRIVER;
03026    AST_LIST_UNLOCK(&channels);
03027 
03028    return NULL;
03029 }
03030 
03031 int ast_call(struct ast_channel *chan, char *addr, int timeout)
03032 {
03033    /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
03034       If the remote end does not answer within the timeout, then do NOT hang up, but
03035       return anyway.  */
03036    int res = -1;
03037    /* Stop if we're a zombie or need a soft hangup */
03038    ast_channel_lock(chan);
03039    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
03040       if (chan->tech->call)
03041          res = chan->tech->call(chan, addr, timeout);
03042       ast_set_flag(chan, AST_FLAG_OUTGOING);
03043    }
03044    ast_channel_unlock(chan);
03045    return res;
03046 }
03047 
03048 /*!
03049   \brief Transfer a call to dest, if the channel supports transfer
03050 
03051   Called by:
03052     \arg app_transfer
03053     \arg the manager interface
03054 */
03055 int ast_transfer(struct ast_channel *chan, char *dest)
03056 {
03057    int res = -1;
03058 
03059    /* Stop if we're a zombie or need a soft hangup */
03060    ast_channel_lock(chan);
03061    if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
03062       if (chan->tech->transfer) {
03063          res = chan->tech->transfer(chan, dest);
03064          if (!res)
03065             res = 1;
03066       } else
03067          res = 0;
03068    }
03069    ast_channel_unlock(chan);
03070    return res;
03071 }
03072 
03073 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
03074 {
03075    return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
03076 }
03077 
03078 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
03079 {
03080    int pos = 0;   /* index in the buffer where we accumulate digits */
03081    int to = ftimeout;
03082 
03083    /* Stop if we're a zombie or need a soft hangup */
03084    if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
03085       return -1;
03086    if (!len)
03087       return -1;
03088    for (;;) {
03089       int d;
03090       if (c->stream) {
03091          d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
03092          ast_stopstream(c);
03093          usleep(1000);
03094          if (!d)
03095             d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
03096       } else {
03097          d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
03098       }
03099       if (d < 0)
03100          return -1;
03101       if (d == 0) {
03102          s[pos]='\0';
03103          return 1;
03104       }
03105       if (d == 1) {
03106          s[pos]='\0';
03107          return 2;
03108       }
03109       if (!strchr(enders, d))
03110          s[pos++] = d;
03111       if (strchr(enders, d) || (pos >= len)) {
03112          s[pos]='\0';
03113          return 0;
03114       }
03115       to = timeout;
03116    }
03117    /* Never reached */
03118    return 0;
03119 }
03120 
03121 int ast_channel_supports_html(struct ast_channel *chan)
03122 {
03123    return (chan->tech->send_html) ? 1 : 0;
03124 }
03125 
03126 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
03127 {
03128    if (chan->tech->send_html)
03129       return chan->tech->send_html(chan, subclass, data, datalen);
03130    return -1;
03131 }
03132 
03133 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
03134 {
03135    return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
03136 }
03137 
03138 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
03139 {
03140    int src;
03141    int dst;
03142 
03143    if (chan->readformat == peer->writeformat && chan->writeformat == peer->readformat) {
03144       /* Already compatible!  Moving on ... */
03145       return 0;
03146    }
03147 
03148    /* Set up translation from the chan to the peer */
03149    src = chan->nativeformats;
03150    dst = peer->nativeformats;
03151    if (ast_translator_best_choice(&dst, &src) < 0) {
03152       ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
03153       return -1;
03154    }
03155 
03156    /* if the best path is not 'pass through', then
03157       transcoding is needed; if desired, force transcode path
03158       to use SLINEAR between channels, but only if there is
03159       no direct conversion available */
03160    if ((src != dst) && ast_opt_transcode_via_slin &&
03161        (ast_translate_path_steps(dst, src) != 1))
03162       dst = AST_FORMAT_SLINEAR;
03163    if (ast_set_read_format(chan, dst) < 0) {
03164       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
03165       return -1;
03166    }
03167    if (ast_set_write_format(peer, dst) < 0) {
03168       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
03169       return -1;
03170    }
03171 
03172    /* Set up translation from the peer to the chan */
03173    src = peer->nativeformats;
03174    dst = chan->nativeformats;
03175    if (ast_translator_best_choice(&dst, &src) < 0) {
03176       ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
03177       return -1;
03178    }
03179 
03180    /* if the best path is not 'pass through', then
03181       transcoding is needed; if desired, force transcode path
03182       to use SLINEAR between channels, but only if there is
03183       no direct conversion available */
03184    if ((src != dst) && ast_opt_transcode_via_slin &&
03185        (ast_translate_path_steps(dst, src) != 1))
03186       dst = AST_FORMAT_SLINEAR;
03187    if (ast_set_read_format(peer, dst) < 0) {
03188       ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
03189       return -1;
03190    }
03191    if (ast_set_write_format(chan, dst) < 0) {
03192       ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
03193       return -1;
03194    }
03195    return 0;
03196 }
03197 
03198 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
03199 {
03200    int res = -1;
03201    struct ast_channel *final_orig, *final_clone, *base;
03202 
03203 retrymasq:
03204    final_orig = original;
03205    final_clone = clone;
03206 
03207    ast_channel_lock(original);
03208    while (ast_channel_trylock(clone)) {
03209       ast_channel_unlock(original);
03210       usleep(1);
03211       ast_channel_lock(original);
03212    }
03213 
03214    /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
03215       and if so, we don't really want to masquerade it, but its proxy */
03216    if (original->_bridge && (original->_bridge != ast_bridged_channel(original)) && (original->_bridge->_bridge != original))
03217       final_orig = original->_bridge;
03218 
03219    if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)) && (clone->_bridge->_bridge != clone))
03220       final_clone = clone->_bridge;
03221    
03222    if (final_clone->tech->get_base_channel && (base = final_clone->tech->get_base_channel(final_clone))) {
03223       final_clone = base;
03224    }
03225 
03226    if ((final_orig != original) || (final_clone != clone)) {
03227       /* Lots and lots of deadlock avoidance.  The main one we're competing with
03228        * is ast_write(), which locks channels recursively, when working with a
03229        * proxy channel. */
03230       if (ast_channel_trylock(final_orig)) {
03231          ast_channel_unlock(clone);
03232          ast_channel_unlock(original);
03233          goto retrymasq;
03234       }
03235       if (ast_channel_trylock(final_clone)) {
03236          ast_channel_unlock(final_orig);
03237          ast_channel_unlock(clone);
03238          ast_channel_unlock(original);
03239          goto retrymasq;
03240       }
03241       ast_channel_unlock(clone);
03242       ast_channel_unlock(original);
03243       original = final_orig;
03244       clone = final_clone;
03245    }
03246 
03247    if (original == clone) {
03248       ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
03249       ast_channel_unlock(clone);
03250       ast_channel_unlock(original);
03251       return -1;
03252    }
03253 
03254    if (option_debug)
03255       ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
03256          clone->name, original->name);
03257    if (original->masq) {
03258       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
03259          original->masq->name, original->name);
03260    } else if (clone->masqr) {
03261       ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
03262          clone->name, clone->masqr->name);
03263    } else {
03264       original->masq = clone;
03265       clone->masqr = original;
03266       ast_queue_frame(original, &ast_null_frame);
03267       ast_queue_frame(clone, &ast_null_frame);
03268       if (option_debug)
03269          ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
03270       res = 0;
03271    }
03272 
03273    ast_channel_unlock(clone);
03274    ast_channel_unlock(original);
03275 
03276    return res;
03277 }
03278 
03279 void ast_change_name(struct ast_channel *chan, char *newname)
03280 {
03281    manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
03282    ast_string_field_set(chan, name, newname);
03283 }
03284 
03285 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
03286 {
03287    struct ast_var_t *current, *newvar;
03288    const char *varname;
03289 
03290    AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
03291       int vartype = 0;
03292 
03293       varname = ast_var_full_name(current);
03294       if (!varname)
03295          continue;
03296 
03297       if (varname[0] == '_') {
03298          vartype = 1;
03299          if (varname[1] == '_')
03300             vartype = 2;
03301       }
03302 
03303       switch (vartype) {
03304       case 1:
03305          newvar = ast_var_assign(&varname[1], ast_var_value(current));
03306          if (newvar) {
03307             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
03308             if (option_debug)
03309                ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
03310          }
03311          break;
03312       case 2:
03313          newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
03314          if (newvar) {
03315             AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
03316             if (option_debug)
03317                ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
03318          }
03319          break;
03320       default:
03321          if (option_debug)
03322             ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
03323          break;
03324       }
03325    }
03326 }
03327 
03328 /*!
03329   \brief Clone channel variables from 'clone' channel into 'original' channel
03330 
03331   All variables except those related to app_groupcount are cloned.
03332   Variables are actually _removed_ from 'clone' channel, presumably
03333   because it will subsequently be destroyed.
03334 
03335   \note Assumes locks will be in place on both channels when called.
03336 */
03337 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
03338 {
03339    struct ast_var_t *current, *newvar;
03340    /* Append variables from clone channel into original channel */
03341    /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
03342    if (AST_LIST_FIRST(&clone->varshead))
03343       AST_LIST_APPEND_LIST(&original->varshead, &clone->varshead, entries);
03344 
03345    /* then, dup the varshead list into the clone */
03346    
03347    AST_LIST_TRAVERSE(&original->varshead, current, entries) {
03348       newvar = ast_var_assign(current->name, current->value);
03349       if (newvar)
03350          AST_LIST_INSERT_TAIL(&clone->varshead, newvar, entries);
03351    }
03352 }
03353 
03354 /*!
03355   \brief Masquerade a channel
03356 
03357   \note Assumes channel will be locked when called
03358 */
03359 int ast_do_masquerade(struct ast_channel *original)
03360 {
03361    int x,i;
03362    int res=0;
03363    int origstate;
03364    struct ast_frame *cur;
03365    const struct ast_channel_tech *t;
03366    void *t_pvt;
03367    struct ast_callerid tmpcid;
03368    struct ast_channel *clone = original->masq;
03369    struct ast_cdr *cdr;
03370    int rformat = original->readformat;
03371    int wformat = original->writeformat;
03372    char newn[100];
03373    char orig[100];
03374    char masqn[100];
03375    char zombn[100];
03376 
03377    if (option_debug > 3)
03378       ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
03379          clone->name, clone->_state, original->name, original->_state);
03380 
03381    /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
03382       the clone channel into the original channel.  Start by killing off the original
03383       channel's backend.   I'm not sure we're going to keep this function, because
03384       while the features are nice, the cost is very high in terms of pure nastiness. XXX */
03385 
03386    /* We need the clone's lock, too */
03387    ast_channel_lock(clone);
03388 
03389    if (option_debug > 1)
03390       ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
03391 
03392    /* Having remembered the original read/write formats, we turn off any translation on either
03393       one */
03394    free_translation(clone);
03395    free_translation(original);
03396 
03397 
03398    /* Unlink the masquerade */
03399    original->masq = NULL;
03400    clone->masqr = NULL;
03401    
03402    /* Save the original name */
03403    ast_copy_string(orig, original->name, sizeof(orig));
03404    /* Save the new name */
03405    ast_copy_string(newn, clone->name, sizeof(newn));
03406    /* Create the masq name */
03407    snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
03408       
03409    /* Copy the name from the clone channel */
03410    ast_string_field_set(original, name, newn);
03411 
03412    /* Mangle the name of the clone channel */
03413    ast_string_field_set(clone, name, masqn);
03414    
03415    /* Notify any managers of the change, first the masq then the other */
03416    manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
03417    manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
03418 
03419    /* Swap the technologies */   
03420    t = original->tech;
03421    original->tech = clone->tech;
03422    clone->tech = t;
03423 
03424    /* Swap the cdrs */
03425    cdr = original->cdr;
03426    original->cdr = clone->cdr;
03427    clone->cdr = cdr;
03428 
03429    t_pvt = original->tech_pvt;
03430    original->tech_pvt = clone->tech_pvt;
03431    clone->tech_pvt = t_pvt;
03432 
03433    /* Swap the alertpipes */
03434    for (i = 0; i < 2; i++) {
03435       x = original->alertpipe[i];
03436       original->alertpipe[i] = clone->alertpipe[i];
03437       clone->alertpipe[i] = x;
03438    }
03439 
03440    /* 
03441     * Swap the readq's.  The end result should be this:
03442     *
03443     *  1) All frames should be on the new (original) channel.
03444     *  2) Any frames that were already on the new channel before this
03445     *     masquerade need to be at the end of the readq, after all of the
03446     *     frames on the old (clone) channel.
03447     *  3) The alertpipe needs to get poked for every frame that was already
03448     *     on the new channel, since we are now using the alert pipe from the
03449     *     old (clone) channel.
03450     */
03451    {
03452       AST_LIST_HEAD_NOLOCK(, ast_frame) tmp_readq;
03453       AST_LIST_HEAD_SET_NOLOCK(&tmp_readq, NULL);
03454 
03455       AST_LIST_APPEND_LIST(&tmp_readq, &original->readq, frame_list);
03456       AST_LIST_APPEND_LIST(&original->readq, &clone->readq, frame_list);
03457 
03458       while ((cur = AST_LIST_REMOVE_HEAD(&tmp_readq, frame_list))) {
03459          AST_LIST_INSERT_TAIL(&original->readq, cur, frame_list);
03460          if (original->alertpipe[1] > -1) {
03461             int poke = 0;
03462             write(original->alertpipe[1], &poke, sizeof(poke));
03463          }
03464       }
03465    }
03466 
03467    /* Swap the raw formats */
03468    x = original->rawreadformat;
03469    original->rawreadformat = clone->rawreadformat;
03470    clone->rawreadformat = x;
03471    x = original->rawwriteformat;
03472    original->rawwriteformat = clone->rawwriteformat;
03473    clone->rawwriteformat = x;
03474 
03475    clone->_softhangup = AST_SOFTHANGUP_DEV;
03476 
03477    /* And of course, so does our current state.  Note we need not
03478       call ast_setstate since the event manager doesn't really consider
03479       these separate.  We do this early so that the clone has the proper
03480       state of the original channel. */
03481    origstate = original->_state;
03482    original->_state = clone->_state;
03483    clone->_state = origstate;
03484 
03485    if (clone->tech->fixup){
03486       res = clone->tech->fixup(original, clone);
03487       if (res)
03488          ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
03489    }
03490 
03491    /* Start by disconnecting the original's physical side */
03492    if (clone->tech->hangup)
03493       res = clone->tech->hangup(clone);
03494    if (res) {
03495       ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
03496       ast_channel_unlock(clone);
03497       return -1;
03498    }
03499    
03500    snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
03501    /* Mangle the name of the clone channel */
03502    ast_string_field_set(clone, name, zombn);
03503    manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
03504 
03505    /* Update the type. */
03506    t_pvt = original->monitor;
03507    original->monitor = clone->monitor;
03508    clone->monitor = t_pvt;
03509    
03510    /* Keep the same language.  */
03511    ast_string_field_set(original, language, clone->language);
03512    /* Copy the FD's other than the generator fd */
03513    for (x = 0; x < AST_MAX_FDS; x++) {
03514       if (x != AST_GENERATOR_FD)
03515          original->fds[x] = clone->fds[x];
03516    }
03517 
03518    ast_app_group_update(clone, original);
03519    /* Move data stores over */
03520    if (AST_LIST_FIRST(&clone->datastores)) {
03521       struct ast_datastore *ds;
03522       AST_LIST_APPEND_LIST(&original->datastores, &clone->datastores, entry);
03523       AST_LIST_TRAVERSE(&original->datastores, ds, entry) {
03524          if (ds->info->chan_fixup)
03525             ds->info->chan_fixup(ds->data, clone, original);
03526       }
03527    }
03528 
03529    clone_variables(original, clone);
03530    /* Presense of ADSI capable CPE follows clone */
03531    original->adsicpe = clone->adsicpe;
03532    /* Bridge remains the same */
03533    /* CDR fields remain the same */
03534    /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
03535    /* Application and data remain the same */
03536    /* Clone exception  becomes real one, as with fdno */
03537    ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
03538    original->fdno = clone->fdno;
03539    /* Schedule context remains the same */
03540    /* Stream stuff stays the same */
03541    /* Keep the original state.  The fixup code will need to work with it most likely */
03542 
03543    /* Just swap the whole structures, nevermind the allocations, they'll work themselves
03544       out. */
03545    tmpcid = original->cid;
03546    original->cid = clone->cid;
03547    clone->cid = tmpcid;
03548    
03549    /* Restore original timing file descriptor */
03550    original->fds[AST_TIMING_FD] = original->timingfd;
03551    
03552    /* Our native formats are different now */
03553    original->nativeformats = clone->nativeformats;
03554    
03555    /* Context, extension, priority, app data, jump table,  remain the same */
03556    /* pvt switches.  pbx stays the same, as does next */
03557    
03558    /* Set the write format */
03559    ast_set_write_format(original, wformat);
03560 
03561    /* Set the read format */
03562    ast_set_read_format(original, rformat);
03563 
03564    /* Copy the music class */
03565    ast_string_field_set(original, musicclass, clone->musicclass);
03566 
03567    if (option_debug)
03568       ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
03569 
03570    /* Okay.  Last thing is to let the channel driver know about all this mess, so he
03571       can fix up everything as best as possible */
03572    if (original->tech->fixup) {
03573       res = original->tech->fixup(clone, original);
03574       if (res) {
03575          ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
03576             original->tech->type, original->name);
03577          ast_channel_unlock(clone);
03578          return -1;
03579       }
03580    } else
03581       ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
03582          original->tech->type, original->name);
03583 
03584    /* If an indication is currently playing maintain it on the channel that is taking the place of original */
03585    if (original->visible_indication)
03586       ast_indicate(original, original->visible_indication);
03587    
03588    /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
03589       a zombie so nothing tries to touch it.  If it's already been marked as a
03590       zombie, then free it now (since it already is considered invalid). */
03591    if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
03592       if (option_debug)
03593          ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
03594       ast_channel_unlock(clone);
03595       manager_event(EVENT_FLAG_CALL, "Hangup",
03596          "Channel: %s\r\n"
03597          "Uniqueid: %s\r\n"
03598          "Cause: %d\r\n"
03599          "Cause-txt: %s\r\n",
03600          clone->name,
03601          clone->uniqueid,
03602          clone->hangupcause,
03603          ast_cause2str(clone->hangupcause)
03604          );
03605       ast_channel_free(clone);
03606    } else {
03607       if (option_debug)
03608          ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
03609       ast_set_flag(clone, AST_FLAG_ZOMBIE);
03610       ast_queue_frame(clone, &ast_null_frame);
03611       ast_channel_unlock(clone);
03612    }
03613    
03614    /* Signal any blocker */
03615    if (ast_test_flag(original, AST_FLAG_BLOCKING))
03616       pthread_kill(original->blocker, SIGURG);
03617    if (option_debug)
03618       ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
03619    return 0;
03620 }
03621 
03622 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
03623 {
03624    ast_channel_lock(chan);
03625 
03626    if (callerid) {
03627       if (chan->cid.cid_num)
03628          free(chan->cid.cid_num);
03629       chan->cid.cid_num = ast_strdup(callerid);
03630    }
03631    if (calleridname) {
03632       if (chan->cid.cid_name)
03633          free(chan->cid.cid_name);
03634       chan->cid.cid_name = ast_strdup(calleridname);
03635    }
03636    if (ani) {
03637       if (chan->cid.cid_ani)
03638          free(chan->cid.cid_ani);
03639       chan->cid.cid_ani = ast_strdup(ani);
03640    }
03641    if (chan->cdr)
03642       ast_cdr_setcid(chan->cdr, chan);
03643    manager_event(EVENT_FLAG_CALL, "Newcallerid",
03644             "Channel: %s\r\n"
03645             "CallerID: %s\r\n"
03646             "CallerIDName: %s\r\n"
03647             "Uniqueid: %s\r\n"
03648             "CID-CallingPres: %d (%s)\r\n",
03649             chan->name,
03650             S_OR(chan->cid.cid_num, "<Unknown>"),
03651             S_OR(chan->cid.cid_name, "<Unknown>"),
03652             chan->uniqueid,
03653             chan->cid.cid_pres,
03654             ast_describe_caller_presentation(chan->cid.cid_pres)
03655             );
03656    
03657    ast_channel_unlock(chan);
03658 }
03659 
03660 int ast_setstate(struct ast_channel *chan, enum ast_channel_state state)
03661 {
03662    int oldstate = chan->_state;
03663 
03664    if (oldstate == state)
03665       return 0;
03666 
03667    chan->_state = state;
03668    ast_device_state_changed_literal(chan->name);
03669    /* setstate used to conditionally report Newchannel; this is no more */
03670    manager_event(EVENT_FLAG_CALL,
03671             "Newstate",
03672             "Channel: %s\r\n"
03673             "State: %s\r\n"
03674             "CallerID: %s\r\n"
03675             "CallerIDName: %s\r\n"
03676             "Uniqueid: %s\r\n",
03677             chan->name, ast_state2str(chan->_state),
03678             S_OR(chan->cid.cid_num, "<unknown>"),
03679             S_OR(chan->cid.cid_name, "<unknown>"),
03680             chan->uniqueid);
03681 
03682    return 0;
03683 }
03684 
03685 /*! \brief Find bridged channel */
03686 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
03687 {
03688    struct ast_channel *bridged;
03689    bridged = chan->_bridge;
03690    if (bridged && bridged->tech->bridged_channel)
03691       bridged = bridged->tech->bridged_channel(chan, bridged);
03692    return bridged;
03693 }
03694 
03695 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
03696 {
03697    int min = 0, sec = 0, check;
03698 
03699    check = ast_autoservice_start(peer);
03700    if (check)
03701       return;
03702 
03703    if (remain > 0) {
03704       if (remain / 60 > 1) {
03705          min = remain / 60;
03706          sec = remain % 60;
03707       } else {
03708          sec = remain;
03709       }
03710    }
03711    
03712    if (!strcmp(sound,"timeleft")) { /* Queue support */
03713       ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
03714       if (min) {
03715          ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
03716          ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
03717       }
03718       if (sec) {
03719          ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
03720          ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
03721       }
03722    } else {
03723       ast_stream_and_wait(chan, sound, chan->language, "");
03724    }
03725 
03726    ast_autoservice_stop(peer);
03727 }
03728 
03729 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
03730                    struct ast_bridge_config *config, struct ast_frame **fo,
03731                    struct ast_channel **rc, struct timeval bridge_end)
03732 {
03733    /* Copy voice back and forth between the two channels. */
03734    struct ast_channel *cs[3];
03735    struct ast_frame *f;
03736    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
03737    int o0nativeformats;
03738    int o1nativeformats;
03739    int watch_c0_dtmf;
03740    int watch_c1_dtmf;
03741    void *pvt0, *pvt1;
03742    /* Indicates whether a frame was queued into a jitterbuffer */
03743    int frame_put_in_jb = 0;
03744    int jb_in_use;
03745    int to;
03746    
03747    cs[0] = c0;
03748    cs[1] = c1;
03749    pvt0 = c0->tech_pvt;
03750    pvt1 = c1->tech_pvt;
03751    o0nativeformats = c0->nativeformats;
03752    o1nativeformats = c1->nativeformats;
03753    watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
03754    watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
03755 
03756    /* Check the need of a jitterbuffer for each channel */
03757    jb_in_use = ast_jb_do_usecheck(c0, c1);
03758 
03759    for (;;) {
03760       struct ast_channel *who, *other;
03761 
03762       if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
03763           (o0nativeformats != c0->nativeformats) ||
03764           (o1nativeformats != c1->nativeformats)) {
03765          /* Check for Masquerade, codec changes, etc */
03766          res = AST_BRIDGE_RETRY;
03767          break;
03768       }
03769       if (bridge_end.tv_sec) {
03770          to = ast_tvdiff_ms(bridge_end, ast_tvnow());
03771          if (to <= 0) {
03772             if (config->timelimit)
03773                res = AST_BRIDGE_RETRY;
03774             else
03775                res = AST_BRIDGE_COMPLETE;
03776             break;
03777          }
03778       } else
03779          to = -1;
03780       /* Calculate the appropriate max sleep interval - in general, this is the time,
03781          left to the closest jb delivery moment */
03782       if (jb_in_use)
03783          to = ast_jb_get_when_to_wakeup(c0, c1, to);
03784       who = ast_waitfor_n(cs, 2, &to);
03785       if (!who) {
03786          /* No frame received within the specified timeout - check if we have to deliver now */
03787          if (jb_in_use)
03788             ast_jb_get_and_deliver(c0, c1);
03789          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
03790             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
03791                c0->_softhangup = 0;
03792             if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
03793                c1->_softhangup = 0;
03794             c0->_bridge = c1;
03795             c1->_bridge = c0;
03796          }
03797          continue;
03798       }
03799       f = ast_read(who);
03800       if (!f) {
03801          *fo = NULL;
03802          *rc = who;
03803          if (option_debug)
03804             ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
03805          break;
03806       }
03807 
03808       other = (who == c0) ? c1 : c0; /* the 'other' channel */
03809       /* Try add the frame info the who's bridged channel jitterbuff */
03810       if (jb_in_use)
03811          frame_put_in_jb = !ast_jb_put(other, f);
03812 
03813       if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
03814          int bridge_exit = 0;
03815 
03816          switch (f->subclass) {
03817          case AST_CONTROL_HOLD:
03818          case AST_CONTROL_UNHOLD:
03819          case AST_CONTROL_VIDUPDATE:
03820          case AST_CONTROL_SRCUPDATE:
03821             ast_indicate_data(other, f->subclass, f->data, f->datalen);
03822             break;
03823          default:
03824             *fo = f;
03825             *rc = who;
03826             bridge_exit = 1;
03827             if (option_debug)
03828                ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
03829             break;
03830          }
03831          if (bridge_exit)
03832             break;
03833       }
03834       if ((f->frametype == AST_FRAME_VOICE) ||
03835           (f->frametype == AST_FRAME_DTMF_BEGIN) ||
03836           (f->frametype == AST_FRAME_DTMF) ||
03837           (f->frametype == AST_FRAME_VIDEO) ||
03838           (f->frametype == AST_FRAME_IMAGE) ||
03839           (f->frametype == AST_FRAME_HTML) ||
03840           (f->frametype == AST_FRAME_MODEM) ||
03841           (f->frametype == AST_FRAME_TEXT)) {
03842          /* monitored dtmf causes exit from bridge */
03843          int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
03844 
03845          if (monitored_source && 
03846             (f->frametype == AST_FRAME_DTMF_END || 
03847             f->frametype == AST_FRAME_DTMF_BEGIN)) {
03848             *fo = f;
03849             *rc = who;
03850             if (option_debug)
03851                ast_log(LOG_DEBUG, "Got DTMF %s on channel (%s)\n", 
03852                   f->frametype == AST_FRAME_DTMF_END ? "end" : "begin",
03853                   who->name);
03854             break;
03855          }
03856          /* Write immediately frames, not passed through jb */
03857          if (!frame_put_in_jb)
03858             ast_write(other, f);
03859             
03860          /* Check if we have to deliver now */
03861          if (jb_in_use)
03862             ast_jb_get_and_deliver(c0, c1);
03863       }
03864       /* XXX do we want to pass on also frames not matched above ? */
03865       ast_frfree(f);
03866 
03867       /* Swap who gets priority */
03868       cs[2] = cs[0];
03869       cs[0] = cs[1];
03870       cs[1] = cs[2];
03871    }
03872    return res;
03873 }
03874 
03875 /*! \brief Bridge two channels together */
03876 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
03877                  struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
03878 {
03879    struct ast_channel *who = NULL;
03880    enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
03881    int nativefailed=0;
03882    int firstpass;
03883    int o0nativeformats;
03884    int o1nativeformats;
03885    long time_left_ms=0;
03886    struct timeval nexteventts = { 0, };
03887    char caller_warning = 0;
03888    char callee_warning = 0;
03889 
03890    if (c0->_bridge) {
03891       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
03892          c0->name, c0->_bridge->name);
03893       return -1;
03894    }
03895    if (c1->_bridge) {
03896       ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
03897          c1->name, c1->_bridge->name);
03898       return -1;
03899    }
03900    
03901    /* Stop if we're a zombie or need a soft hangup */
03902    if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
03903        ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
03904       return -1;
03905 
03906    *fo = NULL;
03907    firstpass = config->firstpass;
03908    config->firstpass = 0;
03909 
03910    if (ast_tvzero(config->start_time))
03911       config->start_time = ast_tvnow();
03912    time_left_ms = config->timelimit;
03913 
03914    caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
03915    callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
03916 
03917    if (config->start_sound && firstpass) {
03918       if (caller_warning)
03919          bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
03920       if (callee_warning)
03921          bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
03922    }
03923 
03924    /* Keep track of bridge */
03925    c0->_bridge = c1;
03926    c1->_bridge = c0;
03927 
03928    /* \todo  XXX here should check that cid_num is not NULL */
03929    manager_event(EVENT_FLAG_CALL, "Link",
03930             "Channel1: %s\r\n"
03931             "Channel2: %s\r\n"
03932             "Uniqueid1: %s\r\n"
03933             "Uniqueid2: %s\r\n"
03934             "CallerID1: %s\r\n"
03935             "CallerID2: %s\r\n",
03936             c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
03937 
03938    o0nativeformats = c0->nativeformats;
03939    o1nativeformats = c1->nativeformats;
03940 
03941    if (config->feature_timer) {
03942       nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->feature_timer, 1000));
03943    } else if (config->timelimit) {
03944       nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
03945       if (caller_warning || callee_warning)
03946          nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
03947    }
03948 
03949    if (!c0->tech->send_digit_begin)
03950       ast_set_flag(c1, AST_FLAG_END_DTMF_ONLY);
03951    if (!c1->tech->send_digit_begin)
03952       ast_set_flag(c0, AST_FLAG_END_DTMF_ONLY);
03953 
03954    /* Before we enter in and bridge these two together tell them both the source of audio has changed */
03955    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
03956    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
03957 
03958    for (/* ever */;;) {
03959       struct timeval now = { 0, };
03960       int to;
03961 
03962       to = -1;
03963 
03964       if (!ast_tvzero(nexteventts)) {
03965          now = ast_tvnow();
03966          to = ast_tvdiff_ms(nexteventts, now);
03967          if (to <= 0) {
03968             if (!config->timelimit) {
03969                res = AST_BRIDGE_COMPLETE;
03970                break;
03971             }
03972             to = 0;
03973          }
03974       }
03975 
03976       if (config->timelimit) {
03977          time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
03978          if (time_left_ms < to)
03979             to = time_left_ms;
03980 
03981          if (time_left_ms <= 0) {
03982             if (caller_warning && config->end_sound)
03983                bridge_playfile(c0, c1, config->end_sound, 0);
03984             if (callee_warning && config->end_sound)
03985                bridge_playfile(c1, c0, config->end_sound, 0);
03986             *fo = NULL;
03987             if (who)
03988                *rc = who;
03989             res = 0;
03990             break;
03991          }
03992          
03993          if (!to) {
03994             if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
03995                int t = (time_left_ms + 500) / 1000; /* round to nearest second */
03996                if (caller_warning)
03997                   bridge_playfile(c0, c1, config->warning_sound, t);
03998                if (callee_warning)
03999                   bridge_playfile(c1, c0, config->warning_sound, t);
04000             }
04001             if (config->warning_freq && (time_left_ms > (config->warning_freq + 5000)))
04002                nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
04003             else
04004                nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
04005          }
04006       }
04007 
04008       if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
04009          if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
04010             c0->_softhangup = 0;
04011          if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
04012             c1->_softhangup = 0;
04013          c0->_bridge = c1;
04014          c1->_bridge = c0;
04015          if (option_debug)
04016             ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
04017          continue;
04018       }
04019       
04020       /* Stop if we're a zombie or need a soft hangup */
04021       if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
04022           ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
04023          *fo = NULL;
04024          if (who)
04025             *rc = who;
04026          res = 0;
04027          if (option_debug)
04028             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",
04029                c0->name, c1->name,
04030                ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
04031                ast_check_hangup(c0) ? "Yes" : "No",
04032                ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
04033                ast_check_hangup(c1) ? "Yes" : "No");
04034          break;
04035       }
04036       
04037       /* See if the BRIDGEPEER variable needs to be updated */
04038       if (!ast_strlen_zero(pbx_builtin_getvar_helper(c0, "BRIDGEPEER")))
04039          pbx_builtin_setvar_helper(c0, "BRIDGEPEER", c1->name);
04040       if (!ast_strlen_zero(pbx_builtin_getvar_helper(c1, "BRIDGEPEER")))
04041          pbx_builtin_setvar_helper(c1, "BRIDGEPEER", c0->name);
04042       
04043       if (c0->tech->bridge &&
04044           (config->timelimit == 0) &&
04045           (c0->tech->bridge == c1->tech->bridge) &&
04046           !nativefailed && !c0->monitor && !c1->monitor &&
04047           !c0->audiohooks && !c1->audiohooks && !ast_test_flag(&(config->features_callee),AST_FEATURE_REDIRECT) &&
04048           !ast_test_flag(&(config->features_caller),AST_FEATURE_REDIRECT) &&
04049           !c0->masq && !c0->masqr && !c1->masq && !c1->masqr) {
04050          /* Looks like they share a bridge method and nothing else is in the way */
04051          ast_set_flag(c0, AST_FLAG_NBRIDGE);
04052          ast_set_flag(c1, AST_FLAG_NBRIDGE);
04053          if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
04054             /* \todo  XXX here should check that cid_num is not NULL */
04055             manager_event(EVENT_FLAG_CALL, "Unlink",
04056                      "Channel1: %s\r\n"
04057                      "Channel2: %s\r\n"
04058                      "Uniqueid1: %s\r\n"
04059                      "Uniqueid2: %s\r\n"
04060                      "CallerID1: %s\r\n"
04061                      "CallerID2: %s\r\n",
04062                      c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
04063             if (option_debug)
04064                ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
04065 
04066             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
04067             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
04068 
04069             if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
04070                continue;
04071 
04072             c0->_bridge = NULL;
04073             c1->_bridge = NULL;
04074 
04075             return res;
04076          } else {
04077             ast_clear_flag(c0, AST_FLAG_NBRIDGE);
04078             ast_clear_flag(c1, AST_FLAG_NBRIDGE);
04079          }
04080          switch (res) {
04081          case AST_BRIDGE_RETRY:
04082             continue;
04083          default:
04084             if (option_verbose > 2)
04085                ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s ended\n",
04086                       c0->name, c1->name);
04087             /* fallthrough */
04088          case AST_BRIDGE_FAILED_NOWARN:
04089             nativefailed++;
04090             break;
04091          }
04092       }
04093    
04094       if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
04095           (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
04096           !(c0->generator || c1->generator)) {
04097          if (ast_channel_make_compatible(c0, c1)) {
04098             ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
04099             /* \todo  XXX here should check that cid_num is not NULL */
04100                                 manager_event(EVENT_FLAG_CALL, "Unlink",
04101                      "Channel1: %s\r\n"
04102                      "Channel2: %s\r\n"
04103                      "Uniqueid1: %s\r\n"
04104                      "Uniqueid2: %s\r\n"
04105                      "CallerID1: %s\r\n"
04106                      "CallerID2: %s\r\n",
04107                      c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
04108             return AST_BRIDGE_FAILED;
04109          }
04110          o0nativeformats = c0->nativeformats;
04111          o1nativeformats = c1->nativeformats;
04112       }
04113       res = ast_generic_bridge(c0, c1, config, fo, rc, nexteventts);
04114       if (res != AST_BRIDGE_RETRY)
04115          break;
04116    }
04117 
04118    ast_clear_flag(c0, AST_FLAG_END_DTMF_ONLY);
04119    ast_clear_flag(c1, AST_FLAG_END_DTMF_ONLY);
04120 
04121    /* Now that we have broken the bridge the source will change yet again */
04122    ast_indicate(c0, AST_CONTROL_SRCUPDATE);
04123    ast_indicate(c1, AST_CONTROL_SRCUPDATE);
04124 
04125    c0->_bridge = NULL;
04126    c1->_bridge = NULL;
04127 
04128    /* \todo  XXX here should check that cid_num is not NULL */
04129    manager_event(EVENT_FLAG_CALL, "Unlink",
04130             "Channel1: %s\r\n"
04131             "Channel2: %s\r\n"
04132             "Uniqueid1: %s\r\n"
04133             "Uniqueid2: %s\r\n"
04134             "CallerID1: %s\r\n"
04135             "CallerID2: %s\r\n",
04136             c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
04137    if (option_debug)
04138       ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
04139 
04140    return res;
04141 }
04142 
04143 /*! \brief Sets an option on a channel */
04144 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
04145 {
04146    int res;
04147 
04148    if (chan->tech->setoption) {
04149       res = chan->tech->setoption(chan, option, data, datalen);
04150       if (res < 0)
04151          return res;
04152    } else {
04153       errno = ENOSYS;
04154       return -1;
04155    }
04156    if (block) {
04157       /* XXX Implement blocking -- just wait for our option frame reply, discarding
04158          intermediate packets. XXX */
04159       ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
04160       return -1;
04161    }
04162    return 0;
04163 }
04164 
04165 struct tonepair_def {
04166    int freq1;
04167    int freq2;
04168    int duration;
04169    int vol;
04170 };
04171 
04172 struct tonepair_state {
04173    int fac1;
04174    int fac2;
04175    int v1_1;
04176    int v2_1;
04177    int v3_1;
04178    int v1_2;
04179    int v2_2;
04180    int v3_2;
04181    int origwfmt;
04182    int pos;
04183    int duration;
04184    int modulate;
04185    struct ast_frame f;
04186    unsigned char offset[AST_FRIENDLY_OFFSET];
04187    short data[4000];
04188 };
04189 
04190 static void tonepair_release(struct ast_channel *chan, void *params)
04191 {
04192    struct tonepair_state *ts = params;
04193 
04194    if (chan)
04195       ast_set_write_format(chan, ts->origwfmt);
04196    free(ts);
04197 }
04198 
04199 static void *tonepair_alloc(struct ast_channel *chan, void *params)
04200 {
04201    struct tonepair_state *ts;
04202    struct tonepair_def *td = params;
04203 
04204    if (!(ts = ast_calloc(1, sizeof(*ts))))
04205       return NULL;
04206    ts->origwfmt = chan->writeformat;
04207    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
04208       ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
04209       tonepair_release(NULL, ts);
04210       ts = NULL;
04211    } else {
04212       ts->fac1 = 2.0 * cos(2.0 * M_PI * (td->freq1 / 8000.0)) * 32768.0;
04213       ts->v1_1 = 0;
04214       ts->v2_1 = sin(-4.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
04215       ts->v3_1 = sin(-2.0 * M_PI * (td->freq1 / 8000.0)) * td->vol;
04216       ts->v2_1 = 0;
04217       ts->fac2 = 2.0 * cos(2.0 * M_PI * (td->freq2 / 8000.0)) * 32768.0;
04218       ts->v2_2 = sin(-4.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
04219       ts->v3_2 = sin(-2.0 * M_PI * (td->freq2 / 8000.0)) * td->vol;
04220       ts->duration = td->duration;
04221       ts->modulate = 0;
04222    }
04223    /* Let interrupts interrupt :) */
04224    ast_set_flag(chan, AST_FLAG_WRITE_INT);
04225    return ts;
04226 }
04227 
04228 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
04229 {
04230    struct tonepair_state *ts = data;
04231    int x;
04232 
04233    /* we need to prepare a frame with 16 * timelen samples as we're
04234     * generating SLIN audio
04235     */
04236    len = samples * 2;
04237 
04238    if (len > sizeof(ts->data) / 2 - 1) {
04239       ast_log(LOG_WARNING, "Can't generate that much data!\n");
04240       return -1;
04241    }
04242    memset(&ts->f, 0, sizeof(ts->f));
04243    for (x=0;x<len/2;x++) {
04244       ts->v1_1 = ts->v2_1;
04245       ts->v2_1 = ts->v3_1;
04246       ts->v3_1 = (ts->fac1 * ts->v2_1 >> 15) - ts->v1_1;
04247       
04248       ts->v1_2 = ts->v2_2;
04249       ts->v2_2 = ts->v3_2;
04250       ts->v3_2 = (ts->fac2 * ts->v2_2 >> 15) - ts->v1_2;
04251       if (ts->modulate) {
04252          int p;
04253          p = ts->v3_2 - 32768;
04254          if (p < 0) p = -p;
04255          p = ((p * 9) / 10) + 1;
04256          ts->data[x] = (ts->v3_1 * p) >> 15;
04257       } else
04258          ts->data[x] = ts->v3_1 + ts->v3_2; 
04259    }
04260    ts->f.frametype = AST_FRAME_VOICE;
04261    ts->f.subclass = AST_FORMAT_SLINEAR;
04262    ts->f.datalen = len;
04263    ts->f.samples = samples;
04264    ts->f.offset = AST_FRIENDLY_OFFSET;
04265    ts->f.data = ts->data;
04266    ast_write(chan, &ts->f);
04267    ts->pos += x;
04268    if (ts->duration > 0) {
04269       if (ts->pos >= ts->duration * 8)
04270          return -1;
04271    }
04272    return 0;
04273 }
04274 
04275 static struct ast_generator tonepair = {
04276    alloc: tonepair_alloc,
04277    release: tonepair_release,
04278    generate: tonepair_generator,
04279 };
04280 
04281 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
04282 {
04283    struct tonepair_def d = { 0, };
04284 
04285    d.freq1 = freq1;
04286    d.freq2 = freq2;
04287    d.duration = duration;
04288    d.vol = (vol < 1) ? 8192 : vol; /* force invalid to 8192 */
04289    if (ast_activate_generator(chan, &tonepair, &d))
04290       return -1;
04291    return 0;
04292 }
04293 
04294 void ast_tonepair_stop(struct ast_channel *chan)
04295 {
04296    ast_deactivate_generator(chan);
04297 }
04298 
04299 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
04300 {
04301    int res;
04302 
04303    if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
04304       return res;
04305 
04306    /* Give us some wiggle room */
04307    while (chan->generatordata && ast_waitfor(chan, 100) >= 0) {
04308       struct ast_frame *f = ast_read(chan);
04309       if (f)
04310          ast_frfree(f);
04311       else
04312          return -1;
04313    }
04314    return 0;
04315 }
04316 
04317 ast_group_t ast_get_group(const char *s)
04318 {
04319    char *piece;
04320    char *c;
04321    int start=0, finish=0, x;
04322    ast_group_t group = 0;
04323 
04324    if (ast_strlen_zero(s))
04325       return 0;
04326 
04327    c = ast_strdupa(s);
04328    
04329    while ((piece = strsep(&c, ","))) {
04330       if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
04331          /* Range */
04332       } else if (sscanf(piece, "%d", &start)) {
04333          /* Just one */
04334          finish = start;
04335       } else {
04336          ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
04337          continue;
04338       }
04339       for (x = start; x <= finish; x++) {
04340          if ((x > 63) || (x < 0)) {
04341             ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
04342          } else
04343             group |= ((ast_group_t) 1 << x);
04344       }
04345    }
04346    return group;
04347 }
04348 
04349 static int (*ast_moh_start_ptr)(struct ast_channel *, const char *, const char *) = NULL;
04350 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
04351 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
04352 
04353 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, const char *, const char *),
04354              void (*stop_ptr)(struct ast_channel *),
04355              void (*cleanup_ptr)(struct ast_channel *))
04356 {
04357    ast_moh_start_ptr = start_ptr;
04358    ast_moh_stop_ptr = stop_ptr;
04359    ast_moh_cleanup_ptr = cleanup_ptr;
04360 }
04361 
04362 void ast_uninstall_music_functions(void)
04363 {
04364    ast_moh_start_ptr = NULL;
04365    ast_moh_stop_ptr = NULL;
04366    ast_moh_cleanup_ptr = NULL;
04367 }
04368 
04369 /*! \brief Turn on music on hold on a given channel */
04370 int ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
04371 {
04372    if (ast_moh_start_ptr)
04373       return ast_moh_start_ptr(chan, mclass, interpclass);
04374 
04375    if (option_verbose > 2) {
04376       ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", 
04377          mclass ? mclass : (interpclass ? interpclass : "default"));
04378    }
04379 
04380    return 0;
04381 }
04382 
04383 /*! \brief Turn off music on hold on a given channel */
04384 void ast_moh_stop(struct ast_channel *chan)
04385 {
04386    if (ast_moh_stop_ptr)
04387       ast_moh_stop_ptr(chan);
04388 }
04389 
04390 void ast_moh_cleanup(struct ast_channel *chan)
04391 {
04392    if (ast_moh_cleanup_ptr)
04393       ast_moh_cleanup_ptr(chan);
04394 }
04395 
04396 void ast_channels_init(void)
04397 {
04398    ast_cli_register_multiple(cli_channel, sizeof(cli_channel) / sizeof(struct ast_cli_entry));
04399 }
04400 
04401 /*! \brief Print call group and pickup group ---*/
04402 char *ast_print_group(char *buf, int buflen, ast_group_t group)
04403 {
04404    unsigned int i;
04405    int first=1;
04406    char num[3];
04407 
04408    buf[0] = '\0';
04409    
04410    if (!group) /* Return empty string if no group */
04411       return buf;
04412 
04413    for (i = 0; i <= 63; i++) {   /* Max group is 63 */
04414       if (group & ((ast_group_t) 1 << i)) {
04415             if (!first) {
04416             strncat(buf, ", ", buflen - strlen(buf) - 1);
04417          } else {
04418             first=0;
04419          }
04420          snprintf(num, sizeof(num), "%u", i);
04421          strncat(buf, num, buflen - strlen(buf) - 1);
04422       }
04423    }
04424    return buf;
04425 }
04426 
04427 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
04428 {
04429    struct ast_variable *cur;
04430 
04431    for (cur = vars; cur; cur = cur->next)
04432       pbx_builtin_setvar_helper(chan, cur->name, cur->value);  
04433 }
04434 
04435 static void *silence_generator_alloc(struct ast_channel *chan, void *data)
04436 {
04437    /* just store the data pointer in the channel structure */
04438    return data;
04439 }
04440 
04441 static void silence_generator_release(struct ast_channel *chan, void *data)
04442 {
04443    /* nothing to do */
04444 }
04445 
04446 static int silence_generator_generate(struct ast_channel *chan, void *data, int len, int samples)
04447 {
04448    short buf[samples];
04449    struct ast_frame frame = {
04450       .frametype = AST_FRAME_VOICE,
04451       .subclass = AST_FORMAT_SLINEAR,
04452       .data = buf,
04453       .samples = samples,
04454       .datalen = sizeof(buf),
04455    };
04456    memset(buf, 0, sizeof(buf));
04457    if (ast_write(chan, &frame))
04458       return -1;
04459    return 0;
04460 }
04461 
04462 static struct ast_generator silence_generator = {
04463    .alloc = silence_generator_alloc,
04464    .release = silence_generator_release,
04465    .generate = silence_generator_generate,
04466 };
04467 
04468 struct ast_silence_generator {
04469    int old_write_format;
04470 };
04471 
04472 struct ast_silence_generator *ast_channel_start_silence_generator(struct ast_channel *chan)
04473 {
04474    struct ast_silence_generator *state;
04475 
04476    if (!(state = ast_calloc(1, sizeof(*state)))) {
04477       return NULL;
04478    }
04479 
04480    state->old_write_format = chan->writeformat;
04481 
04482    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
04483       ast_log(LOG_ERROR, "Could not set write format to SLINEAR\n");
04484       free(state);
04485       return NULL;
04486    }
04487 
04488    ast_activate_generator(chan, &silence_generator, state);
04489 
04490    if (option_debug)
04491       ast_log(LOG_DEBUG, "Started silence generator on '%s'\n", chan->name);
04492 
04493    return state;
04494 }
04495 
04496 void ast_channel_stop_silence_generator(struct ast_channel *chan, struct ast_silence_generator *state)
04497 {
04498    if (!state)
04499       return;
04500 
04501    ast_deactivate_generator(chan);
04502 
04503    if (option_debug)
04504       ast_log(LOG_DEBUG, "Stopped silence generator on '%s'\n", chan->name);
04505 
04506    if (ast_set_write_format(chan, state->old_write_format) < 0)
04507       ast_log(LOG_ERROR, "Could not return write format to its original state\n");
04508 
04509    free(state);
04510 }
04511 
04512 
04513 /*! \ brief Convert channel reloadreason (ENUM) to text string for manager event */
04514 const char *channelreloadreason2txt(enum channelreloadreason reason)
04515 {
04516    switch (reason) {
04517    case CHANNEL_MODULE_LOAD:
04518       return "LOAD (Channel module load)";
04519 
04520    case CHANNEL_MODULE_RELOAD:
04521       return "RELOAD (Channel module reload)";
04522 
04523    case CHANNEL_CLI_RELOAD:
04524       return "CLIRELOAD (Channel module reload by CLI command)";
04525 
04526    default:
04527       return "MANAGERRELOAD (Channel module reload by manager)";
04528    }
04529 };
04530 
04531 #ifdef DEBUG_CHANNEL_LOCKS
04532 
04533 /*! \brief Unlock AST channel (and print debugging output) 
04534 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
04535 */
04536 int __ast_channel_unlock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
04537 {
04538    int res = 0;
04539    if (option_debug > 2) 
04540       ast_log(LOG_DEBUG, "::::==== Unlocking AST channel %s\n", chan->name);
04541    
04542    if (!chan) {
04543       if (option_debug)
04544          ast_log(LOG_DEBUG, "::::==== Unlocking non-existing channel \n");
04545       return 0;
04546    }
04547 #ifdef DEBUG_THREADS
04548    res = __ast_pthread_mutex_unlock(filename, lineno, func, "(channel lock)", &chan->lock);
04549 #else
04550    res = ast_mutex_unlock(&chan->lock);
04551 #endif
04552 
04553    if (option_debug > 2) {
04554 #ifdef DEBUG_THREADS
04555       int count = 0;
04556       if ((count = chan->lock.reentrancy))
04557          ast_log(LOG_DEBUG, ":::=== Still have %d locks (recursive)\n", count);
04558 #endif
04559       if (!res)
04560          if (option_debug)
04561             ast_log(LOG_DEBUG, "::::==== Channel %s was unlocked\n", chan->name);
04562          if (res == EINVAL) {
04563             if (option_debug)
04564                ast_log(LOG_DEBUG, "::::==== Channel %s had no lock by this thread. Failed unlocking\n", chan->name);
04565          }
04566       }
04567       if (res == EPERM) {
04568          /* We had no lock, so okay any way*/
04569          if (option_debug > 3)
04570             ast_log(LOG_DEBUG, "::::==== Channel %s was not locked at all \n", chan->name);
04571       res = 0;
04572    }
04573    return res;
04574 }
04575 
04576 /*! \brief Lock AST channel (and print debugging output)
04577 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
04578 int __ast_channel_lock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
04579 {
04580    int res;
04581 
04582    if (option_debug > 3)
04583       ast_log(LOG_DEBUG, "====:::: Locking AST channel %s\n", chan->name);
04584 
04585 #ifdef DEBUG_THREADS
04586    res = __ast_pthread_mutex_lock(filename, lineno, func, "(channel lock)", &chan->lock);
04587 #else
04588    res = ast_mutex_lock(&chan->lock);
04589 #endif
04590 
04591    if (option_debug > 3) {
04592 #ifdef DEBUG_THREADS
04593       int count = 0;
04594       if ((count = chan->lock.reentrancy))
04595          ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
04596 #endif
04597       if (!res)
04598          ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
04599       if (res == EDEADLK) {
04600       /* We had no lock, so okey any way */
04601       if (option_debug > 3)
04602          ast_log(LOG_DEBUG, "::::==== Channel %s was not locked by us. Lock would cause deadlock.\n", chan->name);
04603       }
04604       if (res == EINVAL) {
04605          if (option_debug > 3)
04606             ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
04607       }
04608    }
04609    return res;
04610 }
04611 
04612 /*! \brief Lock AST channel (and print debugging output)
04613 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
04614 int __ast_channel_trylock(struct ast_channel *chan, const char *filename, int lineno, const char *func)
04615 {
04616    int res;
04617 
04618    if (option_debug > 2)
04619       ast_log(LOG_DEBUG, "====:::: Trying to lock AST channel %s\n", chan->name);
04620 #ifdef DEBUG_THREADS
04621    res = __ast_pthread_mutex_trylock(filename, lineno, func, "(channel lock)", &chan->lock);
04622 #else
04623    res = ast_mutex_trylock(&chan->lock);
04624 #endif
04625 
04626    if (option_debug > 2) {
04627 #ifdef DEBUG_THREADS
04628       int count = 0;
04629       if ((count = chan->lock.reentrancy))
04630          ast_log(LOG_DEBUG, ":::=== Now have %d locks (recursive)\n", count);
04631 #endif
04632       if (!res)
04633          ast_log(LOG_DEBUG, "::::==== Channel %s was locked\n", chan->name);
04634       if (res == EBUSY) {
04635          /* We failed to lock */
04636          if (option_debug > 2)
04637             ast_log(LOG_DEBUG, "::::==== Channel %s failed to lock. Not waiting around...\n", chan->name);
04638       }
04639       if (res == EDEADLK) {
04640          /* We had no lock, so okey any way*/
04641          if (option_debug > 2)
04642             ast_log(LOG_DEBUG, "::::==== Channel %s was not locked. Lock would cause deadlock.\n", chan->name);
04643       }
04644       if (res == EINVAL && option_debug > 2)
04645          ast_log(LOG_DEBUG, "::::==== Channel %s lock failed. No mutex.\n", chan->name);
04646    }
04647    return res;
04648 }
04649 
04650 #endif
04651 
04652 /*
04653  * Wrappers for various ast_say_*() functions that call the full version
04654  * of the same functions.
04655  * The proper place would be say.c, but that file is optional and one
04656  * must be able to build asterisk even without it (using a loadable 'say'
04657  * implementation that only supplies the 'full' version of the functions.
04658  */
04659 
04660 int ast_say_number(struct ast_channel *chan, int num,
04661    const char *ints, const char *language, const char *options)
04662 {
04663         return ast_say_number_full(chan, num, ints, language, options, -1, -1);
04664 }
04665 
04666 int ast_say_enumeration(struct ast_channel *chan, int num,
04667    const char *ints, const char *language, const char *options)
04668 {
04669         return ast_say_enumeration_full(chan, num, ints, language, options, -1, -1);
04670 }
04671 
04672 int ast_say_digits(struct ast_channel *chan, int num,
04673    const char *ints, const char *lang)
04674 {
04675         return ast_say_digits_full(chan, num, ints, lang, -1, -1);
04676 }
04677 
04678 int ast_say_digit_str(struct ast_channel *chan, const char *str,
04679    const char *ints, const char *lang)
04680 {
04681         return ast_say_digit_str_full(chan, str, ints, lang, -1, -1);
04682 }
04683 
04684 int ast_say_character_str(struct ast_channel *chan, const char *str,
04685    const char *ints, const char *lang)
04686 {
04687         return ast_say_character_str_full(chan, str, ints, lang, -1, -1);
04688 }
04689 
04690 int ast_say_phonetic_str(struct ast_channel *chan, const char *str,
04691    const char *ints, const char *lang)
04692 {
04693         return ast_say_phonetic_str_full(chan, str, ints, lang, -1, -1);
04694 }
04695 
04696 int ast_say_digits_full(struct ast_channel *chan, int num,
04697    const char *ints, const char *lang, int audiofd, int ctrlfd)
04698 {
04699         char buf[256];
04700 
04701         snprintf(buf, sizeof(buf), "%d", num);
04702         return ast_say_digit_str_full(chan, buf, ints, lang, audiofd, ctrlfd);
04703 }
04704 

Generated on Tue Nov 4 13:20:18 2008 for Asterisk - the Open Source PBX by  doxygen 1.4.7