Fri Jul 3 20:35:39 2009

Asterisk developer's documentation


pbx.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 Core PBX routines.
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00029 
00030 #include <sys/types.h>
00031 #include <string.h>
00032 #include <unistd.h>
00033 #include <stdlib.h>
00034 #include <stdio.h>
00035 #include <ctype.h>
00036 #include <errno.h>
00037 #include <time.h>
00038 #include <sys/time.h>
00039 #include <limits.h>
00040 
00041 #include "asterisk/lock.h"
00042 #include "asterisk/cli.h"
00043 #include "asterisk/pbx.h"
00044 #include "asterisk/channel.h"
00045 #include "asterisk/options.h"
00046 #include "asterisk/logger.h"
00047 #include "asterisk/file.h"
00048 #include "asterisk/callerid.h"
00049 #include "asterisk/cdr.h"
00050 #include "asterisk/config.h"
00051 #include "asterisk/term.h"
00052 #include "asterisk/manager.h"
00053 #include "asterisk/ast_expr.h"
00054 #include "asterisk/linkedlists.h"
00055 #define  SAY_STUBS   /* generate declarations and stubs for say methods */
00056 #include "asterisk/say.h"
00057 #include "asterisk/utils.h"
00058 #include "asterisk/causes.h"
00059 #include "asterisk/musiconhold.h"
00060 #include "asterisk/app.h"
00061 #include "asterisk/devicestate.h"
00062 #include "asterisk/stringfields.h"
00063 #include "asterisk/threadstorage.h"
00064 
00065 /*!
00066  * \note I M P O R T A N T :
00067  *
00068  *    The speed of extension handling will likely be among the most important
00069  * aspects of this PBX.  The switching scheme as it exists right now isn't
00070  * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
00071  * of priorities, but a constant search time here would be great ;-)
00072  *
00073  */
00074 
00075 #ifdef LOW_MEMORY
00076 #define EXT_DATA_SIZE 256
00077 #else
00078 #define EXT_DATA_SIZE 8192
00079 #endif
00080 
00081 #define SWITCH_DATA_LENGTH 256
00082 
00083 #define VAR_BUF_SIZE 4096
00084 
00085 #define  VAR_NORMAL     1
00086 #define  VAR_SOFTTRAN   2
00087 #define  VAR_HARDTRAN   3
00088 
00089 #define BACKGROUND_SKIP    (1 << 0)
00090 #define BACKGROUND_NOANSWER   (1 << 1)
00091 #define BACKGROUND_MATCHEXTEN (1 << 2)
00092 #define BACKGROUND_PLAYBACK   (1 << 3)
00093 
00094 AST_APP_OPTIONS(background_opts, {
00095    AST_APP_OPTION('s', BACKGROUND_SKIP),
00096    AST_APP_OPTION('n', BACKGROUND_NOANSWER),
00097    AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
00098    AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
00099 });
00100 
00101 #define WAITEXTEN_MOH      (1 << 0)
00102 
00103 AST_APP_OPTIONS(waitexten_opts, {
00104    AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
00105 });
00106 
00107 struct ast_context;
00108 
00109 AST_THREADSTORAGE(switch_data, switch_data_init);
00110 
00111 /*!
00112    \brief ast_exten: An extension
00113    The dialplan is saved as a linked list with each context
00114    having it's own linked list of extensions - one item per
00115    priority.
00116 */
00117 struct ast_exten {
00118    char *exten;         /*!< Extension name */
00119    int matchcid;        /*!< Match caller id ? */
00120    const char *cidmatch;      /*!< Caller id to match for this extension */
00121    int priority;        /*!< Priority */
00122    const char *label;      /*!< Label */
00123    struct ast_context *parent;   /*!< The context this extension belongs to  */
00124    const char *app;     /*!< Application to execute */
00125    void *data;       /*!< Data to use (arguments) */
00126    void (*datad)(void *);     /*!< Data destructor */
00127    struct ast_exten *peer;    /*!< Next higher priority with our extension */
00128    const char *registrar;     /*!< Registrar */
00129    struct ast_exten *next;    /*!< Extension with a greater ID */
00130    char stuff[0];
00131 };
00132 
00133 /*! \brief ast_include: include= support in extensions.conf */
00134 struct ast_include {
00135    const char *name;
00136    const char *rname;         /*!< Context to include */
00137    const char *registrar;        /*!< Registrar */
00138    int hastime;            /*!< If time construct exists */
00139    struct ast_timing timing;               /*!< time construct */
00140    struct ast_include *next;     /*!< Link them together */
00141    char stuff[0];
00142 };
00143 
00144 /*! \brief ast_sw: Switch statement in extensions.conf */
00145 struct ast_sw {
00146    char *name;
00147    const char *registrar;        /*!< Registrar */
00148    char *data;          /*!< Data load */
00149    int eval;
00150    AST_LIST_ENTRY(ast_sw) list;
00151    char stuff[0];
00152 };
00153 
00154 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
00155 struct ast_ignorepat {
00156    const char *registrar;
00157    struct ast_ignorepat *next;
00158    const char pattern[0];
00159 };
00160 
00161 /*! \brief ast_context: An extension context */
00162 struct ast_context {
00163    ast_mutex_t lock;          /*!< A lock to prevent multiple threads from clobbering the context */
00164    struct ast_exten *root;       /*!< The root of the list of extensions */
00165    struct ast_context *next;     /*!< Link them together */
00166    struct ast_include *includes;    /*!< Include other contexts */
00167    struct ast_ignorepat *ignorepats;   /*!< Patterns for which to continue playing dialtone */
00168    const char *registrar;        /*!< Registrar */
00169    AST_LIST_HEAD_NOLOCK(, ast_sw) alts;   /*!< Alternative switches */
00170    ast_mutex_t macrolock;        /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
00171    char name[0];           /*!< Name of the context */
00172 };
00173 
00174 
00175 /*! \brief ast_app: A registered application */
00176 struct ast_app {
00177    int (*execute)(struct ast_channel *chan, void *data);
00178    const char *synopsis;         /*!< Synopsis text for 'show applications' */
00179    const char *description;      /*!< Description (help text) for 'show application &lt;name&gt;' */
00180    AST_LIST_ENTRY(ast_app) list;    /*!< Next app in list */
00181    struct module *module;        /*!< Module this app belongs to */
00182    char name[0];           /*!< Name of the application */
00183 };
00184 
00185 /*! \brief ast_state_cb: An extension state notify register item */
00186 struct ast_state_cb {
00187    int id;
00188    void *data;
00189    ast_state_cb_type callback;
00190    struct ast_state_cb *next;
00191 };
00192 
00193 /*! \brief Structure for dial plan hints
00194 
00195   \note Hints are pointers from an extension in the dialplan to one or
00196   more devices (tech/name) */
00197 struct ast_hint {
00198    struct ast_exten *exten;   /*!< Extension */
00199    int laststate;          /*!< Last known state */
00200    struct ast_state_cb *callbacks;  /*!< Callback list for this extension */
00201    AST_LIST_ENTRY(ast_hint) list;   /*!< Pointer to next hint in list */
00202 };
00203 
00204 static const struct cfextension_states {
00205    int extension_state;
00206    const char * const text;
00207 } extension_states[] = {
00208    { AST_EXTENSION_NOT_INUSE,                     "Idle" },
00209    { AST_EXTENSION_INUSE,                         "InUse" },
00210    { AST_EXTENSION_BUSY,                          "Busy" },
00211    { AST_EXTENSION_UNAVAILABLE,                   "Unavailable" },
00212    { AST_EXTENSION_RINGING,                       "Ringing" },
00213    { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
00214    { AST_EXTENSION_ONHOLD,                        "Hold" },
00215    { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD,  "InUse&Hold" }
00216 };
00217 
00218 static int pbx_builtin_answer(struct ast_channel *, void *);
00219 static int pbx_builtin_goto(struct ast_channel *, void *);
00220 static int pbx_builtin_hangup(struct ast_channel *, void *);
00221 static int pbx_builtin_background(struct ast_channel *, void *);
00222 static int pbx_builtin_wait(struct ast_channel *, void *);
00223 static int pbx_builtin_waitexten(struct ast_channel *, void *);
00224 static int pbx_builtin_resetcdr(struct ast_channel *, void *);
00225 static int pbx_builtin_setamaflags(struct ast_channel *, void *);
00226 static int pbx_builtin_ringing(struct ast_channel *, void *);
00227 static int pbx_builtin_progress(struct ast_channel *, void *);
00228 static int pbx_builtin_congestion(struct ast_channel *, void *);
00229 static int pbx_builtin_busy(struct ast_channel *, void *);
00230 static int pbx_builtin_setglobalvar(struct ast_channel *, void *);
00231 static int pbx_builtin_noop(struct ast_channel *, void *);
00232 static int pbx_builtin_gotoif(struct ast_channel *, void *);
00233 static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
00234 static int pbx_builtin_execiftime(struct ast_channel *, void *);
00235 static int pbx_builtin_saynumber(struct ast_channel *, void *);
00236 static int pbx_builtin_saydigits(struct ast_channel *, void *);
00237 static int pbx_builtin_saycharacters(struct ast_channel *, void *);
00238 static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
00239 int pbx_builtin_setvar(struct ast_channel *, void *);
00240 static int pbx_builtin_importvar(struct ast_channel *, void *);
00241 
00242 AST_MUTEX_DEFINE_STATIC(globalslock);
00243 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
00244 
00245 static int autofallthrough = 1;
00246 
00247 AST_MUTEX_DEFINE_STATIC(maxcalllock);
00248 static int countcalls;
00249 
00250 static AST_LIST_HEAD_STATIC(acf_root, ast_custom_function);
00251 
00252 /*! \brief Declaration of builtin applications */
00253 static struct pbx_builtin {
00254    char name[AST_MAX_APP];
00255    int (*execute)(struct ast_channel *chan, void *data);
00256    char *synopsis;
00257    char *description;
00258 } builtins[] =
00259 {
00260    /* These applications are built into the PBX core and do not
00261       need separate modules */
00262 
00263    { "Answer", pbx_builtin_answer,
00264    "Answer a channel if ringing",
00265    "  Answer([delay]): If the call has not been answered, this application will\n"
00266    "answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
00267    "Asterisk will wait this number of milliseconds before returning to\n"
00268    "the dialplan after answering the call.\n"
00269    },
00270 
00271    { "BackGround", pbx_builtin_background,
00272    "Play an audio file while waiting for digits of an extension to go to.",
00273    "  Background(filename1[&filename2...][|options[|langoverride][|context]]):\n"
00274    "This application will play the given list of files (do not put extension)\n"
00275    "while waiting for an extension to be dialed by the calling channel. To\n"
00276    "continue waiting for digits after this application has finished playing\n"
00277    "files, the WaitExten application should be used. The 'langoverride' option\n"
00278    "explicitly specifies which language to attempt to use for the requested sound\n"
00279    "files. If a 'context' is specified, this is the dialplan context that this\n"
00280    "application will use when exiting to a dialed extension."
00281    "  If one of the requested sound files does not exist, call processing will be\n"
00282    "terminated.\n"
00283    "  Options:\n"
00284    "    s - Causes the playback of the message to be skipped\n"
00285    "          if the channel is not in the 'up' state (i.e. it\n"
00286    "          hasn't been answered yet). If this happens, the\n"
00287    "          application will return immediately.\n"
00288    "    n - Don't answer the channel before playing the files.\n"
00289    "    m - Only break if a digit hit matches a one digit\n"
00290    "          extension in the destination context.\n"
00291    "See Also: Playback (application) -- Play sound file(s) to the channel,\n"
00292     "                                    that cannot be interrupted\n"
00293    },
00294 
00295    { "Busy", pbx_builtin_busy,
00296    "Indicate the Busy condition",
00297    "  Busy([timeout]): This application will indicate the busy condition to\n"
00298    "the calling channel. If the optional timeout is specified, the calling channel\n"
00299    "will be hung up after the specified number of seconds. Otherwise, this\n"
00300    "application will wait until the calling channel hangs up.\n"
00301    },
00302 
00303    { "Congestion", pbx_builtin_congestion,
00304    "Indicate the Congestion condition",
00305    "  Congestion([timeout]): This application will indicate the congestion\n"
00306    "condition to the calling channel. If the optional timeout is specified, the\n"
00307    "calling channel will be hung up after the specified number of seconds.\n"
00308    "Otherwise, this application will wait until the calling channel hangs up.\n"
00309    },
00310 
00311    { "Goto", pbx_builtin_goto,
00312    "Jump to a particular priority, extension, or context",
00313    "  Goto([[context|]extension|]priority): This application will set the current\n"
00314    "context, extension, and priority in the channel structure. After it completes, the\n"
00315    "pbx engine will continue dialplan execution at the specified location.\n"
00316    "If no specific extension, or extension and context, are specified, then this\n"
00317    "application will just set the specified priority of the current extension.\n"
00318    "  At least a priority is required as an argument, or the goto will return a -1,\n"
00319    "and the channel and call will be terminated.\n"
00320    "  If the location that is put into the channel information is bogus, and asterisk cannot\n"
00321         "find that location in the dialplan,\n"
00322    "then the execution engine will try to find and execute the code in the 'i' (invalid)\n"
00323    "extension in the current context. If that does not exist, it will try to execute the\n"
00324    "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
00325    "channel is hung up, and the execution of instructions on the channel is terminated.\n"
00326    "What this means is that, for example, you specify a context that does not exist, then\n"
00327    "it will not be possible to find the 'h' or 'i' extensions, and the call will terminate!\n"
00328    },
00329 
00330    { "GotoIf", pbx_builtin_gotoif,
00331    "Conditional goto",
00332    "  GotoIf(condition?[labeliftrue]:[labeliffalse]): This application will set the current\n"
00333    "context, extension, and priority in the channel structure based on the evaluation of\n"
00334    "the given condition. After this application completes, the\n"
00335    "pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
00336    "The channel will continue at\n"
00337    "'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
00338    "false. The labels are specified with the same syntax as used within the Goto\n"
00339    "application.  If the label chosen by the condition is omitted, no jump is\n"
00340    "performed, and the execution passes to the next instruction.\n"
00341    "If the target location is bogus, and does not exist, the execution engine will try \n"
00342    "to find and execute the code in the 'i' (invalid)\n"
00343    "extension in the current context. If that does not exist, it will try to execute the\n"
00344    "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
00345    "channel is hung up, and the execution of instructions on the channel is terminated.\n"
00346    "Remember that this command can set the current context, and if the context specified\n"
00347    "does not exist, then it will not be able to find any 'h' or 'i' extensions there, and\n"
00348    "the channel and call will both be terminated!\n"
00349    },
00350 
00351    { "GotoIfTime", pbx_builtin_gotoiftime,
00352    "Conditional Goto based on the current time",
00353    "  GotoIfTime(<times>|<weekdays>|<mdays>|<months>?[[context|]exten|]priority):\n"
00354    "This application will set the context, extension, and priority in the channel structure\n"
00355    "if the current time matches the given time specification. Otherwise, nothing is done.\n"
00356         "Further information on the time specification can be found in examples\n"
00357         "illustrating how to do time-based context includes in the dialplan.\n" 
00358    "If the target jump location is bogus, the same actions would be taken as for Goto.\n"
00359    },
00360 
00361    { "ExecIfTime", pbx_builtin_execiftime,
00362    "Conditional application execution based on the current time",
00363    "  ExecIfTime(<times>|<weekdays>|<mdays>|<months>?appname[|appargs]):\n"
00364    "This application will execute the specified dialplan application, with optional\n"
00365    "arguments, if the current time matches the given time specification.\n"
00366    },
00367 
00368    { "Hangup", pbx_builtin_hangup,
00369    "Hang up the calling channel",
00370    "  Hangup([causecode]): This application will hang up the calling channel.\n"
00371    "If a causecode is given the channel's hangup cause will be set to the given\n"
00372    "value.\n"
00373    },
00374 
00375    { "NoOp", pbx_builtin_noop,
00376    "Do Nothing",
00377    "  NoOp(): This applicatiion does nothing. However, it is useful for debugging\n"
00378    "purposes. Any text that is provided as arguments to this application can be\n"
00379    "viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
00380    "variables or functions without having any effect."
00381    },
00382 
00383    { "Progress", pbx_builtin_progress,
00384    "Indicate progress",
00385    "  Progress(): This application will request that in-band progress information\n"
00386    "be provided to the calling channel.\n"
00387    },
00388 
00389    { "ResetCDR", pbx_builtin_resetcdr,
00390    "Resets the Call Data Record",
00391    "  ResetCDR([options]):  This application causes the Call Data Record to be\n"
00392    "reset.\n"
00393    "  Options:\n"
00394    "    w -- Store the current CDR record before resetting it.\n"
00395    "    a -- Store any stacked records.\n"
00396    "    v -- Save CDR variables.\n"
00397    },
00398 
00399    { "Ringing", pbx_builtin_ringing,
00400    "Indicate ringing tone",
00401    "  Ringing(): This application will request that the channel indicate a ringing\n"
00402    "tone to the user.\n"
00403    },
00404 
00405    { "SayNumber", pbx_builtin_saynumber,
00406    "Say Number",
00407    "  SayNumber(digits[,gender]): This application will play the sounds that\n"
00408    "correspond to the given number. Optionally, a gender may be specified.\n"
00409    "This will use the language that is currently set for the channel. See the\n"
00410    "LANGUAGE function for more information on setting the language for the channel.\n"
00411    },
00412 
00413    { "SayDigits", pbx_builtin_saydigits,
00414    "Say Digits",
00415    "  SayDigits(digits): This application will play the sounds that correspond\n"
00416    "to the digits of the given number. This will use the language that is currently\n"
00417    "set for the channel. See the LANGUAGE function for more information on setting\n"
00418    "the language for the channel.\n"
00419    },
00420 
00421    { "SayAlpha", pbx_builtin_saycharacters,
00422    "Say Alpha",
00423    "  SayAlpha(string): This application will play the sounds that correspond to\n"
00424    "the letters of the given string.\n"
00425    },
00426 
00427    { "SayPhonetic", pbx_builtin_sayphonetic,
00428    "Say Phonetic",
00429    "  SayPhonetic(string): This application will play the sounds from the phonetic\n"
00430    "alphabet that correspond to the letters in the given string.\n"
00431    },
00432 
00433    { "SetAMAFlags", pbx_builtin_setamaflags,
00434    "Set the AMA Flags",
00435    "  SetAMAFlags([flag]): This application will set the channel's AMA Flags for\n"
00436    "  billing purposes.\n"
00437    },
00438 
00439    { "SetGlobalVar", pbx_builtin_setglobalvar,
00440    "Set a global variable to a given value",
00441    "  SetGlobalVar(variable=value): This application sets a given global variable to\n"
00442    "the specified value.\n"
00443    "\n\nThis application is deprecated in favor of Set(GLOBAL(var)=value)\n"
00444    },
00445 
00446    { "Set", pbx_builtin_setvar,
00447    "Set channel variable(s) or function value(s)",
00448    "  Set(name1=value1|name2=value2|..[|options])\n"
00449    "This function can be used to set the value of channel variables or dialplan\n"
00450    "functions. It will accept up to 24 name/value pairs. When setting variables,\n"
00451    "if the variable name is prefixed with _, the variable will be inherited into\n"
00452    "channels created from the current channel. If the variable name is prefixed\n"
00453    "with __, the variable will be inherited into channels created from the current\n"
00454    "channel and all children channels.\n"
00455    "  Options:\n"
00456    "    g - Set variable globally instead of on the channel\n"
00457    "        (applies only to variables, not functions)\n"
00458    "\n\nThe use of Set to set multiple variables at once and the g flag have both\n"
00459    "been deprecated.  Please use multiple Set calls and the GLOBAL() dialplan\n"
00460    "function instead.\n"
00461    },
00462 
00463    { "ImportVar", pbx_builtin_importvar,
00464    "Import a variable from a channel into a new variable",
00465    "  ImportVar(newvar=channelname|variable): This application imports a variable\n"
00466    "from the specified channel (as opposed to the current one) and stores it as\n"
00467    "a variable in the current channel (the channel that is calling this\n"
00468    "application). Variables created by this application have the same inheritance\n"
00469    "properties as those created with the Set application. See the documentation for\n"
00470    "Set for more information.\n"
00471    },
00472 
00473    { "Wait", pbx_builtin_wait,
00474    "Waits for some time",
00475    "  Wait(seconds): This application waits for a specified number of seconds.\n"
00476    "Then, dialplan execution will continue at the next priority.\n"
00477    "  Note that the seconds can be passed with fractions of a second. For example,\n"
00478    "'1.5' will ask the application to wait for 1.5 seconds.\n"
00479    },
00480 
00481    { "WaitExten", pbx_builtin_waitexten,
00482    "Waits for an extension to be entered",
00483    "  WaitExten([seconds][|options]): This application waits for the user to enter\n"
00484    "a new extension for a specified number of seconds.\n"
00485    "  Note that the seconds can be passed with fractions of a second. For example,\n"
00486    "'1.5' will ask the application to wait for 1.5 seconds.\n"
00487    "  Options:\n"
00488    "    m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
00489    "               Optionally, specify the class for music on hold within parenthesis.\n"
00490    "See Also: Playback(application), Background(application).\n"
00491    },
00492 
00493 };
00494 
00495 static struct ast_context *contexts;
00496 AST_RWLOCK_DEFINE_STATIC(conlock);     /*!< Lock for the ast_context list */
00497 
00498 static AST_LIST_HEAD_STATIC(apps, ast_app);
00499 
00500 static AST_LIST_HEAD_STATIC(switches, ast_switch);
00501 
00502 static int stateid = 1;
00503 /* WARNING:
00504    When holding this list's lock, do _not_ do anything that will cause conlock
00505    to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
00506    function will take the locks in conlock/hints order, so any other
00507    paths that require both locks must also take them in that order.
00508 */
00509 static AST_LIST_HEAD_STATIC(hints, ast_hint);
00510 struct ast_state_cb *statecbs;
00511 
00512 /*
00513    \note This function is special. It saves the stack so that no matter
00514    how many times it is called, it returns to the same place */
00515 int pbx_exec(struct ast_channel *c,       /*!< Channel */
00516         struct ast_app *app,     /*!< Application */
00517         void *data)        /*!< Data for execution */
00518 {
00519    int res;
00520 
00521    const char *saved_c_appl;
00522    const char *saved_c_data;
00523 
00524    if (c->cdr && !ast_check_hangup(c))
00525       ast_cdr_setapp(c->cdr, app->name, data);
00526 
00527    /* save channel values */
00528    saved_c_appl= c->appl;
00529    saved_c_data= c->data;
00530 
00531    c->appl = app->name;
00532    c->data = data;
00533    /* XXX remember what to to when we have linked apps to modules */
00534    if (app->module) {
00535       /* XXX LOCAL_USER_ADD(app->module) */
00536    }
00537    res = app->execute(c, S_OR(data, ""));
00538    if (app->module) {
00539       /* XXX LOCAL_USER_REMOVE(app->module) */
00540    }
00541    /* restore channel values */
00542    c->appl = saved_c_appl;
00543    c->data = saved_c_data;
00544    return res;
00545 }
00546 
00547 
00548 /*! Go no deeper than this through includes (not counting loops) */
00549 #define AST_PBX_MAX_STACK  128
00550 
00551 /*! \brief Find application handle in linked list
00552  */
00553 struct ast_app *pbx_findapp(const char *app)
00554 {
00555    struct ast_app *tmp;
00556 
00557    AST_LIST_LOCK(&apps);
00558    AST_LIST_TRAVERSE(&apps, tmp, list) {
00559       if (!strcasecmp(tmp->name, app))
00560          break;
00561    }
00562    AST_LIST_UNLOCK(&apps);
00563 
00564    return tmp;
00565 }
00566 
00567 static struct ast_switch *pbx_findswitch(const char *sw)
00568 {
00569    struct ast_switch *asw;
00570 
00571    AST_LIST_LOCK(&switches);
00572    AST_LIST_TRAVERSE(&switches, asw, list) {
00573       if (!strcasecmp(asw->name, sw))
00574          break;
00575    }
00576    AST_LIST_UNLOCK(&switches);
00577 
00578    return asw;
00579 }
00580 
00581 static inline int include_valid(struct ast_include *i)
00582 {
00583    if (!i->hastime)
00584       return 1;
00585 
00586    return ast_check_timing(&(i->timing));
00587 }
00588 
00589 static void pbx_destroy(struct ast_pbx *p)
00590 {
00591    free(p);
00592 }
00593 
00594 /*
00595  * Special characters used in patterns:
00596  * '_'   underscore is the leading character of a pattern.
00597  *    In other position it is treated as a regular char.
00598  * ' ' '-'  space and '-' are separator and ignored. Why? so
00599  *         patterns like NXX-XXX-XXXX or NXX XXX XXXX will work.
00600  * .  one or more of any character. Only allowed at the end of
00601  *    a pattern.
00602  * !  zero or more of anything. Also impacts the result of CANMATCH
00603  *    and MATCHMORE. Only allowed at the end of a pattern.
00604  *    In the core routine, ! causes a match with a return code of 2.
00605  *    In turn, depending on the search mode: (XXX check if it is implemented)
00606  *    - E_MATCH retuns 1 (does match)
00607  *    - E_MATCHMORE returns 0 (no match)
00608  *    - E_CANMATCH returns 1 (does match)
00609  *
00610  * /  should not appear as it is considered the separator of the CID info.
00611  *    XXX at the moment we may stop on this char.
00612  *
00613  * X Z N match ranges 0-9, 1-9, 2-9 respectively.
00614  * [  denotes the start of a set of character. Everything inside
00615  *    is considered literally. We can have ranges a-d and individual
00616  *    characters. A '[' and '-' can be considered literally if they
00617  *    are just before ']'.
00618  *    XXX currently there is no way to specify ']' in a range, nor \ is
00619  *    considered specially.
00620  *
00621  * When we compare a pattern with a specific extension, all characters in the extension
00622  * itself are considered literally with the only exception of '-' which is considered
00623  * as a separator and thus ignored.
00624  * XXX do we want to consider space as a separator as well ?
00625  * XXX do we want to consider the separators in non-patterns as well ?
00626  */
00627 
00628 /*!
00629  * \brief helper functions to sort extensions and patterns in the desired way,
00630  * so that more specific patterns appear first.
00631  *
00632  * ext_cmp1 compares individual characters (or sets of), returning
00633  * an int where bits 0-7 are the ASCII code of the first char in the set,
00634  * while bit 8-15 are the cardinality of the set minus 1.
00635  * This way more specific patterns (smaller cardinality) appear first.
00636  * Wildcards have a special value, so that we can directly compare them to
00637  * sets by subtracting the two values. In particular:
00638  *    0x000xx     one character, xx
00639  *    0x0yyxx     yy character set starting with xx
00640  *    0x10000     '.' (one or more of anything)
00641  *    0x20000     '!' (zero or more of anything)
00642  *    0x30000     NUL (end of string)
00643  *    0x40000     error in set.
00644  * The pointer to the string is advanced according to needs.
00645  * NOTES:
00646  * 1. the empty set is equivalent to NUL.
00647  * 2. given that a full set has always 0 as the first element,
00648  *    we could encode the special cases as 0xffXX where XX
00649  *    is 1, 2, 3, 4 as used above.
00650  */
00651 static int ext_cmp1(const char **p)
00652 {
00653    uint32_t chars[8];
00654    int c, cmin = 0xff, count = 0;
00655    const char *end;
00656 
00657    /* load, sign extend and advance pointer until we find
00658     * a valid character.
00659     */
00660    while ( (c = *(*p)++) && (c == ' ' || c == '-') )
00661       ;  /* ignore some characters */
00662 
00663    /* always return unless we have a set of chars */
00664    switch (c) {
00665    default: /* ordinary character */
00666       return 0x0000 | (c & 0xff);
00667 
00668    case 'N':   /* 2..9 */
00669       return 0x0800 | '2' ;
00670 
00671    case 'X':   /* 0..9 */
00672       return 0x0A00 | '0';
00673 
00674    case 'Z':   /* 1..9 */
00675       return 0x0900 | '1';
00676 
00677    case '.':   /* wildcard */
00678       return 0x10000;
00679 
00680    case '!':   /* earlymatch */
00681       return 0x20000;   /* less specific than NULL */
00682 
00683    case '\0':  /* empty string */
00684       *p = NULL;
00685       return 0x30000;
00686 
00687    case '[':   /* pattern */
00688       break;
00689    }
00690    /* locate end of set */
00691    end = strchr(*p, ']');  
00692 
00693    if (end == NULL) {
00694       ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
00695       return 0x40000;   /* XXX make this entry go last... */
00696    }
00697 
00698    bzero(chars, sizeof(chars));  /* clear all chars in the set */
00699    for (; *p < end  ; (*p)++) {
00700       unsigned char c1, c2;   /* first-last char in range */
00701       c1 = (unsigned char)((*p)[0]);
00702       if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
00703          c2 = (unsigned char)((*p)[2]);
00704          *p += 2; /* skip a total of 3 chars */
00705       } else         /* individual character */
00706          c2 = c1;
00707       if (c1 < cmin)
00708          cmin = c1;
00709       for (; c1 <= c2; c1++) {
00710          uint32_t mask = 1 << (c1 % 32);
00711          if ( (chars[ c1 / 32 ] & mask) == 0)
00712             count += 0x100;
00713          chars[ c1 / 32 ] |= mask;
00714       }
00715    }
00716    (*p)++;
00717    return count == 0 ? 0x30000 : (count | cmin);
00718 }
00719 
00720 /*!
00721  * \brief the full routine to compare extensions in rules.
00722  */
00723 static int ext_cmp(const char *a, const char *b)
00724 {
00725    /* make sure non-patterns come first.
00726     * If a is not a pattern, it either comes first or
00727     * we use strcmp to compare the strings.
00728     */
00729    int ret = 0;
00730 
00731    if (a[0] != '_')
00732       return (b[0] == '_') ? -1 : strcmp(a, b);
00733 
00734    /* Now we know a is a pattern; if b is not, a comes first */
00735    if (b[0] != '_')
00736       return 1;
00737 #if 0 /* old mode for ext matching */
00738    return strcmp(a, b);
00739 #endif
00740    /* ok we need full pattern sorting routine */
00741    while (!ret && a && b)
00742       ret = ext_cmp1(&a) - ext_cmp1(&b);
00743    if (ret == 0)
00744       return 0;
00745    else
00746       return (ret > 0) ? 1 : -1;
00747 }
00748 
00749 /*!
00750  * When looking up extensions, we can have different requests
00751  * identified by the 'action' argument, as follows.
00752  * Note that the coding is such that the low 4 bits are the
00753  * third argument to extension_match_core.
00754  */
00755 enum ext_match_t {
00756    E_MATCHMORE =  0x00, /* extension can match but only with more 'digits' */
00757    E_CANMATCH =   0x01, /* extension can match with or without more 'digits' */
00758    E_MATCH =   0x02, /* extension is an exact match */
00759    E_MATCH_MASK = 0x03, /* mask for the argument to extension_match_core() */
00760    E_SPAWN =   0x12, /* want to spawn an extension. Requires exact match */
00761    E_FINDLABEL =  0x22  /* returns the priority for a given label. Requires exact match */
00762 };
00763 
00764 /*
00765  * Internal function for ast_extension_{match|close}
00766  * return 0 on no-match, 1 on match, 2 on early match.
00767  * mode is as follows:
00768  * E_MATCH     success only on exact match
00769  * E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
00770  * E_CANMATCH  either of the above.
00771  */
00772 
00773 static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
00774 {
00775    mode &= E_MATCH_MASK;   /* only consider the relevant bits */
00776 
00777    if ( (mode == E_MATCH) && (pattern[0] == '_') && (strcasecmp(pattern,data)==0) ) /* note: if this test is left out, then _x. will not match _x. !!! */
00778       return 1;
00779 
00780    if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
00781       int ld = strlen(data), lp = strlen(pattern);
00782 
00783       if (lp < ld)      /* pattern too short, cannot match */
00784          return 0;
00785       /* depending on the mode, accept full or partial match or both */
00786       if (mode == E_MATCH)
00787          return !strcmp(pattern, data); /* 1 on match, 0 on fail */
00788       if (ld == 0 || !strncasecmp(pattern, data, ld)) /* partial or full match */
00789          return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
00790       else
00791          return 0;
00792    }
00793    pattern++; /* skip leading _ */
00794    /*
00795     * XXX below we stop at '/' which is a separator for the CID info. However we should
00796     * not store '/' in the pattern at all. When we insure it, we can remove the checks.
00797     */
00798    while (*data && *pattern && *pattern != '/') {
00799       const char *end;
00800 
00801       if (*data == '-') { /* skip '-' in data (just a separator) */
00802          data++;
00803          continue;
00804       }
00805       switch (toupper(*pattern)) {
00806       case '[':   /* a range */
00807          end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
00808          if (end == NULL) {
00809             ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
00810             return 0;   /* unconditional failure */
00811          }
00812          for (pattern++; pattern != end; pattern++) {
00813             if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
00814                if (*data >= pattern[0] && *data <= pattern[2])
00815                   break;   /* match found */
00816                else {
00817                   pattern += 2; /* skip a total of 3 chars */
00818                   continue;
00819                }
00820             } else if (*data == pattern[0])
00821                break;   /* match found */
00822          }
00823          if (pattern == end)
00824             return 0;
00825          pattern = end; /* skip and continue */
00826          break;
00827       case 'N':
00828          if (*data < '2' || *data > '9')
00829             return 0;
00830          break;
00831       case 'X':
00832          if (*data < '0' || *data > '9')
00833             return 0;
00834          break;
00835       case 'Z':
00836          if (*data < '1' || *data > '9')
00837             return 0;
00838          break;
00839       case '.':   /* Must match, even with more digits */
00840          return 1;
00841       case '!':   /* Early match */
00842          return 2;
00843       case ' ':
00844       case '-':   /* Ignore these in patterns */
00845          data--; /* compensate the final data++ */
00846          break;
00847       default:
00848          if (*data != *pattern)
00849             return 0;
00850       }
00851       data++;
00852       pattern++;
00853    }
00854    if (*data)        /* data longer than pattern, no match */
00855       return 0;
00856    /*
00857     * match so far, but ran off the end of the data.
00858     * Depending on what is next, determine match or not.
00859     */
00860    if (*pattern == '\0' || *pattern == '/')  /* exact match */
00861       return (mode == E_MATCHMORE) ? 0 : 1;  /* this is a failure for E_MATCHMORE */
00862    else if (*pattern == '!')        /* early match */
00863       return 2;
00864    else                 /* partial match */
00865       return (mode == E_MATCH) ? 0 : 1;   /* this is a failure for E_MATCH */
00866 }
00867 
00868 /*
00869  * Wrapper around _extension_match_core() to do performance measurement
00870  * using the profiling code.
00871  */
00872 static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
00873 {
00874    int i;
00875    static int prof_id = -2;   /* marker for 'unallocated' id */
00876    if (prof_id == -2)
00877       prof_id = ast_add_profile("ext_match", 0);
00878    ast_mark(prof_id, 1);
00879    i = _extension_match_core(pattern, data, mode);
00880    ast_mark(prof_id, 0);
00881    return i;
00882 }
00883 
00884 int ast_extension_match(const char *pattern, const char *data)
00885 {
00886    return extension_match_core(pattern, data, E_MATCH);
00887 }
00888 
00889 int ast_extension_close(const char *pattern, const char *data, int needmore)
00890 {
00891    if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
00892       ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
00893    return extension_match_core(pattern, data, needmore);
00894 }
00895 
00896 struct ast_context *ast_context_find(const char *name)
00897 {
00898    struct ast_context *tmp = NULL;
00899 
00900    ast_rdlock_contexts();
00901 
00902    while ( (tmp = ast_walk_contexts(tmp)) ) {
00903       if (!name || !strcasecmp(name, tmp->name))
00904          break;
00905    }
00906 
00907    ast_unlock_contexts();
00908 
00909    return tmp;
00910 }
00911 
00912 #define STATUS_NO_CONTEXT  1
00913 #define STATUS_NO_EXTENSION   2
00914 #define STATUS_NO_PRIORITY 3
00915 #define STATUS_NO_LABEL    4
00916 #define STATUS_SUCCESS     5
00917 
00918 static int matchcid(const char *cidpattern, const char *callerid)
00919 {
00920    /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
00921       failing to get a number should count as a match, otherwise not */
00922 
00923    if (ast_strlen_zero(callerid))
00924       return ast_strlen_zero(cidpattern) ? 1 : 0;
00925 
00926    return ast_extension_match(cidpattern, callerid);
00927 }
00928 
00929 /* request and result for pbx_find_extension */
00930 struct pbx_find_info {
00931 #if 0
00932    const char *context;
00933    const char *exten;
00934    int priority;
00935 #endif
00936 
00937    char *incstack[AST_PBX_MAX_STACK];      /* filled during the search */
00938    int stacklen;                   /* modified during the search */
00939    int status;                     /* set on return */
00940    struct ast_switch *swo;         /* set on return */
00941    const char *data;               /* set on return */
00942    const char *foundcontext;       /* set on return */
00943 };
00944 
00945 static struct ast_exten *pbx_find_extension(struct ast_channel *chan,
00946    struct ast_context *bypass, struct pbx_find_info *q,
00947    const char *context, const char *exten, int priority,
00948    const char *label, const char *callerid, enum ext_match_t action)
00949 {
00950    int x, res;
00951    struct ast_context *tmp;
00952    struct ast_exten *e, *eroot;
00953    struct ast_include *i;
00954    struct ast_sw *sw;
00955    char *tmpdata = NULL;
00956 
00957    /* Initialize status if appropriate */
00958    if (q->stacklen == 0) {
00959       q->status = STATUS_NO_CONTEXT;
00960       q->swo = NULL;
00961       q->data = NULL;
00962       q->foundcontext = NULL;
00963    }
00964    /* Check for stack overflow */
00965    if (q->stacklen >= AST_PBX_MAX_STACK) {
00966       ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
00967       return NULL;
00968    }
00969    /* Check first to see if we've already been checked */
00970    for (x = 0; x < q->stacklen; x++) {
00971       if (!strcasecmp(q->incstack[x], context))
00972          return NULL;
00973    }
00974    if (bypass) /* bypass means we only look there */
00975       tmp = bypass;
00976    else {   /* look in contexts */
00977       tmp = NULL;
00978       while ((tmp = ast_walk_contexts(tmp)) ) {
00979          if (!strcmp(tmp->name, context))
00980             break;
00981       }
00982       if (!tmp)
00983          return NULL;
00984    }
00985    if (q->status < STATUS_NO_EXTENSION)
00986       q->status = STATUS_NO_EXTENSION;
00987 
00988    /* scan the list trying to match extension and CID */
00989    eroot = NULL;
00990    while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
00991       int match = extension_match_core(eroot->exten, exten, action);
00992       /* 0 on fail, 1 on match, 2 on earlymatch */
00993 
00994       if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
00995          continue;   /* keep trying */
00996       if (match == 2 && action == E_MATCHMORE) {
00997          /* We match an extension ending in '!'.
00998           * The decision in this case is final and is NULL (no match).
00999           */
01000          return NULL;
01001       }
01002       /* found entry, now look for the right priority */
01003       if (q->status < STATUS_NO_PRIORITY)
01004          q->status = STATUS_NO_PRIORITY;
01005       e = NULL;
01006       while ( (e = ast_walk_extension_priorities(eroot, e)) ) {
01007          /* Match label or priority */
01008          if (action == E_FINDLABEL) {
01009             if (q->status < STATUS_NO_LABEL)
01010                q->status = STATUS_NO_LABEL;
01011             if (label && e->label && !strcmp(label, e->label))
01012                break;   /* found it */
01013          } else if (e->priority == priority) {
01014             break;   /* found it */
01015          } /* else keep searching */
01016       }
01017       if (e) { /* found a valid match */
01018          q->status = STATUS_SUCCESS;
01019          q->foundcontext = context;
01020          return e;
01021       }
01022    }
01023    /* Check alternative switches */
01024    AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
01025       struct ast_switch *asw = pbx_findswitch(sw->name);
01026       ast_switch_f *aswf = NULL;
01027       char *datap;
01028 
01029       if (!asw) {
01030          ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
01031          continue;
01032       }
01033       /* Substitute variables now */
01034       if (sw->eval) {
01035          if (!(tmpdata = ast_threadstorage_get(&switch_data, 512))) {
01036             ast_log(LOG_WARNING, "Can't evaluate switch?!");
01037             continue;
01038          }
01039          pbx_substitute_variables_helper(chan, sw->data, tmpdata, 512);
01040       }
01041 
01042       /* equivalent of extension_match_core() at the switch level */
01043       if (action == E_CANMATCH)
01044          aswf = asw->canmatch;
01045       else if (action == E_MATCHMORE)
01046          aswf = asw->matchmore;
01047       else /* action == E_MATCH */
01048          aswf = asw->exists;
01049       datap = sw->eval ? tmpdata : sw->data;
01050       if (!aswf)
01051          res = 0;
01052       else {
01053          if (chan)
01054             ast_autoservice_start(chan);
01055          res = aswf(chan, context, exten, priority, callerid, datap);
01056          if (chan)
01057             ast_autoservice_stop(chan);
01058       }
01059       if (res) {  /* Got a match */
01060          q->swo = asw;
01061          q->data = datap;
01062          q->foundcontext = context;
01063          /* XXX keep status = STATUS_NO_CONTEXT ? */
01064          return NULL;
01065       }
01066    }
01067    q->incstack[q->stacklen++] = tmp->name;   /* Setup the stack */
01068    /* Now try any includes we have in this context */
01069    for (i = tmp->includes; i; i = i->next) {
01070       if (include_valid(i)) {
01071          if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action)))
01072             return e;
01073          if (q->swo)
01074             return NULL;
01075       }
01076    }
01077    return NULL;
01078 }
01079 
01080 /*! \brief extract offset:length from variable name.
01081  * Returns 1 if there is a offset:length part, which is
01082  * trimmed off (values go into variables)
01083  */
01084 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
01085 {
01086    int parens=0;
01087 
01088    *offset = 0;
01089    *length = INT_MAX;
01090    *isfunc = 0;
01091    for (; *var; var++) {
01092       if (*var == '(') {
01093          (*isfunc)++;
01094          parens++;
01095       } else if (*var == ')') {
01096          parens--;
01097       } else if (*var == ':' && parens == 0) {
01098          *var++ = '\0';
01099          sscanf(var, "%d:%d", offset, length);
01100          return 1; /* offset:length valid */
01101       }
01102    }
01103    return 0;
01104 }
01105 
01106 /*! \brief takes a substring. It is ok to call with value == workspace.
01107  *
01108  * offset < 0 means start from the end of the string and set the beginning
01109  *   to be that many characters back.
01110  * length is the length of the substring.  A value less than 0 means to leave
01111  * that many off the end.
01112  * Always return a copy in workspace.
01113  */
01114 static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
01115 {
01116    char *ret = workspace;
01117    int lr;  /* length of the input string after the copy */
01118 
01119    ast_copy_string(workspace, value, workspace_len); /* always make a copy */
01120 
01121    lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
01122 
01123    /* Quick check if no need to do anything */
01124    if (offset == 0 && length >= lr) /* take the whole string */
01125       return ret;
01126 
01127    if (offset < 0)   {  /* translate negative offset into positive ones */
01128       offset = lr + offset;
01129       if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
01130          offset = 0;
01131    }
01132 
01133    /* too large offset result in empty string so we know what to return */
01134    if (offset >= lr)
01135       return ret + lr;  /* the final '\0' */
01136 
01137    ret += offset;    /* move to the start position */
01138    if (length >= 0 && length < lr - offset)  /* truncate if necessary */
01139       ret[length] = '\0';
01140    else if (length < 0) {
01141       if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
01142          ret[lr + length - offset] = '\0';
01143       else
01144          ret[0] = '\0';
01145    }
01146 
01147    return ret;
01148 }
01149 
01150 /*! \brief  pbx_retrieve_variable: Support for Asterisk built-in variables
01151   ---*/
01152 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
01153 {
01154    const char not_found = '\0';
01155    char *tmpvar;
01156    const char *s; /* the result */
01157    int offset, length;
01158    int i, need_substring;
01159    struct varshead *places[2] = { headp, &globals };  /* list of places where we may look */
01160 
01161    if (c) {
01162       ast_channel_lock(c);
01163       places[0] = &c->varshead;
01164    }
01165    /*
01166     * Make a copy of var because parse_variable_name() modifies the string.
01167     * Then if called directly, we might need to run substring() on the result;
01168     * remember this for later in 'need_substring', 'offset' and 'length'
01169     */
01170    tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
01171    need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
01172 
01173    /*
01174     * Look first into predefined variables, then into variable lists.
01175     * Variable 's' points to the result, according to the following rules:
01176     * s == &not_found (set at the beginning) means that we did not find a
01177     * matching variable and need to look into more places.
01178     * If s != &not_found, s is a valid result string as follows:
01179     * s = NULL if the variable does not have a value;
01180     * you typically do this when looking for an unset predefined variable.
01181     * s = workspace if the result has been assembled there;
01182     * typically done when the result is built e.g. with an snprintf(),
01183     * so we don't need to do an additional copy.
01184     * s != workspace in case we have a string, that needs to be copied
01185     * (the ast_copy_string is done once for all at the end).
01186     * Typically done when the result is already available in some string.
01187     */
01188    s = &not_found;   /* default value */
01189    if (c) { /* This group requires a valid channel */
01190       /* Names with common parts are looked up a piece at a time using strncmp. */
01191       if (!strncmp(var, "CALL", 4)) {
01192          if (!strncmp(var + 4, "ING", 3)) {
01193             if (!strcmp(var + 7, "PRES")) {        /* CALLINGPRES */
01194                snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);
01195                s = workspace;
01196             } else if (!strcmp(var + 7, "ANI2")) {    /* CALLINGANI2 */
01197                snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
01198                s = workspace;
01199             } else if (!strcmp(var + 7, "TON")) {     /* CALLINGTON */
01200                snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
01201                s = workspace;
01202             } else if (!strcmp(var + 7, "TNS")) {     /* CALLINGTNS */
01203                snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
01204                s = workspace;
01205             }
01206          }
01207       } else if (!strcmp(var, "HINT")) {
01208          s = ast_get_hint(workspace, workspacelen, NULL, 0, c, c->context, c->exten) ? workspace : NULL;
01209       } else if (!strcmp(var, "HINTNAME")) {
01210          s = ast_get_hint(NULL, 0, workspace, workspacelen, c, c->context, c->exten) ? workspace : NULL;
01211       } else if (!strcmp(var, "EXTEN")) {
01212          s = c->exten;
01213       } else if (!strcmp(var, "CONTEXT")) {
01214          s = c->context;
01215       } else if (!strcmp(var, "PRIORITY")) {
01216          snprintf(workspace, workspacelen, "%d", c->priority);
01217          s = workspace;
01218       } else if (!strcmp(var, "CHANNEL")) {
01219          s = c->name;
01220       } else if (!strcmp(var, "UNIQUEID")) {
01221          s = c->uniqueid;
01222       } else if (!strcmp(var, "HANGUPCAUSE")) {
01223          snprintf(workspace, workspacelen, "%d", c->hangupcause);
01224          s = workspace;
01225       }
01226    }
01227    if (s == &not_found) { /* look for more */
01228       if (!strcmp(var, "EPOCH")) {
01229          snprintf(workspace, workspacelen, "%u",(int)time(NULL));
01230          s = workspace;
01231       } else if (!strcmp(var, "SYSTEMNAME")) {
01232          s = ast_config_AST_SYSTEM_NAME;
01233       }
01234    }
01235    /* if not found, look into chanvars or global vars */
01236    for (i = 0; s == &not_found && i < (sizeof(places) / sizeof(places[0])); i++) {
01237       struct ast_var_t *variables;
01238       if (!places[i])
01239          continue;
01240       if (places[i] == &globals)
01241          ast_mutex_lock(&globalslock);
01242       AST_LIST_TRAVERSE(places[i], variables, entries) {
01243          if (strcasecmp(ast_var_name(variables), var)==0) {
01244             s = ast_var_value(variables);
01245             break;
01246          }
01247       }
01248       if (places[i] == &globals)
01249          ast_mutex_unlock(&globalslock);
01250    }
01251    if (s == &not_found || s == NULL)
01252       *ret = NULL;
01253    else {
01254       if (s != workspace)
01255          ast_copy_string(workspace, s, workspacelen);
01256       *ret = workspace;
01257       if (need_substring)
01258          *ret = substring(*ret, offset, length, workspace, workspacelen);
01259    }
01260 
01261    if (c)
01262       ast_channel_unlock(c);
01263 }
01264 
01265 /*! \brief CLI function to show installed custom functions
01266     \addtogroup CLI_functions
01267  */
01268 static int handle_show_functions_deprecated(int fd, int argc, char *argv[])
01269 {
01270    struct ast_custom_function *acf;
01271    int count_acf = 0;
01272    int like = 0;
01273 
01274    if (argc == 4 && (!strcmp(argv[2], "like")) ) {
01275       like = 1;
01276    } else if (argc != 2) {
01277       return RESULT_SHOWUSAGE;
01278    }
01279 
01280    ast_cli(fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
01281 
01282    AST_LIST_LOCK(&acf_root);
01283    AST_LIST_TRAVERSE(&acf_root, acf, acflist) {
01284       if (!like || strstr(acf->name, argv[3])) {
01285          count_acf++;
01286          ast_cli(fd, "%-20.20s  %-35.35s  %s\n", acf->name, acf->syntax, acf->synopsis);
01287       }
01288    }
01289    AST_LIST_UNLOCK(&acf_root);
01290 
01291    ast_cli(fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
01292 
01293    return RESULT_SUCCESS;
01294 }
01295 static int handle_show_functions(int fd, int argc, char *argv[])
01296 {
01297    struct ast_custom_function *acf;
01298    int count_acf = 0;
01299    int like = 0;
01300 
01301    if (argc == 5 && (!strcmp(argv[3], "like")) ) {
01302       like = 1;
01303    } else if (argc != 3) {
01304       return RESULT_SHOWUSAGE;
01305    }
01306 
01307    ast_cli(fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
01308 
01309    AST_LIST_LOCK(&acf_root);
01310    AST_LIST_TRAVERSE(&acf_root, acf, acflist) {
01311       if (!like || strstr(acf->name, argv[4])) {
01312          count_acf++;
01313          ast_cli(fd, "%-20.20s  %-35.35s  %s\n", acf->name, acf->syntax, acf->synopsis);
01314       }
01315    }
01316    AST_LIST_UNLOCK(&acf_root);
01317 
01318    ast_cli(fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
01319 
01320    return RESULT_SUCCESS;
01321 }
01322 
01323 static int handle_show_function_deprecated(int fd, int argc, char *argv[])
01324 {
01325    struct ast_custom_function *acf;
01326    /* Maximum number of characters added by terminal coloring is 22 */
01327    char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
01328    char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
01329    char stxtitle[40], *syntax = NULL;
01330    int synopsis_size, description_size, syntax_size;
01331 
01332    if (argc < 3)
01333       return RESULT_SHOWUSAGE;
01334 
01335    if (!(acf = ast_custom_function_find(argv[2]))) {
01336       ast_cli(fd, "No function by that name registered.\n");
01337       return RESULT_FAILURE;
01338 
01339    }
01340 
01341    if (acf->synopsis)
01342       synopsis_size = strlen(acf->synopsis) + 23;
01343    else
01344       synopsis_size = strlen("Not available") + 23;
01345    synopsis = alloca(synopsis_size);
01346 
01347    if (acf->desc)
01348       description_size = strlen(acf->desc) + 23;
01349    else
01350       description_size = strlen("Not available") + 23;
01351    description = alloca(description_size);
01352 
01353    if (acf->syntax)
01354       syntax_size = strlen(acf->syntax) + 23;
01355    else
01356       syntax_size = strlen("Not available") + 23;
01357    syntax = alloca(syntax_size);
01358 
01359    snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about function '%s' =- \n\n", acf->name);
01360    term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
01361    term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
01362    term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
01363    term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
01364    term_color(syntax,
01365          acf->syntax ? acf->syntax : "Not available",
01366          COLOR_CYAN, 0, syntax_size);
01367    term_color(synopsis,
01368          acf->synopsis ? acf->synopsis : "Not available",
01369          COLOR_CYAN, 0, synopsis_size);
01370    term_color(description,
01371          acf->desc ? acf->desc : "Not available",
01372          COLOR_CYAN, 0, description_size);
01373 
01374    ast_cli(fd,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle, stxtitle, syntax, syntitle, synopsis, destitle, description);
01375 
01376    return RESULT_SUCCESS;
01377 }
01378 
01379 static int handle_show_function(int fd, int argc, char *argv[])
01380 {
01381    struct ast_custom_function *acf;
01382    /* Maximum number of characters added by terminal coloring is 22 */
01383    char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
01384    char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
01385    char stxtitle[40], *syntax = NULL;
01386    int synopsis_size, description_size, syntax_size;
01387 
01388    if (argc < 4)
01389       return RESULT_SHOWUSAGE;
01390 
01391    if (!(acf = ast_custom_function_find(argv[3]))) {
01392       ast_cli(fd, "No function by that name registered.\n");
01393       return RESULT_FAILURE;
01394 
01395    }
01396 
01397    if (acf->synopsis)
01398       synopsis_size = strlen(acf->synopsis) + 23;
01399    else
01400       synopsis_size = strlen("Not available") + 23;
01401    synopsis = alloca(synopsis_size);
01402 
01403    if (acf->desc)
01404       description_size = strlen(acf->desc) + 23;
01405    else
01406       description_size = strlen("Not available") + 23;
01407    description = alloca(description_size);
01408 
01409    if (acf->syntax)
01410       syntax_size = strlen(acf->syntax) + 23;
01411    else
01412       syntax_size = strlen("Not available") + 23;
01413    syntax = alloca(syntax_size);
01414 
01415    snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about function '%s' =- \n\n", acf->name);
01416    term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
01417    term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
01418    term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
01419    term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
01420    term_color(syntax,
01421          acf->syntax ? acf->syntax : "Not available",
01422          COLOR_CYAN, 0, syntax_size);
01423    term_color(synopsis,
01424          acf->synopsis ? acf->synopsis : "Not available",
01425          COLOR_CYAN, 0, synopsis_size);
01426    term_color(description,
01427          acf->desc ? acf->desc : "Not available",
01428          COLOR_CYAN, 0, description_size);
01429 
01430    ast_cli(fd,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle, stxtitle, syntax, syntitle, synopsis, destitle, description);
01431 
01432    return RESULT_SUCCESS;
01433 }
01434 
01435 static char *complete_show_function(const char *line, const char *word, int pos, int state)
01436 {
01437    struct ast_custom_function *acf;
01438    char *ret = NULL;
01439    int which = 0;
01440    int wordlen = strlen(word);
01441 
01442    /* case-insensitive for convenience in this 'complete' function */
01443    AST_LIST_LOCK(&acf_root);
01444    AST_LIST_TRAVERSE(&acf_root, acf, acflist) {
01445       if (!strncasecmp(word, acf->name, wordlen) && ++which > state) {
01446          ret = strdup(acf->name);
01447          break;
01448       }
01449    }
01450    AST_LIST_UNLOCK(&acf_root);
01451 
01452    return ret;
01453 }
01454 
01455 struct ast_custom_function *ast_custom_function_find(const char *name)
01456 {
01457    struct ast_custom_function *acf = NULL;
01458 
01459    AST_LIST_LOCK(&acf_root);
01460    AST_LIST_TRAVERSE(&acf_root, acf, acflist) {
01461       if (!strcmp(name, acf->name))
01462          break;
01463    }
01464    AST_LIST_UNLOCK(&acf_root);
01465 
01466    return acf;
01467 }
01468 
01469 int ast_custom_function_unregister(struct ast_custom_function *acf)
01470 {
01471    struct ast_custom_function *cur;
01472 
01473    if (!acf)
01474       return -1;
01475 
01476    AST_LIST_LOCK(&acf_root);
01477    AST_LIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
01478       if (cur == acf) {
01479          AST_LIST_REMOVE_CURRENT(&acf_root, acflist);
01480          if (option_verbose > 1)
01481             ast_verbose(VERBOSE_PREFIX_2 "Unregistered custom function %s\n", acf->name);
01482          break;
01483       }
01484    }
01485    AST_LIST_TRAVERSE_SAFE_END
01486    AST_LIST_UNLOCK(&acf_root);
01487 
01488    return acf ? 0 : -1;
01489 }
01490 
01491 int ast_custom_function_register(struct ast_custom_function *acf)
01492 {
01493    struct ast_custom_function *cur;
01494 
01495    if (!acf)
01496       return -1;
01497 
01498    AST_LIST_LOCK(&acf_root);
01499 
01500    if (ast_custom_function_find(acf->name)) {
01501       ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
01502       AST_LIST_UNLOCK(&acf_root);
01503       return -1;
01504    }
01505 
01506    /* Store in alphabetical order */
01507    AST_LIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
01508       if (strcasecmp(acf->name, cur->name) < 0) {
01509          AST_LIST_INSERT_BEFORE_CURRENT(&acf_root, acf, acflist);
01510          break;
01511       }
01512    }
01513    AST_LIST_TRAVERSE_SAFE_END
01514    if (!cur)
01515       AST_LIST_INSERT_TAIL(&acf_root, acf, acflist);
01516 
01517    AST_LIST_UNLOCK(&acf_root);
01518 
01519    if (option_verbose > 1)
01520       ast_verbose(VERBOSE_PREFIX_2 "Registered custom function %s\n", acf->name);
01521 
01522    return 0;
01523 }
01524 
01525 /*! \brief return a pointer to the arguments of the function,
01526  * and terminates the function name with '\\0'
01527  */
01528 static char *func_args(char *function)
01529 {
01530    char *args = strchr(function, '(');
01531 
01532    if (!args)
01533       ast_log(LOG_WARNING, "Function doesn't contain parentheses.  Assuming null argument.\n");
01534    else {
01535       char *p;
01536       *args++ = '\0';
01537       if ((p = strrchr(args, ')')) )
01538          *p = '\0';
01539       else
01540          ast_log(LOG_WARNING, "Can't find trailing parenthesis?\n");
01541    }
01542    return args;
01543 }
01544 
01545 int ast_func_read(struct ast_channel *chan, char *function, char *workspace, size_t len)
01546 {
01547    char *args = func_args(function);
01548    struct ast_custom_function *acfptr = ast_custom_function_find(function);
01549 
01550    if (acfptr == NULL)
01551       ast_log(LOG_ERROR, "Function %s not registered\n", function);
01552    else if (!acfptr->read)
01553       ast_log(LOG_ERROR, "Function %s cannot be read\n", function);
01554    else
01555       return acfptr->read(chan, function, args, workspace, len);
01556    return -1;
01557 }
01558 
01559 int ast_func_write(struct ast_channel *chan, char *function, const char *value)
01560 {
01561    char *args = func_args(function);
01562    struct ast_custom_function *acfptr = ast_custom_function_find(function);
01563 
01564    if (acfptr == NULL)
01565       ast_log(LOG_ERROR, "Function %s not registered\n", function);
01566    else if (!acfptr->write)
01567       ast_log(LOG_ERROR, "Function %s cannot be written to\n", function);
01568    else
01569       return acfptr->write(chan, function, args, value);
01570 
01571    return -1;
01572 }
01573 
01574 static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count)
01575 {
01576    /* Substitutes variables into cp2, based on string cp1, and assuming cp2 to be
01577       zero-filled */
01578    char *cp4;
01579    const char *tmp, *whereweare;
01580    int length, offset, offset2, isfunction;
01581    char *workspace = NULL;
01582    char *ltmp = NULL, *var = NULL;
01583    char *nextvar, *nextexp, *nextthing;
01584    char *vars, *vare;
01585    int pos, brackets, needsub, len;
01586 
01587    whereweare=tmp=cp1;
01588    while (!ast_strlen_zero(whereweare) && count) {
01589       /* Assume we're copying the whole remaining string */
01590       pos = strlen(whereweare);
01591       nextvar = NULL;
01592       nextexp = NULL;
01593       nextthing = strchr(whereweare, '$');
01594       if (nextthing) {
01595          switch(nextthing[1]) {
01596          case '{':
01597             nextvar = nextthing;
01598             pos = nextvar - whereweare;
01599             break;
01600          case '[':
01601             nextexp = nextthing;
01602             pos = nextexp - whereweare;
01603             break;
01604          default:
01605             pos = 1;
01606          }
01607       }
01608 
01609       if (pos) {
01610          /* Can't copy more than 'count' bytes */
01611          if (pos > count)
01612             pos = count;
01613 
01614          /* Copy that many bytes */
01615          memcpy(cp2, whereweare, pos);
01616 
01617          count -= pos;
01618          cp2 += pos;
01619          whereweare += pos;
01620       }
01621 
01622       if (nextvar) {
01623          /* We have a variable.  Find the start and end, and determine
01624             if we are going to have to recursively call ourselves on the
01625             contents */
01626          vars = vare = nextvar + 2;
01627          brackets = 1;
01628          needsub = 0;
01629 
01630          /* Find the end of it */
01631          while (brackets && *vare) {
01632             if ((vare[0] == '$') && (vare[1] == '{')) {
01633                needsub++;
01634             } else if (vare[0] == '{') {
01635                brackets++;
01636             } else if (vare[0] == '}') {
01637                brackets--;
01638             } else if ((vare[0] == '$') && (vare[1] == '['))
01639                needsub++;
01640             vare++;
01641          }
01642          if (brackets)
01643             ast_log(LOG_NOTICE, "Error in extension logic (missing '}')\n");
01644          len = vare - vars - 1;
01645 
01646          /* Skip totally over variable string */
01647          whereweare += (len + 3);
01648 
01649          if (!var)
01650             var = alloca(VAR_BUF_SIZE);
01651 
01652          /* Store variable name (and truncate) */
01653          ast_copy_string(var, vars, len + 1);
01654 
01655          /* Substitute if necessary */
01656          if (needsub) {
01657             if (!ltmp)
01658                ltmp = alloca(VAR_BUF_SIZE);
01659 
01660             memset(ltmp, 0, VAR_BUF_SIZE);
01661             pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
01662             vars = ltmp;
01663          } else {
01664             vars = var;
01665          }
01666 
01667          if (!workspace)
01668             workspace = alloca(VAR_BUF_SIZE);
01669 
01670          workspace[0] = '\0';
01671 
01672          parse_variable_name(vars, &offset, &offset2, &isfunction);
01673          if (isfunction) {
01674             /* Evaluate function */
01675             if (c || !headp)
01676                cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
01677             else {
01678                struct varshead old;
01679                struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/%p", vars);
01680                if (c) {
01681                   memcpy(&old, &c->varshead, sizeof(old));
01682                   memcpy(&c->varshead, headp, sizeof(c->varshead));
01683                   cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
01684                   /* Don't deallocate the varshead that was passed in */
01685                   memcpy(&c->varshead, &old, sizeof(c->varshead));
01686                   ast_channel_free(c);
01687                } else
01688                   ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
01689             }
01690 
01691             if (option_debug)
01692                ast_log(LOG_DEBUG, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
01693          } else {
01694             /* Retrieve variable value */
01695             pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
01696          }
01697          if (cp4) {
01698             cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
01699 
01700             length = strlen(cp4);
01701             if (length > count)
01702                length = count;
01703             memcpy(cp2, cp4, length);
01704             count -= length;
01705             cp2 += length;
01706          }
01707       } else if (nextexp) {
01708          /* We have an expression.  Find the start and end, and determine
01709             if we are going to have to recursively call ourselves on the
01710             contents */
01711          vars = vare = nextexp + 2;
01712          brackets = 1;
01713          needsub = 0;
01714 
01715          /* Find the end of it */
01716          while(brackets && *vare) {
01717             if ((vare[0] == '$') && (vare[1] == '[')) {
01718                needsub++;
01719                brackets++;
01720                vare++;
01721             } else if (vare[0] == '[') {
01722                brackets++;
01723             } else if (vare[0] == ']') {
01724                brackets--;
01725             } else if ((vare[0] == '$') && (vare[1] == '{')) {
01726                needsub++;
01727                vare++;
01728             }
01729             vare++;
01730          }
01731          if (brackets)
01732             ast_log(LOG_NOTICE, "Error in extension logic (missing ']')\n");
01733          len = vare - vars - 1;
01734 
01735          /* Skip totally over expression */
01736          whereweare += (len + 3);
01737 
01738          if (!var)
01739             var = alloca(VAR_BUF_SIZE);
01740 
01741          /* Store variable name (and truncate) */
01742          ast_copy_string(var, vars, len + 1);
01743 
01744          /* Substitute if necessary */
01745          if (needsub) {
01746             if (!ltmp)
01747                ltmp = alloca(VAR_BUF_SIZE);
01748 
01749             memset(ltmp, 0, VAR_BUF_SIZE);
01750             pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
01751             vars = ltmp;
01752          } else {
01753             vars = var;
01754          }
01755 
01756          length = ast_expr(vars, cp2, count);
01757 
01758          if (length) {
01759             if (option_debug)
01760                ast_log(LOG_DEBUG, "Expression result is '%s'\n", cp2);
01761             count -= length;
01762             cp2 += length;
01763          }
01764       }
01765    }
01766 }
01767 
01768 void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
01769 {
01770    pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count);
01771 }
01772 
01773 void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
01774 {
01775    pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count);
01776 }
01777 
01778 static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
01779 {
01780    memset(passdata, 0, datalen);
01781 
01782    /* No variables or expressions in e->data, so why scan it? */
01783    if (e->data && !strchr(e->data, '$') && !strstr(e->data,"${") && !strstr(e->data,"$[") && !strstr(e->data,"$(")) {
01784       ast_copy_string(passdata, e->data, datalen);
01785       return;
01786    }
01787 
01788    pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
01789 }
01790 
01791 /*! 
01792  * \brief The return value depends on the action:
01793  *
01794  * E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
01795  * and return 0 on failure, -1 on match;
01796  * E_FINDLABEL maps the label to a priority, and returns
01797  * the priority on success, ... XXX
01798  * E_SPAWN, spawn an application,
01799  * and return 0 on success, -1 on failure.
01800  *
01801  * \note The channel is auto-serviced in this function, because doing an extension
01802  * match may block for a long time.  For example, if the lookup has to use a network
01803  * dialplan switch, such as DUNDi or IAX2, it may take a while.  However, the channel
01804  * auto-service code will queue up any important signalling frames to be processed
01805  * after this is done.
01806  */
01807 static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
01808    const char *context, const char *exten, int priority,
01809    const char *label, const char *callerid, enum ext_match_t action)
01810 {
01811    struct ast_exten *e;
01812    struct ast_app *app;
01813    int res;
01814    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
01815    char passdata[EXT_DATA_SIZE];
01816 
01817    int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
01818 
01819    ast_rdlock_contexts();
01820    e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
01821    if (e) {
01822       if (matching_action) {
01823          ast_unlock_contexts();
01824          return -1;  /* success, we found it */
01825       } else if (action == E_FINDLABEL) { /* map the label to a priority */
01826          res = e->priority;
01827          ast_unlock_contexts();
01828          return res; /* the priority we were looking for */
01829       } else { /* spawn */
01830          app = pbx_findapp(e->app);
01831          ast_unlock_contexts();
01832          if (!app) {
01833             ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
01834             return -1;
01835          }
01836          if (c->context != context)
01837             ast_copy_string(c->context, context, sizeof(c->context));
01838          if (c->exten != exten)
01839             ast_copy_string(c->exten, exten, sizeof(c->exten));
01840          c->priority = priority;
01841          pbx_substitute_variables(passdata, sizeof(passdata), c, e);
01842          if (option_debug) {
01843             ast_log(LOG_DEBUG, "Launching '%s'\n", app->name);
01844          }
01845          if (option_verbose > 2) {
01846             char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE];
01847             ast_verbose( VERBOSE_PREFIX_3 "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
01848                exten, context, priority,
01849                term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
01850                term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
01851                term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
01852                "in new stack");
01853          }
01854          manager_event(EVENT_FLAG_CALL, "Newexten",
01855                "Channel: %s\r\n"
01856                "Context: %s\r\n"
01857                "Extension: %s\r\n"
01858                "Priority: %d\r\n"
01859                "Application: %s\r\n"
01860                "AppData: %s\r\n"
01861                "Uniqueid: %s\r\n",
01862                c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid);
01863          return pbx_exec(c, app, passdata);  /* 0 on success, -1 on failure */
01864       }
01865    } else if (q.swo) {  /* not found here, but in another switch */
01866       ast_unlock_contexts();
01867       if (matching_action) {
01868          return -1;
01869       } else {
01870          if (!q.swo->exec) {
01871             ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
01872             res = -1;
01873          }
01874          return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
01875       }
01876    } else { /* not found anywhere, see what happened */
01877       ast_unlock_contexts();
01878       switch (q.status) {
01879       case STATUS_NO_CONTEXT:
01880          if (!matching_action)
01881             ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", context);
01882          break;
01883       case STATUS_NO_EXTENSION:
01884          if (!matching_action)
01885             ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, context);
01886          break;
01887       case STATUS_NO_PRIORITY:
01888          if (!matching_action)
01889             ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, context);
01890          break;
01891       case STATUS_NO_LABEL:
01892          if (context)
01893             ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, context);
01894          break;
01895       default:
01896          if (option_debug)
01897             ast_log(LOG_DEBUG, "Shouldn't happen!\n");
01898       }
01899 
01900       return (matching_action) ? 0 : -1;
01901    }
01902 }
01903 
01904 /*! \brief  ast_hint_extension: Find hint for given extension in context */
01905 static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten)
01906 {
01907    struct ast_exten *e;
01908    struct pbx_find_info q = { .stacklen = 0 }; /* the rest is set in pbx_find_context */
01909 
01910    ast_rdlock_contexts();
01911    e = pbx_find_extension(c, NULL, &q, context, exten, PRIORITY_HINT, NULL, "", E_MATCH);
01912    ast_unlock_contexts();
01913 
01914    return e;
01915 }
01916 
01917 /*! \brief  ast_extensions_state2: Check state of extension by using hints */
01918 static int ast_extension_state2(struct ast_exten *e)
01919 {
01920    char hint[AST_MAX_EXTENSION];
01921    char *cur, *rest;
01922    int allunavailable = 1, allbusy = 1, allfree = 1, allonhold = 1;
01923    int busy = 0, inuse = 0, ring = 0;
01924 
01925    if (!e)
01926       return -1;
01927 
01928    ast_copy_string(hint, ast_get_extension_app(e), sizeof(hint));
01929 
01930    rest = hint;   /* One or more devices separated with a & character */
01931    while ( (cur = strsep(&rest, "&")) ) {
01932       int res = ast_device_state(cur);
01933       switch (res) {
01934       case AST_DEVICE_NOT_INUSE:
01935          allunavailable = 0;
01936          allbusy = 0;
01937          allonhold = 0;
01938          break;
01939       case AST_DEVICE_INUSE:
01940          inuse = 1;
01941          allunavailable = 0;
01942          allfree = 0;
01943          allonhold = 0;
01944          break;
01945       case AST_DEVICE_RINGING:
01946          ring = 1;
01947          allunavailable = 0;
01948          allfree = 0;
01949          allonhold = 0;
01950          break;
01951       case AST_DEVICE_RINGINUSE:
01952          inuse = 1;
01953          ring = 1;
01954          allunavailable = 0;
01955          allfree = 0;
01956          allonhold = 0;
01957          break;
01958       case AST_DEVICE_ONHOLD:
01959          allunavailable = 0;
01960          allfree = 0;
01961          break;
01962       case AST_DEVICE_BUSY:
01963          allunavailable = 0;
01964          allfree = 0;
01965          allonhold = 0;
01966          busy = 1;
01967          break;
01968       case AST_DEVICE_UNAVAILABLE:
01969       case AST_DEVICE_INVALID:
01970          allbusy = 0;
01971          allfree = 0;
01972          allonhold = 0;
01973          break;
01974       default:
01975          allunavailable = 0;
01976          allbusy = 0;
01977          allfree = 0;
01978          allonhold = 0;
01979       }
01980    }
01981 
01982    if (!inuse && ring)
01983       return AST_EXTENSION_RINGING;
01984    if (inuse && ring)
01985       return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING);
01986    if (inuse)
01987       return AST_EXTENSION_INUSE;
01988    if (allfree)
01989       return AST_EXTENSION_NOT_INUSE;
01990    if (allonhold)
01991       return AST_EXTENSION_ONHOLD;
01992    if (allbusy)
01993       return AST_EXTENSION_BUSY;
01994    if (allunavailable)
01995       return AST_EXTENSION_UNAVAILABLE;
01996    if (busy)
01997       return AST_EXTENSION_INUSE;
01998 
01999    return AST_EXTENSION_NOT_INUSE;
02000 }
02001 
02002 /*! \brief  ast_extension_state2str: Return extension_state as string */
02003 const char *ast_extension_state2str(int extension_state)
02004 {
02005    int i;
02006 
02007    for (i = 0; (i < (sizeof(extension_states) / sizeof(extension_states[0]))); i++) {
02008       if (extension_states[i].extension_state == extension_state)
02009          return extension_states[i].text;
02010    }
02011    return "Unknown";
02012 }
02013 
02014 /*! \brief  ast_extension_state: Check extension state for an extension by using hint */
02015 int ast_extension_state(struct ast_channel *c, const char *context, const char *exten)
02016 {
02017    struct ast_exten *e;
02018 
02019    e = ast_hint_extension(c, context, exten);   /* Do we have a hint for this extension ? */
02020    if (!e)
02021       return -1;           /* No hint, return -1 */
02022 
02023    return ast_extension_state2(e);        /* Check all devices in the hint */
02024 }
02025 
02026 void ast_hint_state_changed(const char *device)
02027 {
02028    struct ast_hint *hint;
02029 
02030    AST_LIST_LOCK(&hints);
02031 
02032    AST_LIST_TRAVERSE(&hints, hint, list) {
02033       struct ast_state_cb *cblist;
02034       char buf[AST_MAX_EXTENSION];
02035       char *parse = buf;
02036       char *cur;
02037       int state;
02038 
02039       ast_copy_string(buf, ast_get_extension_app(hint->exten), sizeof(buf));
02040       while ( (cur = strsep(&parse, "&")) ) {
02041          if (!strcasecmp(cur, device))
02042             break;
02043       }
02044       if (!cur)
02045          continue;
02046 
02047       /* Get device state for this hint */
02048       state = ast_extension_state2(hint->exten);
02049 
02050       if ((state == -1) || (state == hint->laststate))
02051          continue;
02052 
02053       /* Device state changed since last check - notify the watchers */
02054 
02055       /* For general callbacks */
02056       for (cblist = statecbs; cblist; cblist = cblist->next)
02057          cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
02058 
02059       /* For extension callbacks */
02060       for (cblist = hint->callbacks; cblist; cblist = cblist->next)
02061          cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
02062 
02063       hint->laststate = state;   /* record we saw the change */
02064    }
02065 
02066    AST_LIST_UNLOCK(&hints);
02067 }
02068 
02069 /*! \brief  ast_extension_state_add: Add watcher for extension states */
02070 int ast_extension_state_add(const char *context, const char *exten,
02071              ast_state_cb_type callback, void *data)
02072 {
02073    struct ast_hint *hint;
02074    struct ast_state_cb *cblist;
02075    struct ast_exten *e;
02076 
02077    /* If there's no context and extension:  add callback to statecbs list */
02078    if (!context && !exten) {
02079       AST_LIST_LOCK(&hints);
02080 
02081       for (cblist = statecbs; cblist; cblist = cblist->next) {
02082          if (cblist->callback == callback) {
02083             cblist->data = data;
02084             AST_LIST_UNLOCK(&hints);
02085             return 0;
02086          }
02087       }
02088 
02089       /* Now insert the callback */
02090       if (!(cblist = ast_calloc(1, sizeof(*cblist)))) {
02091          AST_LIST_UNLOCK(&hints);
02092          return -1;
02093       }
02094       cblist->id = 0;
02095       cblist->callback = callback;
02096       cblist->data = data;
02097 
02098       cblist->next = statecbs;
02099       statecbs = cblist;
02100 
02101       AST_LIST_UNLOCK(&hints);
02102       return 0;
02103    }
02104 
02105    if (!context || !exten)
02106       return -1;
02107 
02108    /* This callback type is for only one hint, so get the hint */
02109    e = ast_hint_extension(NULL, context, exten);
02110    if (!e) {
02111       return -1;
02112    }
02113 
02114    /* Find the hint in the list of hints */
02115    AST_LIST_LOCK(&hints);
02116 
02117    AST_LIST_TRAVERSE(&hints, hint, list) {
02118       if (hint->exten == e)
02119          break;
02120    }
02121 
02122    if (!hint) {
02123       /* We have no hint, sorry */
02124       AST_LIST_UNLOCK(&hints);
02125       return -1;
02126    }
02127 
02128    /* Now insert the callback in the callback list  */
02129    if (!(cblist = ast_calloc(1, sizeof(*cblist)))) {
02130       AST_LIST_UNLOCK(&hints);
02131       return -1;
02132    }
02133    cblist->id = stateid++;    /* Unique ID for this callback */
02134    cblist->callback = callback;  /* Pointer to callback routine */
02135    cblist->data = data;    /* Data for the callback */
02136 
02137    cblist->next = hint->callbacks;
02138    hint->callbacks = cblist;
02139 
02140    AST_LIST_UNLOCK(&hints);
02141    return cblist->id;
02142 }
02143 
02144 /*! \brief  ast_extension_state_del: Remove a watcher from the callback list */
02145 int ast_extension_state_del(int id, ast_state_cb_type callback)
02146 {
02147    struct ast_state_cb **p_cur = NULL; /* address of pointer to us */
02148    int ret = -1;
02149 
02150    if (!id && !callback)
02151       return -1;
02152 
02153    AST_LIST_LOCK(&hints);
02154 
02155    if (!id) {  /* id == 0 is a callback without extension */
02156       for (p_cur = &statecbs; *p_cur; p_cur = &(*p_cur)->next) {
02157          if ((*p_cur)->callback == callback)
02158             break;
02159       }
02160    } else { /* callback with extension, find the callback based on ID */
02161       struct ast_hint *hint;
02162       AST_LIST_TRAVERSE(&hints, hint, list) {
02163          for (p_cur = &hint->callbacks; *p_cur; p_cur = &(*p_cur)->next) {
02164             if ((*p_cur)->id == id)
02165                break;
02166          }
02167          if (*p_cur) /* found in the inner loop */
02168             break;
02169       }
02170    }
02171    if (p_cur && *p_cur) {
02172       struct ast_state_cb *cur = *p_cur;
02173       *p_cur = cur->next;
02174       free(cur);
02175       ret = 0;
02176    }
02177    AST_LIST_UNLOCK(&hints);
02178    return ret;
02179 }
02180 
02181 /*! \brief  ast_add_hint: Add hint to hint list, check initial extension state */
02182 static int ast_add_hint(struct ast_exten *e)
02183 {
02184    struct ast_hint *hint;
02185 
02186    if (!e)
02187       return -1;
02188 
02189    AST_LIST_LOCK(&hints);
02190 
02191    /* Search if hint exists, do nothing */
02192    AST_LIST_TRAVERSE(&hints, hint, list) {
02193       if (hint->exten == e) {
02194          AST_LIST_UNLOCK(&hints);
02195          if (option_debug > 1)
02196             ast_log(LOG_DEBUG, "HINTS: Not re-adding existing hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
02197          return -1;
02198       }
02199    }
02200 
02201    if (option_debug > 1)
02202       ast_log(LOG_DEBUG, "HINTS: Adding hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
02203 
02204    if (!(hint = ast_calloc(1, sizeof(*hint)))) {
02205       AST_LIST_UNLOCK(&hints);
02206       return -1;
02207    }
02208    /* Initialize and insert new item at the top */
02209    hint->exten = e;
02210    hint->laststate = ast_extension_state2(e);
02211    AST_LIST_INSERT_HEAD(&hints, hint, list);
02212 
02213    AST_LIST_UNLOCK(&hints);
02214    return 0;
02215 }
02216 
02217 /*! \brief  ast_change_hint: Change hint for an extension */
02218 static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne)
02219 {
02220    struct ast_hint *hint;
02221    int res = -1;
02222 
02223    AST_LIST_LOCK(&hints);
02224    AST_LIST_TRAVERSE(&hints, hint, list) {
02225       if (hint->exten == oe) {
02226             hint->exten = ne;
02227          res = 0;
02228          break;
02229       }
02230    }
02231    AST_LIST_UNLOCK(&hints);
02232 
02233    return res;
02234 }
02235 
02236 /*! \brief  ast_remove_hint: Remove hint from extension */
02237 static int ast_remove_hint(struct ast_exten *e)
02238 {
02239    /* Cleanup the Notifys if hint is removed */
02240    struct ast_hint *hint;
02241    struct ast_state_cb *cblist, *cbprev;
02242    int res = -1;
02243 
02244    if (!e)
02245       return -1;
02246 
02247    AST_LIST_LOCK(&hints);
02248    AST_LIST_TRAVERSE_SAFE_BEGIN(&hints, hint, list) {
02249       if (hint->exten == e) {
02250          cbprev = NULL;
02251          cblist = hint->callbacks;
02252          while (cblist) {
02253             /* Notify with -1 and remove all callbacks */
02254             cbprev = cblist;
02255             cblist = cblist->next;
02256             cbprev->callback(hint->exten->parent->name, hint->exten->exten, AST_EXTENSION_DEACTIVATED, cbprev->data);
02257             free(cbprev);
02258             }
02259             hint->callbacks = NULL;
02260          AST_LIST_REMOVE_CURRENT(&hints, list);
02261             free(hint);
02262             res = 0;
02263          break;
02264       }
02265    }
02266    AST_LIST_TRAVERSE_SAFE_END
02267    AST_LIST_UNLOCK(&hints);
02268 
02269    return res;
02270 }
02271 
02272 
02273 /*! \brief  ast_get_hint: Get hint for channel */
02274 int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten)
02275 {
02276    struct ast_exten *e = ast_hint_extension(c, context, exten);
02277 
02278    if (e) {
02279       if (hint)
02280          ast_copy_string(hint, ast_get_extension_app(e), hintsize);
02281       if (name) {
02282          const char *tmp = ast_get_extension_app_data(e);
02283          if (tmp)
02284             ast_copy_string(name, tmp, namesize);
02285       }
02286       return -1;
02287    }
02288    return 0;
02289 }
02290 
02291 int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
02292 {
02293    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCH);
02294 }
02295 
02296 int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid)
02297 {
02298    return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, E_FINDLABEL);
02299 }
02300 
02301 int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid)
02302 {
02303    return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, E_FINDLABEL);
02304 }
02305 
02306 int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
02307 {
02308    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_CANMATCH);
02309 }
02310 
02311 int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
02312 {
02313    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_MATCHMORE);
02314 }
02315 
02316 int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
02317 {
02318    return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, E_SPAWN);
02319 }
02320 
02321 /* helper function to set extension and priority */
02322 static void set_ext_pri(struct ast_channel *c, const char *exten, int pri)
02323 {
02324    ast_channel_lock(c);
02325    ast_copy_string(c->exten, exten, sizeof(c->exten));
02326    c->priority = pri;
02327    ast_channel_unlock(c);
02328 }
02329 
02330 /*!
02331  * \brief collect digits from the channel into the buffer,
02332  * return -1 on error, 0 on timeout or done.
02333  */
02334 static int collect_digits(struct ast_channel *c, int waittime, char *buf, int buflen, int pos)
02335 {
02336    int digit;
02337 
02338    buf[pos] = '\0';  /* make sure it is properly terminated */
02339    while (ast_matchmore_extension(c, c->context, buf, 1, c->cid.cid_num)) {
02340       /* As long as we're willing to wait, and as long as it's not defined,
02341          keep reading digits until we can't possibly get a right answer anymore.  */
02342       digit = ast_waitfordigit(c, waittime * 1000);
02343       if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
02344          c->_softhangup = 0;
02345       } else {
02346          if (!digit) /* No entry */
02347             break;
02348          if (digit < 0) /* Error, maybe a  hangup */
02349             return -1;
02350          if (pos < buflen - 1) { /* XXX maybe error otherwise ? */
02351             buf[pos++] = digit;
02352             buf[pos] = '\0';
02353          }
02354          waittime = c->pbx->dtimeout;
02355       }
02356    }
02357    return 0;
02358 }
02359 
02360 static int __ast_pbx_run(struct ast_channel *c)
02361 {
02362    int found = 0; /* set if we find at least one match */
02363    int res = 0;
02364    int autoloopflag;
02365    int error = 0;    /* set an error conditions */
02366 
02367    /* A little initial setup here */
02368    if (c->pbx) {
02369       ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
02370       /* XXX and now what ? */
02371       free(c->pbx);
02372    }
02373    if (!(c->pbx = ast_calloc(1, sizeof(*c->pbx))))
02374       return -1;
02375    /* Set reasonable defaults */
02376    c->pbx->rtimeout = 10;
02377    c->pbx->dtimeout = 5;
02378 
02379    autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP);   /* save value to restore at the end */
02380    ast_set_flag(c, AST_FLAG_IN_AUTOLOOP);
02381 
02382    /* Start by trying whatever the channel is set to */
02383    if (!ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
02384       /* If not successful fall back to 's' */
02385       if (option_verbose > 1)
02386          ast_verbose( VERBOSE_PREFIX_2 "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority);
02387       /* XXX the original code used the existing priority in the call to
02388        * ast_exists_extension(), and reset it to 1 afterwards.
02389        * I believe the correct thing is to set it to 1 immediately.
02390        */
02391       set_ext_pri(c, "s", 1);
02392       if (!ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
02393          /* JK02: And finally back to default if everything else failed */
02394          if (option_verbose > 1)
02395             ast_verbose( VERBOSE_PREFIX_2 "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority);
02396          ast_copy_string(c->context, "default", sizeof(c->context));
02397       }
02398    }
02399    for (;;) {
02400       char dst_exten[256]; /* buffer to accumulate digits */
02401       int pos = 0;      /* XXX should check bounds */
02402       int digit = 0;
02403 
02404       /* loop on priorities in this context/exten */
02405       while (ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
02406          found = 1;
02407          if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->cid.cid_num))) {
02408             /* Something bad happened, or a hangup has been requested. */
02409             if (strchr("0123456789ABCDEF*#", res)) {
02410                if (option_debug)
02411                   ast_log(LOG_DEBUG, "Oooh, got something to jump out with ('%c')!\n", res);
02412                pos = 0;
02413                dst_exten[pos++] = digit = res;
02414                dst_exten[pos] = '\0';
02415                break;
02416             }
02417             if (res == AST_PBX_KEEPALIVE) {
02418                if (option_debug)
02419                   ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
02420                if (option_verbose > 1)
02421                   ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
02422                error = 1;
02423                break;
02424             }
02425             if (option_debug)
02426                ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
02427             if (option_verbose > 1)
02428                ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
02429             if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
02430                c->_softhangup = 0;
02431             } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
02432                /* atimeout, nothing bad */
02433             } else {
02434                if (c->cdr)
02435                   ast_cdr_update(c);
02436                error = 1;
02437                break;
02438             }
02439          }
02440          if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
02441             c->_softhangup = 0;
02442          } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT && ast_exists_extension(c,c->context,"T",1,c->cid.cid_num)) {
02443             set_ext_pri(c, "T", 0); /* 0 will become 1 with the c->priority++; at the end */
02444             /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
02445             c->whentohangup = 0;
02446             c->_softhangup &= ~AST_SOFTHANGUP_TIMEOUT;
02447          } else if (c->_softhangup) {
02448             if (option_debug)
02449                ast_log(LOG_DEBUG, "Extension %s, priority %d returned normally even though call was hung up\n",
02450                   c->exten, c->priority);
02451             error = 1;
02452             break;
02453          }
02454          c->priority++;
02455       } /* end while  - from here on we can use 'break' to go out */
02456       if (error)
02457          break;
02458 
02459       /* XXX we get here on non-existing extension or a keypress or hangup ? */
02460 
02461       if (!ast_exists_extension(c, c->context, c->exten, 1, c->cid.cid_num)) {
02462          /* If there is no match at priority 1, it is not a valid extension anymore.
02463           * Try to continue at "i", 1 or exit if the latter does not exist.
02464           */
02465          if (ast_exists_extension(c, c->context, "i", 1, c->cid.cid_num)) {
02466             if (option_verbose > 2)
02467                ast_verbose(VERBOSE_PREFIX_3 "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
02468             pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten);
02469             set_ext_pri(c, "i", 1);
02470          } else {
02471             ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
02472                c->name, c->exten, c->context);
02473             error = 1; /* we know what to do with it */
02474             break;
02475          }
02476       } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
02477          /* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
02478          c->_softhangup = 0;
02479       } else { /* keypress received, get more digits for a full extension */
02480          int waittime = 0;
02481          if (digit)
02482             waittime = c->pbx->dtimeout;
02483          else if (!autofallthrough)
02484             waittime = c->pbx->rtimeout;
02485          if (!waittime) {
02486             const char *status = pbx_builtin_getvar_helper(c, "DIALSTATUS");
02487             if (!status)
02488                status = "UNKNOWN";
02489             if (option_verbose > 2)
02490                ast_verbose(VERBOSE_PREFIX_2 "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status);
02491             if (!strcasecmp(status, "CONGESTION"))
02492                res = pbx_builtin_congestion(c, "10");
02493             else if (!strcasecmp(status, "CHANUNAVAIL"))
02494                res = pbx_builtin_congestion(c, "10");
02495             else if (!strcasecmp(status, "BUSY"))
02496                res = pbx_builtin_busy(c, "10");
02497             error = 1; /* XXX disable message */
02498             break;   /* exit from the 'for' loop */
02499          }
02500 
02501          if (collect_digits(c, waittime, dst_exten, sizeof(dst_exten), pos))
02502             break;
02503          if (ast_exists_extension(c, c->context, dst_exten, 1, c->cid.cid_num)) /* Prepare the next cycle */
02504             set_ext_pri(c, dst_exten, 1);
02505          else {
02506             /* No such extension */
02507             if (!ast_strlen_zero(dst_exten)) {
02508                /* An invalid extension */
02509                if (ast_exists_extension(c, c->context, "i", 1, c->cid.cid_num)) {
02510                   if (option_verbose > 2)
02511                      ast_verbose( VERBOSE_PREFIX_3 "Invalid extension '%s' in context '%s' on %s\n", dst_exten, c->context, c->name);
02512                   pbx_builtin_setvar_helper(c, "INVALID_EXTEN", dst_exten);
02513                   set_ext_pri(c, "i", 1);
02514                } else {
02515                   ast_log(LOG_WARNING, "Invalid extension '%s', but no rule 'i' in context '%s'\n", dst_exten, c->context);
02516                   found = 1; /* XXX disable message */
02517                   break;
02518                }
02519             } else {
02520                /* A simple timeout */
02521                if (ast_exists_extension(c, c->context, "t", 1, c->cid.cid_num)) {
02522                   if (option_verbose > 2)
02523                      ast_verbose( VERBOSE_PREFIX_3 "Timeout on %s\n", c->name);
02524                   set_ext_pri(c, "t", 1);
02525                } else {
02526                   ast_log(LOG_WARNING, "Timeout, but no rule 't' in context '%s'\n", c->context);
02527                   found = 1; /* XXX disable message */
02528                   break;
02529                }
02530             }
02531          }
02532          if (c->cdr) {
02533             if (option_verbose > 2)
02534                ast_verbose(VERBOSE_PREFIX_2 "CDR updated on %s\n",c->name);
02535             ast_cdr_update(c);
02536          }
02537       }
02538    }
02539    if (!found && !error)
02540       ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
02541    if (res != AST_PBX_KEEPALIVE)
02542       ast_softhangup(c, c->hangupcause ? c->hangupcause : AST_CAUSE_NORMAL_CLEARING);
02543    if ((res != AST_PBX_KEEPALIVE) && !ast_test_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN) && ast_exists_extension(c, c->context, "h", 1, c->cid.cid_num)) {
02544       set_ext_pri(c, "h", 1);
02545       while(ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
02546          if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->cid.cid_num))) {
02547             /* Something bad happened, or a hangup has been requested. */
02548             if (option_debug)
02549                ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
02550             if (option_verbose > 1)
02551                ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
02552             break;
02553          }
02554          c->priority++;
02555       }
02556    }
02557    ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP);
02558    ast_clear_flag(c, AST_FLAG_BRIDGE_HANGUP_RUN); /* from one round to the next, make sure this gets cleared */
02559    pbx_destroy(c->pbx);
02560    c->pbx = NULL;
02561    if (res != AST_PBX_KEEPALIVE)
02562       ast_hangup(c);
02563    return 0;
02564 }
02565 
02566 /* Returns 0 on success, non-zero if call limit was reached */
02567 static int increase_call_count(const struct ast_channel *c)
02568 {
02569    int failed = 0;
02570    double curloadavg;
02571    ast_mutex_lock(&maxcalllock);
02572    if (option_maxcalls) {
02573       if (countcalls >= option_maxcalls) {
02574          ast_log(LOG_NOTICE, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name);
02575          failed = -1;
02576       }
02577    }
02578    if (option_maxload) {
02579       getloadavg(&curloadavg, 1);
02580       if (curloadavg >= option_maxload) {
02581          ast_log(LOG_NOTICE, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg);
02582          failed = -1;
02583       }
02584    }
02585    if (!failed)
02586       countcalls++;
02587    ast_mutex_unlock(&maxcalllock);
02588 
02589    return failed;
02590 }
02591 
02592 static void decrease_call_count(void)
02593 {
02594    ast_mutex_lock(&maxcalllock);
02595    if (countcalls > 0)
02596       countcalls--;
02597    ast_mutex_unlock(&maxcalllock);
02598 }
02599 
02600 static void destroy_exten(struct ast_exten *e)
02601 {
02602    if (e->priority == PRIORITY_HINT)
02603       ast_remove_hint(e);
02604 
02605    if (e->datad)
02606       e->datad(e->data);
02607    free(e);
02608 }
02609 
02610 static void *pbx_thread(void *data)
02611 {
02612    /* Oh joyeous kernel, we're a new thread, with nothing to do but
02613       answer this channel and get it going.
02614    */
02615    /* NOTE:
02616       The launcher of this function _MUST_ increment 'countcalls'
02617       before invoking the function; it will be decremented when the
02618       PBX has finished running on the channel
02619     */
02620    struct ast_channel *c = data;
02621 
02622    __ast_pbx_run(c);
02623    decrease_call_count();
02624 
02625    pthread_exit(NULL);
02626 
02627    return NULL;
02628 }
02629 
02630 enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
02631 {
02632    pthread_t t;
02633    pthread_attr_t attr;
02634 
02635    if (!c) {
02636       ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
02637       return AST_PBX_FAILED;
02638    }
02639 
02640    if (increase_call_count(c))
02641       return AST_PBX_CALL_LIMIT;
02642 
02643    /* Start a new thread, and get something handling this channel. */
02644    pthread_attr_init(&attr);
02645    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
02646    if (ast_pthread_create(&t, &attr, pbx_thread, c)) {
02647       ast_log(LOG_WARNING, "Failed to create new channel thread\n");
02648       pthread_attr_destroy(&attr);
02649       decrease_call_count();
02650       return AST_PBX_FAILED;
02651    }
02652    pthread_attr_destroy(&attr);
02653 
02654    return AST_PBX_SUCCESS;
02655 }
02656 
02657 enum ast_pbx_result ast_pbx_run(struct ast_channel *c)
02658 {
02659    enum ast_pbx_result res = AST_PBX_SUCCESS;
02660 
02661    if (increase_call_count(c))
02662       return AST_PBX_CALL_LIMIT;
02663 
02664    res = __ast_pbx_run(c);
02665    decrease_call_count();
02666 
02667    return res;
02668 }
02669 
02670 int ast_active_calls(void)
02671 {
02672    return countcalls;
02673 }
02674 
02675 int pbx_set_autofallthrough(int newval)
02676 {
02677    int oldval = autofallthrough;
02678    autofallthrough = newval;
02679    return oldval;
02680 }
02681 
02682 /* lookup for a context with a given name,
02683  * return with conlock held if found, NULL if not found
02684  */
02685 static struct ast_context *find_context_locked(const char *context)
02686 {
02687    struct ast_context *c = NULL;
02688 
02689    ast_rdlock_contexts();
02690    while ( (c = ast_walk_contexts(c)) ) {
02691       if (!strcmp(ast_get_context_name(c), context))
02692          return c;
02693    }
02694    ast_unlock_contexts();
02695 
02696    return NULL;
02697 }
02698 
02699 /*
02700  * This function locks contexts list by &conlist, search for the right context
02701  * structure, leave context list locked and call ast_context_remove_include2
02702  * which removes include, unlock contexts list and return ...
02703  */
02704 int ast_context_remove_include(const char *context, const char *include, const char *registrar)
02705 {
02706    int ret = -1;
02707    struct ast_context *c = find_context_locked(context);
02708 
02709    if (c) {
02710       /* found, remove include from this context ... */
02711       ret = ast_context_remove_include2(c, include, registrar);
02712       ast_unlock_contexts();
02713    }
02714    return ret;
02715 }
02716 
02717 /*
02718  * When we call this function, &conlock lock must be locked, because when
02719  * we giving *con argument, some process can remove/change this context
02720  * and after that there can be segfault.
02721  *
02722  * This function locks given context, removes include, unlock context and
02723  * return.
02724  */
02725 int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar)
02726 {
02727    struct ast_include *i, *pi = NULL;
02728    int ret = -1;
02729 
02730    ast_mutex_lock(&con->lock);
02731 
02732    /* find our include */
02733    for (i = con->includes; i; pi = i, i = i->next) {
02734       if (!strcmp(i->name, include) &&
02735             (!registrar || !strcmp(i->registrar, registrar))) {
02736          /* remove from list */
02737          if (pi)
02738             pi->next = i->next;
02739          else
02740             con->includes = i->next;
02741          /* free include and return */
02742          free(i);
02743          ret = 0;
02744          break;
02745       }
02746    }
02747 
02748    ast_mutex_unlock(&con->lock);
02749    return ret;
02750 }
02751 
02752 /*!
02753  * \note This function locks contexts list by &conlist, search for the rigt context
02754  * structure, leave context list locked and call ast_context_remove_switch2
02755  * which removes switch, unlock contexts list and return ...
02756  */
02757 int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar)
02758 {
02759    int ret = -1; /* default error return */
02760    struct ast_context *c = find_context_locked(context);
02761 
02762    if (c) {
02763       /* remove switch from this context ... */
02764       ret = ast_context_remove_switch2(c, sw, data, registrar);
02765       ast_unlock_contexts();
02766    }
02767    return ret;
02768 }
02769 
02770 /*!
02771  * \brief This function locks given context, removes switch, unlock context and
02772  * return.
02773  * \note When we call this function, &conlock lock must be locked, because when
02774  * we giving *con argument, some process can remove/change this context
02775  * and after that there can be segfault.
02776  *
02777  */
02778 int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar)
02779 {
02780    struct ast_sw *i;
02781    int ret = -1;
02782 
02783    ast_mutex_lock(&con->lock);
02784 
02785    /* walk switches */
02786    AST_LIST_TRAVERSE_SAFE_BEGIN(&con->alts, i, list) {
02787       if (!strcmp(i->name, sw) && !strcmp(i->data, data) &&
02788          (!registrar || !strcmp(i->registrar, registrar))) {
02789          /* found, remove from list */
02790          AST_LIST_REMOVE_CURRENT(&con->alts, list);
02791          free(i); /* free switch and return */
02792          ret = 0;
02793          break;
02794       }
02795    }
02796    AST_LIST_TRAVERSE_SAFE_END
02797 
02798    ast_mutex_unlock(&con->lock);
02799 
02800    return ret;
02801 }
02802 
02803 /*
02804  * \note This functions lock contexts list, search for the right context,
02805  * call ast_context_remove_extension2, unlock contexts list and return.
02806  * In this function we are using
02807  */
02808 int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
02809 {
02810    return ast_context_remove_extension_callerid(context, extension, priority, NULL, 0, registrar);
02811 }
02812 
02813 int ast_context_remove_extension_callerid(const char *context, const char *extension, int priority, const char *callerid, int matchcid, const char *registrar)
02814 {
02815    int ret = -1; /* default error return */
02816    struct ast_context *c = find_context_locked(context);
02817 
02818    if (c) { /* ... remove extension ... */
02819       ret = ast_context_remove_extension_callerid2(c, extension, priority, callerid, matchcid, registrar);
02820       ast_unlock_contexts();
02821    }
02822    return ret;
02823 }
02824 
02825 /*!
02826  * \brief This functionc locks given context, search for the right extension and
02827  * fires out all peer in this extensions with given priority. If priority
02828  * is set to 0, all peers are removed. After that, unlock context and
02829  * return.
02830  * \note When do you want to call this function, make sure that &conlock is locked,
02831  * because some process can handle with your *con context before you lock
02832  * it.
02833  *
02834  */
02835 int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar)
02836 {
02837    return ast_context_remove_extension_callerid2(con, extension, priority, NULL, 0, registrar);
02838 }
02839 
02840 int ast_context_remove_extension_callerid2(struct ast_context *con, const char *extension, int priority, const char *callerid, int matchcid, const char *registrar)
02841 {
02842    struct ast_exten *exten, *prev_exten = NULL;
02843    struct ast_exten *peer;
02844    struct ast_exten *previous_peer = NULL;
02845    struct ast_exten *next_peer = NULL;
02846    int found = 0;
02847 
02848    ast_mutex_lock(&con->lock);
02849 
02850    /* scan the extension list to find first matching extension-registrar */
02851    for (exten = con->root; exten; prev_exten = exten, exten = exten->next) {
02852       if (!strcmp(exten->exten, extension) &&
02853          (!registrar || !strcmp(exten->registrar, registrar)))
02854          break;
02855    }
02856    if (!exten) {
02857       /* we can't find right extension */
02858       ast_mutex_unlock(&con->lock);
02859       return -1;
02860    }
02861 
02862    /* scan the priority list to remove extension with exten->priority == priority */
02863    for (peer = exten, next_peer = exten->peer ? exten->peer : exten->next;
02864          peer && !strcmp(peer->exten, extension);
02865          peer = next_peer, next_peer = next_peer ? (next_peer->peer ? next_peer->peer : next_peer->next) : NULL) {
02866       if ((priority == 0 || peer->priority == priority) &&
02867             (!callerid || !matchcid || (matchcid && !strcmp(peer->cidmatch, callerid))) &&
02868             (!registrar || !strcmp(peer->registrar, registrar) )) {
02869          found = 1;
02870 
02871          /* we are first priority extension? */
02872          if (!previous_peer) {
02873             /*
02874              * We are first in the priority chain, so must update the extension chain.
02875              * The next node is either the next priority or the next extension
02876              */
02877             struct ast_exten *next_node = peer->peer ? peer->peer : peer->next;
02878 
02879             if (!prev_exten) {   /* change the root... */
02880                con->root = next_node;
02881             } else {
02882                prev_exten->next = next_node; /* unlink */
02883             }
02884             if (peer->peer)   { /* update the new head of the pri list */
02885                peer->peer->next = peer->next;
02886             }
02887          } else { /* easy, we are not first priority in extension */
02888             previous_peer->peer = peer->peer;
02889          }
02890 
02891          /* now, free whole priority extension */
02892          destroy_exten(peer);
02893       } else {
02894          previous_peer = peer;
02895       }
02896    }
02897    ast_mutex_unlock(&con->lock);
02898    return found ? 0 : -1;
02899 }
02900 
02901 
02902 /*!
02903  * \note This function locks contexts list by &conlist, searches for the right context
02904  * structure, and locks the macrolock mutex in that context.
02905  * macrolock is used to limit a macro to be executed by one call at a time.
02906  */
02907 int ast_context_lockmacro(const char *context)
02908 {
02909    struct ast_context *c = NULL;
02910    int ret = -1;
02911 
02912    ast_rdlock_contexts();
02913 
02914    while ((c = ast_walk_contexts(c))) {
02915       if (!strcmp(ast_get_context_name(c), context)) {
02916          ret = 0;
02917          break;
02918       }
02919    }
02920 
02921    ast_unlock_contexts();
02922 
02923    /* if we found context, lock macrolock */
02924    if (ret == 0) 
02925       ret = ast_mutex_lock(&c->macrolock);
02926 
02927    return ret;
02928 }
02929 
02930 /*!
02931  * \note This function locks contexts list by &conlist, searches for the right context
02932  * structure, and unlocks the macrolock mutex in that context.
02933  * macrolock is used to limit a macro to be executed by one call at a time.
02934  */
02935 int ast_context_unlockmacro(const char *context)
02936 {
02937    struct ast_context *c = NULL;
02938    int ret = -1;
02939 
02940    ast_rdlock_contexts();
02941 
02942    while ((c = ast_walk_contexts(c))) {
02943       if (!strcmp(ast_get_context_name(c), context)) {
02944          ret = 0;
02945          break;
02946       }
02947    }
02948 
02949    ast_unlock_contexts();
02950 
02951    /* if we found context, unlock macrolock */
02952    if (ret == 0) 
02953       ret = ast_mutex_unlock(&c->macrolock);
02954 
02955    return ret;
02956 }
02957 
02958 /*! \brief Dynamically register a new dial plan application */
02959 int ast_register_application(const char *app, int (*execute)(struct ast_channel *, void *), const char *synopsis, const char *description)
02960 {
02961    struct ast_app *tmp, *cur = NULL;
02962    char tmps[80];
02963    int length;
02964 
02965    AST_LIST_LOCK(&apps);
02966    AST_LIST_TRAVERSE(&apps, tmp, list) {
02967       if (!strcasecmp(app, tmp->name)) {
02968          ast_log(LOG_WARNING, "Already have an application '%s'\n", app);
02969          AST_LIST_UNLOCK(&apps);
02970          return -1;
02971       }
02972    }
02973 
02974    length = sizeof(*tmp) + strlen(app) + 1;
02975 
02976    if (!(tmp = ast_calloc(1, length))) {
02977       AST_LIST_UNLOCK(&apps);
02978       return -1;
02979    }
02980 
02981    strcpy(tmp->name, app);
02982    tmp->execute = execute;
02983    tmp->synopsis = synopsis;
02984    tmp->description = description;
02985 
02986    /* Store in alphabetical order */
02987    AST_LIST_TRAVERSE_SAFE_BEGIN(&apps, cur, list) {
02988       if (strcasecmp(tmp->name, cur->name) < 0) {
02989          AST_LIST_INSERT_BEFORE_CURRENT(&apps, tmp, list);
02990          break;
02991       }
02992    }
02993    AST_LIST_TRAVERSE_SAFE_END
02994    if (!cur)
02995       AST_LIST_INSERT_TAIL(&apps, tmp, list);
02996 
02997    if (option_verbose > 1)
02998       ast_verbose( VERBOSE_PREFIX_2 "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps)));
02999 
03000    AST_LIST_UNLOCK(&apps);
03001 
03002    return 0;
03003 }
03004 
03005 /*
03006  * Append to the list. We don't have a tail pointer because we need
03007  * to scan the list anyways to check for duplicates during insertion.
03008  */
03009 int ast_register_switch(struct ast_switch *sw)
03010 {
03011    struct ast_switch *tmp;
03012 
03013    AST_LIST_LOCK(&switches);
03014    AST_LIST_TRAVERSE(&switches, tmp, list) {
03015       if (!strcasecmp(tmp->name, sw->name)) {
03016          AST_LIST_UNLOCK(&switches);
03017          ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
03018          return -1;
03019       }
03020    }
03021    AST_LIST_INSERT_TAIL(&switches, sw, list);
03022    AST_LIST_UNLOCK(&switches);
03023 
03024    return 0;
03025 }
03026 
03027 void ast_unregister_switch(struct ast_switch *sw)
03028 {
03029    AST_LIST_LOCK(&switches);
03030    AST_LIST_REMOVE(&switches, sw, list);
03031    AST_LIST_UNLOCK(&switches);
03032 }
03033 
03034 /*
03035  * Help for CLI commands ...
03036  */
03037 static char show_applications_help[] =
03038 "Usage: core show applications [{like|describing} <text>]\n"
03039 "       List applications which are currently available.\n"
03040 "       If 'like', <text> will be a substring of the app name\n"
03041 "       If 'describing', <text> will be a substring of the description\n";
03042 
03043 static char show_functions_help[] =
03044 "Usage: core show functions [like <text>]\n"
03045 "       List builtin functions, optionally only those matching a given string\n";
03046 
03047 static char show_switches_help[] =
03048 "Usage: core show switches\n"
03049 "       List registered switches\n";
03050 
03051 static char show_hints_help[] =
03052 "Usage: core show hints\n"
03053 "       List registered hints\n";
03054 
03055 static char show_globals_help[] =
03056 "Usage: core show globals\n"
03057 "       List current global dialplan variables and their values\n";
03058 
03059 static char show_application_help[] =
03060 "Usage: core show application <application> [<application> [<application> [...]]]\n"
03061 "       Describes a particular application.\n";
03062 
03063 static char show_function_help[] =
03064 "Usage: core show function <function>\n"
03065 "       Describe a particular dialplan function.\n";
03066 
03067 static char show_dialplan_help[] =
03068 "Usage: dialplan show [exten@][context]\n"
03069 "       Show dialplan\n";
03070 
03071 static char set_global_help[] =
03072 "Usage: core set global <name> <value>\n"
03073 "       Set global dialplan variable <name> to <value>\n";
03074 
03075 
03076 /*
03077  * \brief 'show application' CLI command implementation functions ...
03078  */
03079 
03080 /*
03081  * There is a possibility to show informations about more than one
03082  * application at one time. You can type 'show application Dial Echo' and
03083  * you will see informations about these two applications ...
03084  */
03085 static char *complete_show_application(const char *line, const char *word, int pos, int state)
03086 {
03087    struct ast_app *a;
03088    char *ret = NULL;
03089    int which = 0;
03090    int wordlen = strlen(word);
03091 
03092    /* return the n-th [partial] matching entry */
03093    AST_LIST_LOCK(&apps);
03094    AST_LIST_TRAVERSE(&apps, a, list) {
03095       if (!strncasecmp(word, a->name, wordlen) && ++which > state) {
03096          ret = strdup(a->name);
03097          break;
03098       }
03099    }
03100    AST_LIST_UNLOCK(&apps);
03101 
03102    return ret;
03103 }
03104 
03105 static int handle_show_application_deprecated(int fd, int argc, char *argv[])
03106 {
03107    struct ast_app *a;
03108    int app, no_registered_app = 1;
03109 
03110    if (argc < 3)
03111       return RESULT_SHOWUSAGE;
03112 
03113    /* ... go through all applications ... */
03114    AST_LIST_LOCK(&apps);
03115    AST_LIST_TRAVERSE(&apps, a, list) {
03116       /* ... compare this application name with all arguments given
03117        * to 'show application' command ... */
03118       for (app = 2; app < argc; app++) {
03119          if (!strcasecmp(a->name, argv[app])) {
03120             /* Maximum number of characters added by terminal coloring is 22 */
03121             char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
03122             char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
03123             int synopsis_size, description_size;
03124 
03125             no_registered_app = 0;
03126 
03127             if (a->synopsis)
03128                synopsis_size = strlen(a->synopsis) + 23;
03129             else
03130                synopsis_size = strlen("Not available") + 23;
03131             synopsis = alloca(synopsis_size);
03132 
03133             if (a->description)
03134                description_size = strlen(a->description) + 23;
03135             else
03136                description_size = strlen("Not available") + 23;
03137             description = alloca(description_size);
03138 
03139             if (synopsis && description) {
03140                snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about application '%s' =- \n\n", a->name);
03141                term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
03142                term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
03143                term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
03144                term_color(synopsis,
03145                            a->synopsis ? a->synopsis : "Not available",
03146                            COLOR_CYAN, 0, synopsis_size);
03147                term_color(description,
03148                            a->description ? a->description : "Not available",
03149                            COLOR_CYAN, 0, description_size);
03150 
03151                ast_cli(fd,"%s%s%s\n\n%s%s\n", infotitle, syntitle, synopsis, destitle, description);
03152             } else {
03153                /* ... one of our applications, show info ...*/
03154                ast_cli(fd,"\n  -= Info about application '%s' =- \n\n"
03155                   "[Synopsis]\n  %s\n\n"
03156                   "[Description]\n%s\n",
03157                   a->name,
03158                   a->synopsis ? a->synopsis : "Not available",
03159                   a->description ? a->description : "Not available");
03160             }
03161          }
03162       }
03163    }
03164    AST_LIST_UNLOCK(&apps);
03165 
03166    /* we found at least one app? no? */
03167    if (no_registered_app) {
03168       ast_cli(fd, "Your application(s) is (are) not registered\n");
03169       return RESULT_FAILURE;
03170    }
03171 
03172    return RESULT_SUCCESS;
03173 }
03174 
03175 static int handle_show_application(int fd, int argc, char *argv[])
03176 {
03177    struct ast_app *a;
03178    int app, no_registered_app = 1;
03179 
03180    if (argc < 4)
03181       return RESULT_SHOWUSAGE;
03182 
03183    /* ... go through all applications ... */
03184    AST_LIST_LOCK(&apps);
03185    AST_LIST_TRAVERSE(&apps, a, list) {
03186       /* ... compare this application name with all arguments given
03187        * to 'show application' command ... */
03188       for (app = 3; app < argc; app++) {
03189          if (!strcasecmp(a->name, argv[app])) {
03190             /* Maximum number of characters added by terminal coloring is 22 */
03191             char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
03192             char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
03193             int synopsis_size, description_size;
03194 
03195             no_registered_app = 0;
03196 
03197             if (a->synopsis)
03198                synopsis_size = strlen(a->synopsis) + 23;
03199             else
03200                synopsis_size = strlen("Not available") + 23;
03201             synopsis = alloca(synopsis_size);
03202 
03203             if (a->description)
03204                description_size = strlen(a->description) + 23;
03205             else
03206                description_size = strlen("Not available") + 23;
03207             description = alloca(description_size);
03208 
03209             if (synopsis && description) {
03210                snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about application '%s' =- \n\n", a->name);
03211                term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
03212                term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
03213                term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
03214                term_color(synopsis,
03215                            a->synopsis ? a->synopsis : "Not available",
03216                            COLOR_CYAN, 0, synopsis_size);
03217                term_color(description,
03218                            a->description ? a->description : "Not available",
03219                            COLOR_CYAN, 0, description_size);
03220 
03221                ast_cli(fd,"%s%s%s\n\n%s%s\n", infotitle, syntitle, synopsis, destitle, description);
03222             } else {
03223                /* ... one of our applications, show info ...*/
03224                ast_cli(fd,"\n  -= Info about application '%s' =- \n\n"
03225                   "[Synopsis]\n  %s\n\n"
03226                   "[Description]\n%s\n",
03227                   a->name,
03228                   a->synopsis ? a->synopsis : "Not available",
03229                   a->description ? a->description : "Not available");
03230             }
03231          }
03232       }
03233    }
03234    AST_LIST_UNLOCK(&apps);
03235 
03236    /* we found at least one app? no? */
03237    if (no_registered_app) {
03238       ast_cli(fd, "Your application(s) is (are) not registered\n");
03239       return RESULT_FAILURE;
03240    }
03241 
03242    return RESULT_SUCCESS;
03243 }
03244 
03245 /*! \brief  handle_show_hints: CLI support for listing registred dial plan hints */
03246 static int handle_show_hints(int fd, int argc, char *argv[])
03247 {
03248    struct ast_hint *hint;
03249    int num = 0;
03250    int watchers;
03251    struct ast_state_cb *watcher;
03252 
03253    if (AST_LIST_EMPTY(&hints)) {
03254       ast_cli(fd, "There are no registered dialplan hints\n");
03255       return RESULT_SUCCESS;
03256    }
03257    /* ... we have hints ... */
03258    ast_cli(fd, "\n    -= Registered Asterisk Dial Plan Hints =-\n");
03259    AST_LIST_LOCK(&hints);
03260    AST_LIST_TRAVERSE(&hints, hint, list) {
03261       watchers = 0;
03262       for (watcher = hint->callbacks; watcher; watcher = watcher->next)
03263          watchers++;
03264       ast_cli(fd, "   %20s@%-20.20s: %-20.20s  State:%-15.15s Watchers %2d\n",
03265          ast_get_extension_name(hint->exten),
03266          ast_get_context_name(ast_get_extension_context(hint->exten)),
03267          ast_get_extension_app(hint->exten),
03268          ast_extension_state2str(hint->laststate), watchers);
03269       num++;
03270    }
03271    ast_cli(fd, "----------------\n");
03272    ast_cli(fd, "- %d hints registered\n", num);
03273    AST_LIST_UNLOCK(&hints);
03274    return RESULT_SUCCESS;
03275 }
03276 
03277 /*! \brief  handle_show_switches: CLI support for listing registred dial plan switches */
03278 static int handle_show_switches(int fd, int argc, char *argv[])
03279 {
03280    struct ast_switch *sw;
03281 
03282    AST_LIST_LOCK(&switches);
03283 
03284    if (AST_LIST_EMPTY(&switches)) {
03285       AST_LIST_UNLOCK(&switches);
03286       ast_cli(fd, "There are no registered alternative switches\n");
03287       return RESULT_SUCCESS;
03288    }
03289 
03290    ast_cli(fd, "\n    -= Registered Asterisk Alternative Switches =-\n");
03291    AST_LIST_TRAVERSE(&switches, sw, list)
03292       ast_cli(fd, "%s: %s\n", sw->name, sw->description);
03293 
03294    AST_LIST_UNLOCK(&switches);
03295 
03296    return RESULT_SUCCESS;
03297 }
03298 
03299 /*
03300  * 'show applications' CLI command implementation functions ...
03301  */
03302 static int handle_show_applications_deprecated(int fd, int argc, char *argv[])
03303 {
03304    struct ast_app *a;
03305    int like = 0, describing = 0;
03306    int total_match = 0;    /* Number of matches in like clause */
03307    int total_apps = 0;  /* Number of apps registered */
03308 
03309    AST_LIST_LOCK(&apps);
03310 
03311    if (AST_LIST_EMPTY(&apps)) {
03312       ast_cli(fd, "There are no registered applications\n");
03313       AST_LIST_UNLOCK(&apps);
03314       return -1;
03315    }
03316 
03317    /* show applications like <keyword> */
03318    if ((argc == 4) && (!strcmp(argv[2], "like"))) {
03319       like = 1;
03320    } else if ((argc > 3) && (!strcmp(argv[2], "describing"))) {
03321       describing = 1;
03322    }
03323 
03324    /* show applications describing <keyword1> [<keyword2>] [...] */
03325    if ((!like) && (!describing)) {
03326       ast_cli(fd, "    -= Registered Asterisk Applications =-\n");
03327    } else {
03328       ast_cli(fd, "    -= Matching Asterisk Applications =-\n");
03329    }
03330 
03331    AST_LIST_TRAVERSE(&apps, a, list) {
03332       int printapp = 0;
03333       total_apps++;
03334       if (like) {
03335          if (strcasestr(a->name, argv[3])) {
03336             printapp = 1;
03337             total_match++;
03338          }
03339       } else if (describing) {
03340          if (a->description) {
03341             /* Match all words on command line */
03342             int i;
03343             printapp = 1;
03344             for (i = 3; i < argc; i++) {
03345                if (!strcasestr(a->description, argv[i])) {
03346                   printapp = 0;
03347                } else {
03348                   total_match++;
03349                }
03350             }
03351          }
03352       } else {
03353          printapp = 1;
03354       }
03355 
03356       if (printapp) {
03357          ast_cli(fd,"  %20s: %s\n", a->name, a->synopsis ? a->synopsis : "<Synopsis not available>");
03358       }
03359    }
03360    if ((!like) && (!describing)) {
03361       ast_cli(fd, "    -= %d Applications Registered =-\n",total_apps);
03362    } else {
03363       ast_cli(fd, "    -= %d Applications Matching =-\n",total_match);
03364    }
03365 
03366    AST_LIST_UNLOCK(&apps);
03367 
03368    return RESULT_SUCCESS;
03369 }
03370 static int handle_show_applications(int fd, int argc, char *argv[])
03371 {
03372    struct ast_app *a;
03373    int like = 0, describing = 0;
03374    int total_match = 0;    /* Number of matches in like clause */
03375    int total_apps = 0;  /* Number of apps registered */
03376 
03377    AST_LIST_LOCK(&apps);
03378 
03379    if (AST_LIST_EMPTY(&apps)) {
03380       ast_cli(fd, "There are no registered applications\n");
03381       AST_LIST_UNLOCK(&apps);
03382       return -1;
03383    }
03384 
03385    /* core list applications like <keyword> */
03386    if ((argc == 5) && (!strcmp(argv[3], "like"))) {
03387       like = 1;
03388    } else if ((argc > 4) && (!strcmp(argv[3], "describing"))) {
03389       describing = 1;
03390    }
03391 
03392    /* core list applications describing <keyword1> [<keyword2>] [...] */
03393    if ((!like) && (!describing)) {
03394       ast_cli(fd, "    -= Registered Asterisk Applications =-\n");
03395    } else {
03396       ast_cli(fd, "    -= Matching Asterisk Applications =-\n");
03397    }
03398 
03399    AST_LIST_TRAVERSE(&apps, a, list) {
03400       int printapp = 0;
03401       total_apps++;
03402       if (like) {
03403          if (strcasestr(a->name, argv[4])) {
03404             printapp = 1;
03405             total_match++;
03406          }
03407       } else if (describing) {
03408          if (a->description) {
03409             /* Match all words on command line */
03410             int i;
03411             printapp = 1;
03412             for (i = 4; i < argc; i++) {
03413                if (!strcasestr(a->description, argv[i])) {
03414                   printapp = 0;
03415                } else {
03416                   total_match++;
03417                }
03418             }
03419          }
03420       } else {
03421          printapp = 1;
03422       }
03423 
03424       if (printapp) {
03425          ast_cli(fd,"  %20s: %s\n", a->name, a->synopsis ? a->synopsis : "<Synopsis not available>");
03426       }
03427    }
03428    if ((!like) && (!describing)) {
03429       ast_cli(fd, "    -= %d Applications Registered =-\n",total_apps);
03430    } else {
03431       ast_cli(fd, "    -= %d Applications Matching =-\n",total_match);
03432    }
03433 
03434    AST_LIST_UNLOCK(&apps);
03435 
03436    return RESULT_SUCCESS;
03437 }
03438 
03439 static char *complete_show_applications_deprecated(const char *line, const char *word, int pos, int state)
03440 {
03441    static char* choices[] = { "like", "describing", NULL };
03442 
03443    return (pos != 2) ? NULL : ast_cli_complete(word, choices, state);
03444 }
03445 
03446 static char *complete_show_applications(const char *line, const char *word, int pos, int state)
03447 {
03448    static char* choices[] = { "like", "describing", NULL };
03449 
03450    return (pos != 3) ? NULL : ast_cli_complete(word, choices, state);
03451 }
03452 
03453 /*
03454  * 'show dialplan' CLI command implementation functions ...
03455  */
03456 static char *complete_show_dialplan_context(const char *line, const char *word, int pos,
03457    int state)
03458 {
03459    struct ast_context *c = NULL;
03460    char *ret = NULL;
03461    int which = 0;
03462    int wordlen;
03463 
03464    /* we are do completion of [exten@]context on second position only */
03465    if (pos != 2)
03466       return NULL;
03467 
03468    ast_rdlock_contexts();
03469 
03470    wordlen = strlen(word);
03471 
03472    /* walk through all contexts and return the n-th match */
03473    while ( (c = ast_walk_contexts(c)) ) {
03474       if (!strncasecmp(word, ast_get_context_name(c), wordlen) && ++which > state) {
03475          ret = ast_strdup(ast_get_context_name(c));
03476          break;
03477       }
03478    }
03479 
03480    ast_unlock_contexts();
03481 
03482    return ret;
03483 }
03484 
03485 struct dialplan_counters {
03486    int total_context;
03487    int total_exten;
03488    int total_prio;
03489    int context_existence;
03490    int extension_existence;
03491 };
03492 
03493 /*! \brief helper function to print an extension */
03494 static void print_ext(struct ast_exten *e, char * buf, int buflen)
03495 {
03496    int prio = ast_get_extension_priority(e);
03497    if (prio == PRIORITY_HINT) {
03498       snprintf(buf, buflen, "hint: %s",
03499          ast_get_extension_app(e));
03500    } else {
03501       snprintf(buf, buflen, "%d. %s(%s)",
03502          prio, ast_get_extension_app(e),
03503          (!ast_strlen_zero(ast_get_extension_app_data(e)) ? (char *)ast_get_extension_app_data(e) : ""));
03504    }
03505 }
03506 
03507 /* XXX not verified */
03508 static int show_dialplan_helper(int fd, const char *context, const char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, const char *includes[])
03509 {
03510    struct ast_context *c = NULL;
03511    int res = 0, old_total_exten = dpc->total_exten;
03512 
03513    ast_rdlock_contexts();
03514 
03515    /* walk all contexts ... */
03516    while ( (c = ast_walk_contexts(c)) ) {
03517       struct ast_exten *e;
03518       struct ast_include *i;
03519       struct ast_ignorepat *ip;
03520       char buf[256], buf2[256];
03521       int context_info_printed = 0;
03522 
03523       if (context && strcmp(ast_get_context_name(c), context))
03524          continue;   /* skip this one, name doesn't match */
03525 
03526       dpc->context_existence = 1;
03527 
03528       ast_lock_context(c);
03529 
03530       /* are we looking for exten too? if yes, we print context
03531        * only if we find our extension.
03532        * Otherwise print context even if empty ?
03533        * XXX i am not sure how the rinclude is handled.
03534        * I think it ought to go inside.
03535        */
03536       if (!exten) {
03537          dpc->total_context++;
03538          ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
03539             ast_get_context_name(c), ast_get_context_registrar(c));
03540          context_info_printed = 1;
03541       }
03542 
03543       /* walk extensions ... */
03544       e = NULL;
03545       while ( (e = ast_walk_context_extensions(c, e)) ) {
03546          struct ast_exten *p;
03547 
03548          if (exten && !ast_extension_match(ast_get_extension_name(e), exten))
03549             continue;   /* skip, extension match failed */
03550 
03551          dpc->extension_existence = 1;
03552 
03553          /* may we print context info? */
03554          if (!context_info_printed) {
03555             dpc->total_context++;
03556             if (rinclude) { /* TODO Print more info about rinclude */
03557                ast_cli(fd, "[ Included context '%s' created by '%s' ]\n",
03558                   ast_get_context_name(c), ast_get_context_registrar(c));
03559             } else {
03560                ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
03561                   ast_get_context_name(c), ast_get_context_registrar(c));
03562             }
03563             context_info_printed = 1;
03564          }
03565          dpc->total_prio++;
03566 
03567          /* write extension name and first peer */
03568          snprintf(buf, sizeof(buf), "'%s' =>", ast_get_extension_name(e));
03569 
03570          print_ext(e, buf2, sizeof(buf2));
03571 
03572          ast_cli(fd, "  %-17s %-45s [%s]\n", buf, buf2,
03573             ast_get_extension_registrar(e));
03574 
03575          dpc->total_exten++;
03576          /* walk next extension peers */
03577          p = e;   /* skip the first one, we already got it */
03578          while ( (p = ast_walk_extension_priorities(e, p)) ) {
03579             const char *el = ast_get_extension_label(p);
03580             dpc->total_prio++;
03581             if (el)
03582                snprintf(buf, sizeof(buf), "   [%s]", el);
03583             else
03584                buf[0] = '\0';
03585             print_ext(p, buf2, sizeof(buf2));
03586 
03587             ast_cli(fd,"  %-17s %-45s [%s]\n", buf, buf2,
03588                ast_get_extension_registrar(p));
03589          }
03590       }
03591 
03592       /* walk included and write info ... */
03593       i = NULL;
03594       while ( (i = ast_walk_context_includes(c, i)) ) {
03595          snprintf(buf, sizeof(buf), "'%s'", ast_get_include_name(i));
03596          if (exten) {
03597             /* Check all includes for the requested extension */
03598             if (includecount >= AST_PBX_MAX_STACK) {
03599                ast_log(LOG_NOTICE, "Maximum include depth exceeded!\n");
03600             } else {
03601                int dupe=0;
03602                int x;
03603                for (x=0;x<includecount;x++) {
03604                   if (!strcasecmp(includes[x], ast_get_include_name(i))) {
03605                      dupe++;
03606                      break;
03607                   }
03608                }
03609                if (!dupe) {
03610                   includes[includecount] = ast_get_include_name(i);
03611                   show_dialplan_helper(fd, ast_get_include_name(i), exten, dpc, i, includecount + 1, includes);
03612                } else {
03613                   ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context);
03614                }
03615             }
03616          } else {
03617             ast_cli(fd, "  Include =>        %-45s [%s]\n",
03618                buf, ast_get_include_registrar(i));
03619          }
03620       }
03621 
03622       /* walk ignore patterns and write info ... */
03623       ip = NULL;
03624       while ( (ip = ast_walk_context_ignorepats(c, ip)) ) {
03625          const char *ipname = ast_get_ignorepat_name(ip);
03626          char ignorepat[AST_MAX_EXTENSION];
03627          snprintf(buf, sizeof(buf), "'%s'", ipname);
03628          snprintf(ignorepat, sizeof(ignorepat), "_%s.", ipname);
03629          if (!exten || ast_extension_match(ignorepat, exten)) {
03630             ast_cli(fd, "  Ignore pattern => %-45s [%s]\n",
03631                buf, ast_get_ignorepat_registrar(ip));
03632          }
03633       }
03634       if (!rinclude) {
03635          struct ast_sw *sw = NULL;
03636          while ( (sw = ast_walk_context_switches(c, sw)) ) {
03637             snprintf(buf, sizeof(buf), "'%s/%s'",
03638                ast_get_switch_name(sw),
03639                ast_get_switch_data(sw));
03640             ast_cli(fd, "  Alt. Switch =>    %-45s [%s]\n",
03641                buf, ast_get_switch_registrar(sw));
03642          }
03643       }
03644 
03645       ast_unlock_context(c);
03646 
03647       /* if we print something in context, make an empty line */
03648       if (context_info_printed)
03649          ast_cli(fd, "\r\n");
03650    }
03651    ast_unlock_contexts();
03652 
03653    return (dpc->total_exten == old_total_exten) ? -1 : res;
03654 }
03655 
03656 static int handle_show_dialplan(int fd, int argc, char *argv[])
03657 {
03658    char *exten = NULL, *context = NULL;
03659    /* Variables used for different counters */
03660    struct dialplan_counters counters;
03661 
03662    const char *incstack[AST_PBX_MAX_STACK];
03663    memset(&counters, 0, sizeof(counters));
03664 
03665    if (argc != 2 && argc != 3)
03666       return RESULT_SHOWUSAGE;
03667 
03668    /* we obtain [exten@]context? if yes, split them ... */
03669    if (argc == 3) {
03670       if (strchr(argv[2], '@')) {   /* split into exten & context */
03671          context = ast_strdupa(argv[2]);
03672          exten = strsep(&context, "@");
03673          /* change empty strings to NULL */
03674          if (ast_strlen_zero(exten))
03675             exten = NULL;
03676       } else { /* no '@' char, only context given */
03677          context = argv[2];
03678       }
03679       if (ast_strlen_zero(context))
03680          context = NULL;
03681    }
03682    /* else Show complete dial plan, context and exten are NULL */
03683    show_dialplan_helper(fd, context, exten, &counters, NULL, 0, incstack);
03684 
03685    /* check for input failure and throw some error messages */
03686    if (context && !counters.context_existence) {
03687       ast_cli(fd, "There is no existence of '%s' context\n", context);
03688       return RESULT_FAILURE;
03689    }
03690 
03691    if (exten && !counters.extension_existence) {
03692       if (context)
03693          ast_cli(fd, "There is no existence of %s@%s extension\n",
03694             exten, context);
03695       else
03696          ast_cli(fd,
03697             "There is no existence of '%s' extension in all contexts\n",
03698             exten);
03699       return RESULT_FAILURE;
03700    }
03701 
03702    ast_cli(fd,"-= %d %s (%d %s) in %d %s. =-\n",
03703             counters.total_exten, counters.total_exten == 1 ? "extension" : "extensions",
03704             counters.total_prio, counters.total_prio == 1 ? "priority" : "priorities",
03705             counters.total_context, counters.total_context == 1 ? "context" : "contexts");
03706 
03707    /* everything ok */
03708    return RESULT_SUCCESS;
03709 }
03710 
03711 /*! \brief CLI support for listing global variables in a parseable way */
03712 static int handle_show_globals(int fd, int argc, char *argv[])
03713 {
03714    int i = 0;
03715    struct ast_var_t *newvariable;
03716 
03717    ast_mutex_lock(&globalslock);
03718    AST_LIST_TRAVERSE (&globals, newvariable, entries) {
03719       i++;
03720       ast_cli(fd, "   %s=%s\n", ast_var_name(newvariable), ast_var_value(newvariable));
03721    }
03722    ast_mutex_unlock(&globalslock);
03723    ast_cli(fd, "\n    -- %d variables\n", i);
03724 
03725    return RESULT_SUCCESS;
03726 }
03727 
03728 /*! \brief  CLI support for setting global variables */
03729 static int handle_set_global_deprecated(int fd, int argc, char *argv[])
03730 {
03731    if (argc != 4)
03732       return RESULT_SHOWUSAGE;
03733 
03734    pbx_builtin_setvar_helper(NULL, argv[2], argv[3]);
03735    ast_cli(fd, "\n    -- Global variable %s set to %s\n", argv[2], argv[3]);
03736 
03737    return RESULT_SUCCESS;
03738 }
03739 
03740 
03741 static int handle_set_global(int fd, int argc, char *argv[])
03742 {
03743    if (argc != 5)
03744       return RESULT_SHOWUSAGE;
03745 
03746    pbx_builtin_setvar_helper(NULL, argv[3], argv[4]);
03747    ast_cli(fd, "\n    -- Global variable %s set to %s\n", argv[3], argv[4]);
03748 
03749    return RESULT_SUCCESS;
03750 }
03751 
03752 
03753 
03754 /*
03755  * CLI entries for upper commands ...
03756  */
03757 static struct ast_cli_entry cli_show_applications_deprecated = {
03758    { "show", "applications", NULL },
03759    handle_show_applications_deprecated, NULL,
03760    NULL, complete_show_applications_deprecated };
03761 
03762 static struct ast_cli_entry cli_show_functions_deprecated = {
03763    { "show", "functions", NULL },
03764    handle_show_functions_deprecated, NULL,
03765         NULL };
03766 
03767 static struct ast_cli_entry cli_show_switches_deprecated = {
03768    { "show", "switches", NULL },
03769    handle_show_switches, NULL,
03770         NULL };
03771 
03772 static struct ast_cli_entry cli_show_hints_deprecated = {
03773    { "show", "hints", NULL },
03774    handle_show_hints, NULL,
03775         NULL };
03776 
03777 static struct ast_cli_entry cli_show_globals_deprecated = {
03778    { "show", "globals", NULL },
03779    handle_show_globals, NULL,
03780         NULL };
03781 
03782 static struct ast_cli_entry cli_show_function_deprecated = {
03783    { "show" , "function", NULL },
03784    handle_show_function_deprecated, NULL,
03785         NULL, complete_show_function };
03786 
03787 static struct ast_cli_entry cli_show_application_deprecated = {
03788    { "show", "application", NULL },
03789    handle_show_application_deprecated, NULL,
03790         NULL, complete_show_application };
03791 
03792 static struct ast_cli_entry cli_show_dialplan_deprecated = {
03793    { "show", "dialplan", NULL },
03794    handle_show_dialplan, NULL,
03795         NULL, complete_show_dialplan_context };
03796 
03797 static struct ast_cli_entry cli_set_global_deprecated = {
03798    { "set", "global", NULL },
03799    handle_set_global_deprecated, NULL,
03800         NULL };
03801 
03802 static struct ast_cli_entry pbx_cli[] = {
03803    { { "core", "show", "applications", NULL },
03804    handle_show_applications, "Shows registered dialplan applications",
03805    show_applications_help, complete_show_applications, &cli_show_applications_deprecated },
03806 
03807    { { "core", "show", "functions", NULL },
03808    handle_show_functions, "Shows registered dialplan functions",
03809    show_functions_help, NULL, &cli_show_functions_deprecated },
03810 
03811    { { "core", "show", "switches", NULL },
03812    handle_show_switches, "Show alternative switches",
03813    show_switches_help, NULL, &cli_show_switches_deprecated },
03814 
03815    { { "core", "show", "hints", NULL },
03816    handle_show_hints, "Show dialplan hints",
03817    show_hints_help, NULL, &cli_show_hints_deprecated },
03818 
03819    { { "core", "show", "globals", NULL },
03820    handle_show_globals, "Show global dialplan variables",
03821    show_globals_help, NULL, &cli_show_globals_deprecated },
03822 
03823    { { "core", "show" , "function", NULL },
03824    handle_show_function, "Describe a specific dialplan function",
03825    show_function_help, complete_show_function, &cli_show_function_deprecated },
03826 
03827    { { "core", "show", "application", NULL },
03828    handle_show_application, "Describe a specific dialplan application",
03829    show_application_help, complete_show_application, &cli_show_application_deprecated },
03830 
03831    { { "core", "set", "global", NULL },
03832    handle_set_global, "Set global dialplan variable",
03833    set_global_help, NULL, &cli_set_global_deprecated },
03834 
03835    { { "dialplan", "show", NULL },
03836    handle_show_dialplan, "Show dialplan",
03837    show_dialplan_help, complete_show_dialplan_context, &cli_show_dialplan_deprecated },
03838 };
03839 
03840 int ast_unregister_application(const char *app)
03841 {
03842    struct ast_app *tmp;
03843 
03844    AST_LIST_LOCK(&apps);
03845    AST_LIST_TRAVERSE_SAFE_BEGIN(&apps, tmp, list) {
03846       if (!strcasecmp(app, tmp->name)) {
03847          AST_LIST_REMOVE_CURRENT(&apps, list);
03848          if (option_verbose > 1)
03849             ast_verbose( VERBOSE_PREFIX_2 "Unregistered application '%s'\n", tmp->name);
03850          free(tmp);
03851          break;
03852       }
03853    }
03854    AST_LIST_TRAVERSE_SAFE_END
03855    AST_LIST_UNLOCK(&apps);
03856 
03857    return tmp ? 0 : -1;
03858 }
03859 
03860 static struct ast_context *__ast_context_create(struct ast_context **extcontexts, const char *name, const char *registrar, int existsokay)
03861 {
03862    struct ast_context *tmp, **local_contexts;
03863    int length = sizeof(struct ast_context) + strlen(name) + 1;
03864 
03865    if (!extcontexts) {
03866       ast_rdlock_contexts();
03867       local_contexts = &contexts;
03868    } else
03869       local_contexts = extcontexts;
03870 
03871    for (tmp = *local_contexts; tmp; tmp = tmp->next) {
03872       if (!strcasecmp(tmp->name, name)) {
03873          if (!existsokay) {
03874             ast_log(LOG_WARNING, "Tried to register context '%s', already in use\n", name);
03875             tmp = NULL;
03876          }
03877          if (!extcontexts)
03878             ast_unlock_contexts();
03879          return tmp;
03880       }
03881    }
03882    
03883    if (!extcontexts)
03884       ast_unlock_contexts();
03885 
03886    if ((tmp = ast_calloc(1, length))) {
03887       ast_mutex_init(&tmp->lock);
03888       ast_mutex_init(&tmp->macrolock);
03889       strcpy(tmp->name, name);
03890       tmp->registrar = registrar;
03891       if (!extcontexts)
03892          ast_wrlock_contexts();
03893       tmp->next = *local_contexts;
03894       *local_contexts = tmp;
03895       if (!extcontexts)
03896          ast_unlock_contexts();
03897       if (option_debug)
03898          ast_log(LOG_DEBUG, "Registered context '%s'\n", tmp->name);
03899       if (option_verbose > 2)
03900          ast_verbose( VERBOSE_PREFIX_3 "Registered extension context '%s'\n", tmp->name);
03901    }
03902 
03903    return tmp;
03904 }
03905 
03906 struct ast_context *ast_context_create(struct ast_context **extcontexts, const char *name, const char *registrar)
03907 {
03908    return __ast_context_create(extcontexts, name, registrar, 0);
03909 }
03910 
03911 struct ast_context *ast_context_find_or_create(struct ast_context **extcontexts, const char *name, const char *registrar)
03912 {
03913    return __ast_context_create(extcontexts, name, registrar, 1);
03914 }
03915 void __ast_context_destroy(struct ast_context *con, const char *registrar);
03916 
03917 struct store_hint {
03918    char *context;
03919    char *exten;
03920    struct ast_state_cb *callbacks;
03921    int laststate;
03922    AST_LIST_ENTRY(store_hint) list;
03923    char data[1];
03924 };
03925 
03926 AST_LIST_HEAD(store_hints, store_hint);
03927 
03928 /* XXX this does not check that multiple contexts are merged */
03929 void ast_merge_contexts_and_delete(struct ast_context **extcontexts, const char *registrar)
03930 {
03931    struct ast_context *tmp, *lasttmp = NULL;
03932    struct store_hints store = AST_LIST_HEAD_INIT_VALUE;
03933    struct store_hint *this;
03934    struct ast_hint *hint;
03935    struct ast_exten *exten;
03936    int length;
03937    struct ast_state_cb *thiscb, *prevcb;
03938 
03939    /* it is very important that this function hold the hint list lock _and_ the conlock
03940       during its operation; not only do we need to ensure that the list of contexts
03941       and extensions does not change, but also that no hint callbacks (watchers) are
03942       added or removed during the merge/delete process
03943 
03944       in addition, the locks _must_ be taken in this order, because there are already
03945       other code paths that use this order
03946    */
03947    ast_wrlock_contexts();
03948    AST_LIST_LOCK(&hints);
03949 
03950    /* preserve all watchers for hints associated with this registrar */
03951    AST_LIST_TRAVERSE(&hints, hint, list) {
03952       if (hint->callbacks && !strcmp(registrar, hint->exten->parent->registrar)) {
03953          length = strlen(hint->exten->exten) + strlen(hint->exten->parent->name) + 2 + sizeof(*this);
03954          if (!(this = ast_calloc(1, length)))
03955             continue;
03956          this->callbacks = hint->callbacks;
03957          hint->callbacks = NULL;
03958          this->laststate = hint->laststate;
03959          this->context = this->data;
03960          strcpy(this->data, hint->exten->parent->name);
03961          this->exten = this->data + strlen(this->context) + 1;
03962          strcpy(this->exten, hint->exten->exten);
03963          AST_LIST_INSERT_HEAD(&store, this, list);
03964       }
03965    }
03966 
03967    tmp = *extcontexts;
03968    if (registrar) {
03969       /* XXX remove previous contexts from same registrar */
03970       if (option_debug)
03971          ast_log(LOG_DEBUG, "must remove any reg %s\n", registrar);
03972       __ast_context_destroy(NULL,registrar);
03973       while (tmp) {
03974          lasttmp = tmp;
03975          tmp = tmp->next;
03976       }
03977    } else {
03978       /* XXX remove contexts with the same name */
03979       while (tmp) {
03980          ast_log(LOG_WARNING, "must remove %s  reg %s\n", tmp->name, tmp->registrar);
03981          __ast_context_destroy(tmp,tmp->registrar);
03982          lasttmp = tmp;
03983          tmp = tmp->next;
03984       }
03985    }
03986    if (lasttmp) {
03987       lasttmp->next = contexts;
03988       contexts = *extcontexts;
03989       *extcontexts = NULL;
03990    } else
03991       ast_log(LOG_WARNING, "Requested contexts didn't get merged\n");
03992 
03993    /* restore the watchers for hints that can be found; notify those that
03994       cannot be restored
03995    */
03996    while ((this = AST_LIST_REMOVE_HEAD(&store, list))) {
03997       struct pbx_find_info q = { .stacklen = 0 };
03998       exten = pbx_find_extension(NULL, NULL, &q, this->context, this->exten, PRIORITY_HINT, NULL, "", E_MATCH);
03999       /* Find the hint in the list of hints */
04000       AST_LIST_TRAVERSE(&hints, hint, list) {
04001          if (hint->exten == exten)
04002             break;
04003       }
04004       if (!exten || !hint) {
04005          /* this hint has been removed, notify the watchers */
04006          prevcb = NULL;
04007          thiscb = this->callbacks;
04008          while (thiscb) {
04009             prevcb = thiscb;
04010             thiscb = thiscb->next;
04011             prevcb->callback(this->context, this->exten, AST_EXTENSION_REMOVED, prevcb->data);
04012             free(prevcb);
04013             }
04014       } else {
04015          thiscb = this->callbacks;
04016          while (thiscb->next)
04017             thiscb = thiscb->next;
04018          thiscb->next = hint->callbacks;
04019          hint->callbacks = this->callbacks;
04020          hint->laststate = this->laststate;
04021       }
04022       free(this);
04023    }
04024 
04025    AST_LIST_UNLOCK(&hints);
04026    ast_unlock_contexts();
04027 
04028    return;
04029 }
04030 
04031 /*
04032  * errno values
04033  *  EBUSY  - can't lock
04034  *  ENOENT - no existence of context
04035  */
04036 int ast_context_add_include(const char *context, const char *include, const char *registrar)
04037 {
04038    int ret = -1;
04039    struct ast_context *c = find_context_locked(context);
04040 
04041    if (c) {
04042       ret = ast_context_add_include2(c, include, registrar);
04043       ast_unlock_contexts();
04044    }
04045    return ret;
04046 }
04047 
04048 /*! \brief Helper for get_range.
04049  * return the index of the matching entry, starting from 1.
04050  * If names is not supplied, try numeric values.
04051  */
04052 static int lookup_name(const char *s, char *const names[], int max)
04053 {
04054    int i;
04055 
04056    if (names) {
04057       for (i = 0; names[i]; i++) {
04058          if (!strcasecmp(s, names[i]))
04059             return i+1;
04060       }
04061    } else if (sscanf(s, "%d", &i) == 1 && i >= 1 && i <= max) {
04062       return i;
04063    }
04064    return 0; /* error return */
04065 }
04066 
04067 /*! \brief helper function to return a range up to max (7, 12, 31 respectively).
04068  * names, if supplied, is an array of names that should be mapped to numbers.
04069  */
04070 static unsigned get_range(char *src, int max, char *const names[], const char *msg)
04071 {
04072    int s, e; /* start and ending position */
04073    unsigned int mask = 0;
04074 
04075    /* Check for whole range */
04076    if (ast_strlen_zero(src) || !strcmp(src, "*")) {
04077       s = 0;
04078       e = max - 1;
04079    } else {
04080       /* Get start and ending position */
04081       char *c = strchr(src, '-');
04082       if (c)
04083          *c++ = '\0';
04084       /* Find the start */
04085       s = lookup_name(src, names, max);
04086       if (!s) {
04087          ast_log(LOG_WARNING, "Invalid %s '%s', assuming none\n", msg, src);
04088          return 0;
04089       }
04090       s--;
04091       if (c) { /* find end of range */
04092          e = lookup_name(c, names, max);
04093          if (!e) {
04094             ast_log(LOG_WARNING, "Invalid end %s '%s', assuming none\n", msg, c);
04095             return 0;
04096          }
04097          e--;
04098       } else
04099          e = s;
04100    }
04101    /* Fill the mask. Remember that ranges are cyclic */
04102    mask = 1 << e; /* initialize with last element */
04103    while (s != e) {
04104       if (s >= max) {
04105          s = 0;
04106          mask |= (1 << s);
04107       } else {
04108          mask |= (1 << s);
04109          s++;
04110       }
04111    }
04112    return mask;
04113 }
04114 
04115 /*! \brief store a bitmask of valid times, one bit each 2 minute */
04116 static void get_timerange(struct ast_timing *i, char *times)
04117 {
04118    char *e;
04119    int x;
04120    int s1, s2;
04121    int e1, e2;
04122    /* int cth, ctm; */
04123 
04124    /* start disabling all times, fill the fields with 0's, as they may contain garbage */
04125    memset(i->minmask, 0, sizeof(i->minmask));
04126 
04127    /* 2-minutes per bit, since the mask has only 32 bits :( */
04128    /* Star is all times */
04129    if (ast_strlen_zero(times) || !strcmp(times, "*")) {
04130       for (x=0; x<24; x++)
04131          i->minmask[x] = 0x3fffffff; /* 30 bits */
04132       return;
04133    }
04134    /* Otherwise expect a range */
04135    e = strchr(times, '-');
04136    if (!e) {
04137       ast_log(LOG_WARNING, "Time range is not valid. Assuming no restrictions based on time.\n");
04138       return;
04139    }
04140    *e++ = '\0';
04141    /* XXX why skip non digits ? */
04142    while (*e && !isdigit(*e))
04143       e++;
04144    if (!*e) {
04145       ast_log(LOG_WARNING, "Invalid time range.  Assuming no restrictions based on time.\n");
04146       return;
04147    }
04148    if (sscanf(times, "%d:%d", &s1, &s2) != 2) {
04149       ast_log(LOG_WARNING, "%s isn't a time.  Assuming no restrictions based on time.\n", times);
04150       return;
04151    }
04152    if (sscanf(e, "%d:%d", &e1, &e2) != 2) {
04153       ast_log(LOG_WARNING, "%s isn't a time.  Assuming no restrictions based on time.\n", e);
04154       return;
04155    }
04156    /* XXX this needs to be optimized */
04157 #if 1
04158    s1 = s1 * 30 + s2/2;
04159    if ((s1 < 0) || (s1 >= 24*30)) {
04160       ast_log(LOG_WARNING, "%s isn't a valid start time. Assuming no time.\n", times);
04161       return;
04162    }
04163    e1 = e1 * 30 + e2/2;
04164    if ((e1 < 0) || (e1 >= 24*30)) {
04165       ast_log(LOG_WARNING, "%s isn't a valid end time. Assuming no time.\n", e);
04166       return;
04167    }
04168    /* Go through the time and enable each appropriate bit */
04169    for (x=s1;x != e1;x = (x + 1) % (24 * 30)) {
04170       i->minmask[x/30] |= (1 << (x % 30));
04171    }
04172    /* Do the last one */
04173    i->minmask[x/30] |= (1 << (x % 30));
04174 #else
04175    for (cth=0; cth<24; cth++) {
04176       /* Initialize masks to blank */
04177       i->minmask[cth] = 0;
04178       for (ctm=0; ctm<30; ctm++) {
04179          if (
04180          /* First hour with more than one hour */
04181                (((cth == s1) && (ctm >= s2)) &&
04182                 ((cth < e1)))
04183          /* Only one hour */
04184          ||    (((cth == s1) && (ctm >= s2)) &&
04185                 ((cth == e1) && (ctm <= e2)))
04186          /* In between first and last hours (more than 2 hours) */
04187          ||    ((cth > s1) &&
04188                 (cth < e1))
04189          /* Last hour with more than one hour */
04190          ||    ((cth > s1) &&
04191                 ((cth == e1) && (ctm <= e2)))
04192          )
04193             i->minmask[cth] |= (1 << (ctm / 2));
04194       }
04195    }
04196 #endif
04197    /* All done */
04198    return;
04199 }
04200 
04201 static char *days[] =
04202 {
04203    "sun",
04204    "mon",
04205    "tue",
04206    "wed",
04207    "thu",
04208    "fri",
04209    "sat",
04210    NULL,
04211 };
04212 
04213 static char *months[] =
04214 {
04215    "jan",
04216    "feb",
04217    "mar",
04218    "apr",
04219    "may",
04220    "jun",
04221    "jul",
04222    "aug",
04223    "sep",
04224    "oct",
04225    "nov",
04226    "dec",
04227    NULL,
04228 };
04229 
04230 int ast_build_timing(struct ast_timing *i, const char *info_in)
04231 {
04232    char info_save[256];
04233    char *info;
04234 
04235    /* Check for empty just in case */
04236    if (ast_strlen_zero(info_in))
04237       return 0;
04238    /* make a copy just in case we were passed a static string */
04239    ast_copy_string(info_save, info_in, sizeof(info_save));
04240    info = info_save;
04241    /* Assume everything except time */
04242    i->monthmask = 0xfff;   /* 12 bits */
04243    i->daymask = 0x7fffffffU; /* 31 bits */
04244    i->dowmask = 0x7f; /* 7 bits */
04245    /* on each call, use strsep() to move info to the next argument */
04246    get_timerange(i, strsep(&info, "|"));
04247    if (info)
04248       i->dowmask = get_range(strsep(&info, "|"), 7, days, "day of week");
04249    if (info)
04250       i->daymask = get_range(strsep(&info, "|"), 31, NULL, "day");
04251    if (info)
04252       i->monthmask = get_range(strsep(&info, "|"), 12, months, "month");
04253    return 1;
04254 }
04255 
04256 int ast_check_timing(const struct ast_timing *i)
04257 {
04258    struct tm tm;
04259    time_t t = time(NULL);
04260 
04261    ast_localtime(&t, &tm, NULL);
04262 
04263    /* If it's not the right month, return */
04264    if (!(i->monthmask & (1 << tm.tm_mon)))
04265       return 0;
04266 
04267    /* If it's not that time of the month.... */
04268    /* Warning, tm_mday has range 1..31! */
04269    if (!(i->daymask & (1 << (tm.tm_mday-1))))
04270       return 0;
04271 
04272    /* If it's not the right day of the week */
04273    if (!(i->dowmask & (1 << tm.tm_wday)))
04274       return 0;
04275 
04276    /* Sanity check the hour just to be safe */
04277    if ((tm.tm_hour < 0) || (tm.tm_hour > 23)) {
04278       ast_log(LOG_WARNING, "Insane time...\n");
04279       return 0;
04280    }
04281 
04282    /* Now the tough part, we calculate if it fits
04283       in the right time based on min/hour */
04284    if (!(i->minmask[tm.tm_hour] & (1 << (tm.tm_min / 2))))
04285       return 0;
04286 
04287    /* If we got this far, then we're good */
04288    return 1;
04289 }
04290 
04291 /*
04292  * errno values
04293  *  ENOMEM - out of memory
04294  *  EBUSY  - can't lock
04295  *  EEXIST - already included
04296  *  EINVAL - there is no existence of context for inclusion
04297  */
04298 int ast_context_add_include2(struct ast_context *con, const char *value,
04299    const char *registrar)
04300 {
04301    struct ast_include *new_include;
04302    char *c;
04303    struct ast_include *i, *il = NULL; /* include, include_last */
04304    int length;
04305    char *p;
04306 
04307    length = sizeof(struct ast_include);
04308    length += 2 * (strlen(value) + 1);
04309 
04310    /* allocate new include structure ... */
04311    if (!(new_include = ast_calloc(1, length)))
04312       return -1;
04313    /* Fill in this structure. Use 'p' for assignments, as the fields
04314     * in the structure are 'const char *'
04315     */
04316    p = new_include->stuff;
04317    new_include->name = p;
04318    strcpy(p, value);
04319    p += strlen(value) + 1;
04320    new_include->rname = p;
04321    strcpy(p, value);
04322    /* Strip off timing info, and process if it is there */
04323    if ( (c = strchr(p, '|')) ) {
04324       *c++ = '\0';
04325            new_include->hastime = ast_build_timing(&(new_include->timing), c);
04326    }
04327    new_include->next      = NULL;
04328    new_include->registrar = registrar;
04329 
04330    ast_mutex_lock(&con->lock);
04331 
04332    /* ... go to last include and check if context is already included too... */
04333    for (i = con->includes; i; i = i->next) {
04334       if (!strcasecmp(i->name, new_include->name)) {
04335          free(new_include);
04336          ast_mutex_unlock(&con->lock);
04337          errno = EEXIST;
04338          return -1;
04339       }
04340       il = i;
04341    }
04342 
04343    /* ... include new context into context list, unlock, return */
04344    if (il)
04345       il->next = new_include;
04346    else
04347       con->includes = new_include;
04348    if (option_verbose > 2)
04349       ast_verbose(VERBOSE_PREFIX_3 "Including context '%s' in context '%s'\n", new_include->name, ast_get_context_name(con));
04350    ast_mutex_unlock(&con->lock);
04351 
04352    return 0;
04353 }
04354 
04355 /*
04356  * errno values
04357  *  EBUSY  - can't lock
04358  *  ENOENT - no existence of context
04359  */
04360 int ast_context_add_switch(const char *context, const char *sw, const char *data, int eval, const char *registrar)
04361 {
04362    int ret = -1;
04363    struct ast_context *c = find_context_locked(context);
04364 
04365    if (c) { /* found, add switch to this context */
04366       ret = ast_context_add_switch2(c, sw, data, eval, registrar);
04367       ast_unlock_contexts();
04368    }
04369    return ret;
04370 }
04371 
04372 /*
04373  * errno values
04374  *  ENOMEM - out of memory
04375  *  EBUSY  - can't lock
04376  *  EEXIST - already included
04377  *  EINVAL - there is no existence of context for inclusion
04378  */
04379 int ast_context_add_switch2(struct ast_context *con, const char *value,
04380    const char *data, int eval, const char *registrar)
04381 {
04382    struct ast_sw *new_sw;
04383    struct ast_sw *i;
04384    int length;
04385    char *p;
04386 
04387    length = sizeof(struct ast_sw);
04388    length += strlen(value) + 1;
04389    if (data)
04390       length += strlen(data);
04391    length++;
04392 
04393    /* allocate new sw structure ... */
04394    if (!(new_sw = ast_calloc(1, length)))
04395       return -1;
04396    /* ... fill in this structure ... */
04397    p = new_sw->stuff;
04398    new_sw->name = p;
04399    strcpy(new_sw->name, value);
04400    p += strlen(value) + 1;
04401    new_sw->data = p;
04402    if (data) {
04403       strcpy(new_sw->data, data);
04404       p += strlen(data) + 1;
04405    } else {
04406       strcpy(new_sw->data, "");
04407       p++;
04408    }
04409    new_sw->eval     = eval;
04410    new_sw->registrar = registrar;
04411 
04412    /* ... try to lock this context ... */
04413    ast_mutex_lock(&con->lock);
04414 
04415    /* ... go to last sw and check if context is already swd too... */
04416    AST_LIST_TRAVERSE(&con->alts, i, list) {
04417       if (!strcasecmp(i->name, new_sw->name) && !strcasecmp(i->data, new_sw->data)) {
04418          free(new_sw);
04419          ast_mutex_unlock(&con->lock);
04420          errno = EEXIST;
04421          return -1;
04422       }
04423    }
04424 
04425    /* ... sw new context into context list, unlock, return */
04426    AST_LIST_INSERT_TAIL(&con->alts, new_sw, list);
04427 
04428    if (option_verbose > 2)
04429       ast_verbose(VERBOSE_PREFIX_3 "Including switch '%s/%s' in context '%s'\n", new_sw->name, new_sw->data, ast_get_context_name(con));
04430 
04431    ast_mutex_unlock(&con->lock);
04432 
04433    return 0;
04434 }
04435 
04436 /*
04437  * EBUSY  - can't lock
04438  * ENOENT - there is not context existence
04439  */
04440 int ast_context_remove_ignorepat(const char *context, const char *ignorepat, const char *registrar)
04441 {
04442    int ret = -1;
04443    struct ast_context *c = find_context_locked(context);
04444 
04445    if (c) {
04446       ret = ast_context_remove_ignorepat2(c, ignorepat, registrar);
04447       ast_unlock_contexts();
04448    }
04449    return ret;
04450 }
04451 
04452 int ast_context_remove_ignorepat2(struct ast_context *con, const char *ignorepat, const char *registrar)
04453 {
04454    struct ast_ignorepat *ip, *ipl = NULL;
04455 
04456    ast_mutex_lock(&con->lock);
04457 
04458    for (ip = con->ignorepats; ip; ip = ip->next) {
04459       if (!strcmp(ip->pattern, ignorepat) &&
04460          (!registrar || (registrar == ip->registrar))) {
04461          if (ipl) {
04462             ipl->next = ip->next;
04463             free(ip);
04464          } else {
04465             con->ignorepats = ip->next;
04466             free(ip);
04467          }
04468          ast_mutex_unlock(&con->lock);
04469          return 0;
04470       }
04471       ipl = ip;
04472    }
04473 
04474    ast_mutex_unlock(&con->lock);
04475    errno = EINVAL;
04476    return -1;
04477 }
04478 
04479 /*
04480  * EBUSY - can't lock
04481  * ENOENT - there is no existence of context
04482  */
04483 int ast_context_add_ignorepat(const char *context, const char *value, const char *registrar)
04484 {
04485    int ret = -1;
04486    struct ast_context *c = find_context_locked(context);
04487 
04488    if (c) {
04489       ret = ast_context_add_ignorepat2(c, value, registrar);
04490       ast_unlock_contexts();
04491    }
04492    return ret;
04493 }
04494 
04495 int ast_context_add_ignorepat2(struct ast_context *con, const char *value, const char *registrar)
04496 {
04497    struct ast_ignorepat *ignorepat, *ignorepatc, *ignorepatl = NULL;
04498    int length;
04499    char *pattern;
04500    length = sizeof(struct ast_ignorepat);
04501    length += strlen(value) + 1;
04502    if (!(ignorepat = ast_calloc(1, length)))
04503       return -1;
04504    /* The cast to char * is because we need to write the initial value.
04505     * The field is not supposed to be modified otherwise.  Also, gcc 4.2
04506     * sees the cast as dereferencing a type-punned pointer and warns about
04507     * it.  This is the workaround (we're telling gcc, yes, that's really
04508     * what we wanted to do).
04509     */
04510    pattern = (char *) ignorepat->pattern;
04511    strcpy(pattern, value);
04512    ignorepat->next = NULL;
04513    ignorepat->registrar = registrar;
04514    ast_mutex_lock(&con->lock);
04515    for (ignorepatc = con->ignorepats; ignorepatc; ignorepatc = ignorepatc->next) {
04516       ignorepatl = ignorepatc;
04517       if (!strcasecmp(ignorepatc->pattern, value)) {
04518          /* Already there */
04519          ast_mutex_unlock(&con->lock);
04520          errno = EEXIST;
04521          return -1;
04522       }
04523    }
04524    if (ignorepatl)
04525       ignorepatl->next = ignorepat;
04526    else
04527       con->ignorepats = ignorepat;
04528    ast_mutex_unlock(&con->lock);
04529    return 0;
04530 
04531 }
04532 
04533 int ast_ignore_pattern(const char *context, const char *pattern)
04534 {
04535    struct ast_context *con = ast_context_find(context);
04536    if (con) {
04537       struct ast_ignorepat *pat;
04538       for (pat = con->ignorepats; pat; pat = pat->next) {
04539          if (ast_extension_match(pat->pattern, pattern))
04540             return 1;
04541       }
04542    }
04543 
04544    return 0;
04545 }
04546 
04547 /*
04548  * EBUSY   - can't lock
04549  * ENOENT  - no existence of context
04550  *
04551  */
04552 int ast_add_extension(const char *context, int replace, const char *extension,
04553    int priority, const char *label, const char *callerid,
04554    const char *application, void *data, void (*datad)(void *), const char *registrar)
04555 {
04556    int ret = -1;
04557    struct ast_context *c = find_context_locked(context);
04558 
04559    if (c) {
04560       ret = ast_add_extension2(c, replace, extension, priority, label, callerid,
04561          application, data, datad, registrar);
04562       ast_unlock_contexts();
04563    }
04564    return ret;
04565 }
04566 
04567 int ast_explicit_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
04568 {
04569    if (!chan)
04570       return -1;
04571 
04572    ast_channel_lock(chan);
04573 
04574    if (!ast_strlen_zero(context))
04575       ast_copy_string(chan->context, context, sizeof(chan->context));
04576    if (!ast_strlen_zero(exten))
04577       ast_copy_string(chan->exten, exten, sizeof(chan->exten));
04578    if (priority > -1) {
04579       chan->priority = priority;
04580       /* see flag description in channel.h for explanation */
04581       if (ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP))
04582          chan->priority--;
04583    }
04584 
04585    ast_channel_unlock(chan);
04586 
04587    return 0;
04588 }
04589 
04590 int ast_async_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
04591 {
04592    int res = 0;
04593 
04594    ast_channel_lock(chan);
04595 
04596    if (chan->pbx) { /* This channel is currently in the PBX */
04597       ast_explicit_goto(chan, context, exten, priority);
04598       ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
04599    } else {
04600       /* In order to do it when the channel doesn't really exist within
04601          the PBX, we have to make a new channel, masquerade, and start the PBX
04602          at the new location */
04603       struct ast_channel *tmpchan = ast_channel_alloc(0, chan->_state, 0, 0, chan->accountcode, chan->exten, chan->context, chan->amaflags, "AsyncGoto/%s", chan->name);
04604       if (!tmpchan) {
04605          res = -1;
04606       } else {
04607          if (chan->cdr) {
04608             ast_cdr_discard(tmpchan->cdr);
04609             tmpchan->cdr = ast_cdr_dup(chan->cdr);  /* share the love */
04610          }
04611          /* Make formats okay */
04612          tmpchan->readformat = chan->readformat;
04613          tmpchan->writeformat = chan->writeformat;
04614          /* Setup proper location */
04615          ast_explicit_goto(tmpchan,
04616             S_OR(context, chan->context), S_OR(exten, chan->exten), priority);
04617 
04618          /* Masquerade into temp channel */
04619          if (ast_channel_masquerade(tmpchan, chan)) {
04620             /* Failed to set up the masquerade.  It's probably chan_local
04621              * in the middle of optimizing itself out.  Sad. :( */
04622             ast_hangup(tmpchan);
04623             tmpchan = NULL;
04624             res = -1;
04625          } else {
04626             /* Grab the locks and get going */
04627             ast_channel_lock(tmpchan);
04628             ast_do_masquerade(tmpchan);
04629             ast_channel_unlock(tmpchan);
04630             /* Start the PBX going on our stolen channel */
04631             if (ast_pbx_start(tmpchan)) {
04632                ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmpchan->name);
04633                ast_hangup(tmpchan);
04634                res = -1;
04635             }
04636          }
04637       }
04638    }
04639    ast_channel_unlock(chan);
04640    return res;
04641 }
04642 
04643 int ast_async_goto_by_name(const char *channame, const char *context, const char *exten, int priority)
04644 {
04645    struct ast_channel *chan;
04646    int res = -1;
04647 
04648    chan = ast_get_channel_by_name_locked(channame);
04649    if (chan) {
04650       res = ast_async_goto(chan, context, exten, priority);
04651       ast_channel_unlock(chan);
04652    }
04653    return res;
04654 }
04655 
04656 /*! \brief copy a string skipping whitespace */
04657 static int ext_strncpy(char *dst, const char *src, int len)
04658 {
04659    int count=0;
04660 
04661    while (*src && (count < len - 1)) {
04662       switch(*src) {
04663       case ' ':
04664          /* otherwise exten => [a-b],1,... doesn't work */
04665          /*    case '-': */
04666          /* Ignore */
04667          break;
04668       default:
04669          *dst = *src;
04670          dst++;
04671       }
04672       src++;
04673       count++;
04674    }
04675    *dst = '\0';
04676 
04677    return count;
04678 }
04679 
04680 /*! \brief add the extension in the priority chain.
04681  * returns 0 on success, -1 on failure
04682  */
04683 static int add_pri(struct ast_context *con, struct ast_exten *tmp,
04684    struct ast_exten *el, struct ast_exten *e, int replace)
04685 {
04686    struct ast_exten *ep;
04687 
04688    for (ep = NULL; e ; ep = e, e = e->peer) {
04689       if (e->priority >= tmp->priority)
04690          break;
04691    }
04692    if (!e) {   /* go at the end, and ep is surely set because the list is not empty */
04693       ep->peer = tmp;
04694       return 0;   /* success */
04695    }
04696    if (e->priority == tmp->priority) {
04697       /* Can't have something exactly the same.  Is this a
04698          replacement?  If so, replace, otherwise, bonk. */
04699       if (!replace) {
04700          ast_log(LOG_WARNING, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp->exten, tmp->priority, con->name);
04701          if (tmp->datad)
04702             tmp->datad(tmp->data);
04703          free(tmp);
04704          return -1;
04705       }
04706       /* we are replacing e, so copy the link fields and then update
04707        * whoever pointed to e to point to us
04708        */
04709       tmp->next = e->next; /* not meaningful if we are not first in the peer list */
04710       tmp->peer = e->peer; /* always meaningful */
04711       if (ep)        /* We're in the peer list, just insert ourselves */
04712          ep->peer = tmp;
04713       else if (el)      /* We're the first extension. Take over e's functions */
04714          el->next = tmp;
04715       else        /* We're the very first extension.  */
04716          con->root = tmp;
04717       if (tmp->priority == PRIORITY_HINT)
04718          ast_change_hint(e,tmp);
04719       /* Destroy the old one */
04720       if (e->datad)
04721          e->datad(e->data);
04722       free(e);
04723    } else { /* Slip ourselves in just before e */
04724       tmp->peer = e;
04725       tmp->next = e->next; /* extension chain, or NULL if e is not the first extension */
04726       if (ep)        /* Easy enough, we're just in the peer list */
04727          ep->peer = tmp;
04728       else {         /* we are the first in some peer list, so link in the ext list */
04729          if (el)
04730             el->next = tmp;   /* in the middle... */
04731          else
04732             con->root = tmp; /* ... or at the head */
04733          e->next = NULL;   /* e is no more at the head, so e->next must be reset */
04734       }
04735       /* And immediately return success. */
04736       if (tmp->priority == PRIORITY_HINT)
04737           ast_add_hint(tmp);
04738    }
04739    return 0;
04740 }
04741 
04742 /*! \brief
04743  * Main interface to add extensions to the list for out context.
04744  *
04745  * We sort extensions in order of matching preference, so that we can
04746  * stop the search as soon as we find a suitable match.
04747  * This ordering also takes care of wildcards such as '.' (meaning
04748  * "one or more of any character") and '!' (which is 'earlymatch',
04749  * meaning "zero or more of any character" but also impacts the
04750  * return value from CANMATCH and EARLYMATCH.
04751  *
04752  * The extension match rules defined in the devmeeting 2006.05.05 are
04753  * quite simple: WE SELECT THE LONGEST MATCH.
04754  * In detail, "longest" means the number of matched characters in
04755  * the extension. In case of ties (e.g. _XXX and 333) in the length
04756  * of a pattern, we give priority to entries with the smallest cardinality
04757  * (e.g, [5-9] comes before [2-8] before the former has only 5 elements,
04758  * while the latter has 7, etc.
04759  * In case of same cardinality, the first element in the range counts.
04760  * If we still have a tie, any final '!' will make this as a possibly
04761  * less specific pattern.
04762  *
04763  * EBUSY - can't lock
04764  * EEXIST - extension with the same priority exist and no replace is set
04765  *
04766  */
04767 int ast_add_extension2(struct ast_context *con,
04768    int replace, const char *extension, int priority, const char *label, const char *callerid,
04769    const char *application, void *data, void (*datad)(void *),
04770    const char *registrar)
04771 {
04772    /*
04773     * Sort extensions (or patterns) according to the rules indicated above.
04774     * These are implemented by the function ext_cmp()).
04775     * All priorities for the same ext/pattern/cid are kept in a list,
04776     * using the 'peer' field  as a link field..
04777     */
04778    struct ast_exten *tmp, *e, *el = NULL;
04779    int res;
04780    int length;
04781    char *p;
04782    char expand_buf[VAR_BUF_SIZE] = { 0, };
04783 
04784    /* if we are adding a hint, and there are global variables, and the hint
04785       contains variable references, then expand them
04786    */
04787    ast_mutex_lock(&globalslock);
04788    if (priority == PRIORITY_HINT && AST_LIST_FIRST(&globals) && strstr(application, "${")) {
04789       pbx_substitute_variables_varshead(&globals, application, expand_buf, sizeof(expand_buf));
04790       application = expand_buf;
04791    }
04792    ast_mutex_unlock(&globalslock);
04793 
04794    length = sizeof(struct ast_exten);
04795    length += strlen(extension) + 1;
04796    length += strlen(application) + 1;
04797    if (label)
04798       length += strlen(label) + 1;
04799    if (callerid)
04800       length += strlen(callerid) + 1;
04801    else
04802       length ++;  /* just the '\0' */
04803 
04804    /* Be optimistic:  Build the extension structure first */
04805    if (!(tmp = ast_calloc(1, length)))
04806       return -1;
04807 
04808    /* use p as dst in assignments, as the fields are const char * */
04809    p = tmp->stuff;
04810    if (label) {
04811       tmp->label = p;
04812       strcpy(p, label);
04813       p += strlen(label) + 1;
04814    }
04815    tmp->exten = p;
04816    p += ext_strncpy(p, extension, strlen(extension) + 1) + 1;
04817    tmp->priority = priority;
04818    tmp->cidmatch = p;   /* but use p for assignments below */
04819    if (callerid) {
04820       p += ext_strncpy(p, callerid, strlen(callerid) + 1) + 1;
04821       tmp->matchcid = 1;
04822    } else {
04823       *p++ = '\0';
04824       tmp->matchcid = 0;
04825    }
04826    tmp->app = p;
04827    strcpy(p, application);
04828    tmp->parent = con;
04829    tmp->data = data;
04830    tmp->datad = datad;
04831    tmp->registrar = registrar;
04832 
04833    ast_mutex_lock(&con->lock);
04834    res = 0; /* some compilers will think it is uninitialized otherwise */
04835    for (e = con->root; e; el = e, e = e->next) {   /* scan the extension list */
04836       res = ext_cmp(e->exten, tmp->exten);
04837       if (res == 0) { /* extension match, now look at cidmatch */
04838          if (!e->matchcid && !tmp->matchcid)
04839             res = 0;
04840          else if (tmp->matchcid && !e->matchcid)
04841             res = 1;
04842          else if (e->matchcid && !tmp->matchcid)
04843             res = -1;
04844          else
04845             res = strcasecmp(e->cidmatch, tmp->cidmatch);
04846       }
04847       if (res >= 0)
04848          break;
04849    }
04850    if (e && res == 0) { /* exact match, insert in the pri chain */
04851       res = add_pri(con, tmp, el, e, replace);
04852       ast_mutex_unlock(&con->lock);
04853       if (res < 0) {
04854          errno = EEXIST;   /* XXX do we care ? */
04855          return 0; /* XXX should we return -1 maybe ? */
04856       }
04857    } else {
04858       /*
04859        * not an exact match, this is the first entry with this pattern,
04860        * so insert in the main list right before 'e' (if any)
04861        */
04862       tmp->next = e;
04863       if (el)
04864          el->next = tmp;
04865       else
04866          con->root = tmp;
04867       ast_mutex_unlock(&con->lock);
04868       if (tmp->priority == PRIORITY_HINT)
04869          ast_add_hint(tmp);
04870    }
04871    if (option_debug) {
04872       if (tmp->matchcid) {
04873          if (option_debug)
04874             ast_log(LOG_DEBUG, "Added extension '%s' priority %d (CID match '%s') to %s\n",
04875                tmp->exten, tmp->priority, tmp->cidmatch, con->name);
04876       } else {
04877          if (option_debug)
04878             ast_log(LOG_DEBUG, "Added extension '%s' priority %d to %s\n",
04879                tmp->exten, tmp->priority, con->name);
04880       }
04881    }
04882    if (option_verbose > 2) {
04883       if (tmp->matchcid) {
04884          ast_verbose( VERBOSE_PREFIX_3 "Added extension '%s' priority %d (CID match '%s')to %s\n",
04885             tmp->exten, tmp->priority, tmp->cidmatch, con->name);
04886       } else {
04887          ast_verbose( VERBOSE_PREFIX_3 "Added extension '%s' priority %d to %s\n",
04888             tmp->exten, tmp->priority, con->name);
04889       }
04890    }
04891    return 0;
04892 }
04893 
04894 struct async_stat {
04895    pthread_t p;
04896    struct ast_channel *chan;
04897    char context[AST_MAX_CONTEXT];
04898    char exten[AST_MAX_EXTENSION];
04899    int priority;
04900    int timeout;
04901    char app[AST_MAX_EXTENSION];
04902    char appdata[1024];
04903 };
04904 
04905 static void *async_wait(void *data)
04906 {
04907    struct async_stat *as = data;
04908    struct ast_channel *chan = as->chan;
04909    int timeout = as->timeout;
04910    int res;
04911    struct ast_frame *f;
04912    struct ast_app *app;
04913 
04914    while (timeout && (chan->_state != AST_STATE_UP)) {
04915       res = ast_waitfor(chan, timeout);
04916       if (res < 1)
04917          break;
04918       if (timeout > -1)
04919          timeout = res;
04920       f = ast_read(chan);
04921       if (!f)
04922          break;
04923       if (f->frametype == AST_FRAME_CONTROL) {
04924          if ((f->subclass == AST_CONTROL_BUSY)  ||
04925              (f->subclass == AST_CONTROL_CONGESTION) ) {
04926             ast_frfree(f);
04927             break;
04928          }
04929       }
04930       ast_frfree(f);
04931    }
04932    if (chan->_state == AST_STATE_UP) {
04933       if (!ast_strlen_zero(as->app)) {
04934          app = pbx_findapp(as->app);
04935          if (app) {
04936             if (option_verbose > 2)
04937                ast_verbose(VERBOSE_PREFIX_3 "Launching %s(%s) on %s\n", as->app, as->appdata, chan->name);
04938             pbx_exec(chan, app, as->appdata);
04939          } else
04940             ast_log(LOG_WARNING, "No such application '%s'\n", as->app);
04941       } else {
04942          if (!ast_strlen_zero(as->context))
04943             ast_copy_string(chan->context, as->context, sizeof(chan->context));
04944          if (!ast_strlen_zero(as->exten))
04945             ast_copy_string(chan->exten, as->exten, sizeof(chan->exten));
04946          if (as->priority > 0)
04947             chan->priority = as->priority;
04948          /* Run the PBX */
04949          if (ast_pbx_run(chan)) {
04950             ast_log(LOG_ERROR, "Failed to start PBX on %s\n", chan->name);
04951          } else {
04952             /* PBX will have taken care of this */
04953             chan = NULL;
04954          }
04955       }
04956    }
04957    free(as);
04958    if (chan)
04959       ast_hangup(chan);
04960    return NULL;
04961 }
04962 
04963 /*! Function to post an empty cdr after a spool call fails.
04964  *
04965  *  This function posts an empty cdr for a failed spool call
04966  *
04967  */
04968 static int ast_pbx_outgoing_cdr_failed(void)
04969 {
04970    /* allocate a channel */
04971    struct ast_channel *chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "%s", "");
04972 
04973    if (!chan)
04974       return -1;  /* failure */
04975 
04976    if (!chan->cdr) {
04977       /* allocation of the cdr failed */
04978       ast_channel_free(chan);   /* free the channel */
04979       return -1;                /* return failure */
04980    }
04981 
04982    /* allocation of the cdr was successful */
04983    ast_cdr_init(chan->cdr, chan);  /* initilize our channel's cdr */
04984    ast_cdr_start(chan->cdr);       /* record the start and stop time */
04985    ast_cdr_end(chan->cdr);
04986    ast_cdr_failed(chan->cdr);      /* set the status to failed */
04987    ast_cdr_detach(chan->cdr);      /* post and free the record */
04988    chan->cdr = NULL;
04989    ast_channel_free(chan);         /* free the channel */
04990 
04991    return 0;  /* success */
04992 }
04993 
04994 int ast_pbx_outgoing_exten(const char *type, int format, void *data, int timeout, const char *context, const char *exten, int priority, int *reason, int sync, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **channel)
04995 {
04996    struct ast_channel *chan;
04997    struct async_stat *as;
04998    int res = -1, cdr_res = -1;
04999    struct outgoing_helper oh;
05000    pthread_attr_t attr;
05001 
05002    if (sync) {
05003       LOAD_OH(oh);
05004       chan = __ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name, &oh);
05005       if (channel) {
05006          *channel = chan;
05007          if (chan)
05008             ast_channel_lock(chan);
05009       }
05010       if (chan) {
05011          if (chan->_state == AST_STATE_UP) {
05012                res = 0;
05013             if (option_verbose > 3)
05014                ast_verbose(VERBOSE_PREFIX_4 "Channel %s was answered.\n", chan->name);
05015 
05016             if (sync > 1) {
05017                if (channel)
05018                   ast_channel_unlock(chan);
05019                if (ast_pbx_run(chan)) {
05020                   ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
05021                   if (channel)
05022                      *channel = NULL;
05023                   ast_hangup(chan);
05024                   chan = NULL;
05025                   res = -1;
05026                }
05027             } else {
05028                if (ast_pbx_start(chan)) {
05029                   ast_log(LOG_ERROR, "Unable to start PBX on %s\n", chan->name);
05030                   if (channel) {
05031                      *channel = NULL;
05032                      ast_channel_unlock(chan);
05033                   }
05034                   ast_hangup(chan);
05035                   res = -1;
05036                }
05037                chan = NULL;
05038             }
05039          } else {
05040             if (option_verbose > 3)
05041                ast_verbose(VERBOSE_PREFIX_4 "Channel %s was never answered.\n", chan->name);
05042 
05043             if (chan->cdr) { /* update the cdr */
05044                /* here we update the status of the call, which sould be busy.
05045                 * if that fails then we set the status to failed */
05046                if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
05047                   ast_cdr_failed(chan->cdr);
05048             }
05049 
05050             if (channel) {
05051                *channel = NULL;
05052                ast_channel_unlock(chan);
05053             }
05054             ast_hangup(chan);
05055             chan = NULL;
05056          }
05057       }
05058 
05059       if (res < 0) { /* the call failed for some reason */
05060          if (*reason == 0) { /* if the call failed (not busy or no answer)
05061                         * update the cdr with the failed message */
05062             cdr_res = ast_pbx_outgoing_cdr_failed();
05063             if (cdr_res != 0) {
05064                res = cdr_res;
05065                goto outgoing_exten_cleanup;
05066             }
05067          }
05068 
05069          /* create a fake channel and execute the "failed" extension (if it exists) within the requested context */
05070          /* check if "failed" exists */
05071          if (ast_exists_extension(chan, context, "failed", 1, NULL)) {
05072             chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "OutgoingSpoolFailed");
05073             if (chan) {
05074                char failed_reason[4] = "";
05075                if (!ast_strlen_zero(context))
05076                   ast_copy_string(chan->context, context, sizeof(chan->context));
05077                set_ext_pri(chan, "failed", 1);
05078                ast_set_variables(chan, vars);
05079                snprintf(failed_reason, sizeof(failed_reason), "%d", *reason);
05080                pbx_builtin_setvar_helper(chan, "REASON", failed_reason);
05081                if (account)
05082                   ast_cdr_setaccount(chan, account);
05083                if (ast_pbx_run(chan)) {
05084                   ast_log(LOG_ERROR, "Unable to run PBX on %s\n", chan->name);
05085                   ast_hangup(chan);
05086                }
05087                chan = NULL;
05088             }
05089          }
05090       }
05091    } else {
05092       if (!(as = ast_calloc(1, sizeof(*as)))) {
05093          res = -1;
05094          goto outgoing_exten_cleanup;
05095       }
05096       chan = ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name);
05097       if (channel) {
05098          *channel = chan;
05099          if (chan)
05100             ast_channel_lock(chan);
05101       }
05102       if (!chan) {
05103          free(as);
05104          res = -1;
05105          goto outgoing_exten_cleanup;
05106       }
05107       as->chan = chan;
05108       ast_copy_string(as->context, context, sizeof(as->context));
05109       set_ext_pri(as->chan,  exten, priority);
05110       as->timeout = timeout;
05111       ast_set_variables(chan, vars);
05112       if (account)
05113          ast_cdr_setaccount(chan, account);
05114       pthread_attr_init(&attr);
05115       pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
05116       if (ast_pthread_create(&as->p, &attr, async_wait, as)) {
05117          ast_log(LOG_WARNING, "Failed to start async wait\n");
05118          free(as);
05119          if (channel) {
05120             *channel = NULL;
05121             ast_channel_unlock(chan);
05122          }
05123          ast_hangup(chan);
05124          res = -1;
05125          pthread_attr_destroy(&attr);
05126          goto outgoing_exten_cleanup;
05127       }
05128       pthread_attr_destroy(&attr);
05129       res = 0;
05130    }
05131 outgoing_exten_cleanup:
05132    ast_variables_destroy(vars);
05133    return res;
05134 }
05135 
05136 struct app_tmp {
05137    char app[256];
05138    char data[256];
05139    struct ast_channel *chan;
05140    pthread_t t;
05141 };
05142 
05143 /*! \brief run the application and free the descriptor once done */
05144 static void *ast_pbx_run_app(void *data)
05145 {
05146    struct app_tmp *tmp = data;
05147    struct ast_app *app;
05148    app = pbx_findapp(tmp->app);
05149    if (app) {
05150       if (option_verbose > 3)
05151          ast_verbose(VERBOSE_PREFIX_4 "Launching %s(%s) on %s\n", tmp->app, tmp->data, tmp->chan->name);
05152       pbx_exec(tmp->chan, app, tmp->data);
05153    } else
05154       ast_log(LOG_WARNING, "No such application '%s'\n", tmp->app);
05155    ast_hangup(tmp->chan);
05156    free(tmp);
05157    return NULL;
05158 }
05159 
05160 int ast_pbx_outgoing_app(const char *type, int format, void *data, int timeout, const char *app, const char *appdata, int *reason, int sync, const char *cid_num, const char *cid_name, struct ast_variable *vars, const char *account, struct ast_channel **locked_channel)
05161 {
05162    struct ast_channel *chan;
05163    struct app_tmp *tmp;
05164    int res = -1, cdr_res = -1;
05165    struct outgoing_helper oh;
05166    pthread_attr_t attr;
05167 
05168    memset(&oh, 0, sizeof(oh));
05169    oh.vars = vars;
05170    oh.account = account;
05171 
05172    if (locked_channel)
05173       *locked_channel = NULL;
05174    if (ast_strlen_zero(app)) {
05175       res = -1;
05176       goto outgoing_app_cleanup;
05177    }
05178    if (sync) {
05179       chan = __ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name, &oh);
05180       if (chan) {
05181          ast_set_variables(chan, vars);
05182          if (account)
05183             ast_cdr_setaccount(chan, account);
05184          if (chan->_state == AST_STATE_UP) {
05185             res = 0;
05186             if (option_verbose > 3)
05187                ast_verbose(VERBOSE_PREFIX_4 "Channel %s was answered.\n", chan->name);
05188             tmp = ast_calloc(1, sizeof(*tmp));
05189             if (!tmp)
05190                res = -1;
05191             else {
05192                ast_copy_string(tmp->app, app, sizeof(tmp->app));
05193                if (appdata)
05194                   ast_copy_string(tmp->data, appdata, sizeof(tmp->data));
05195                tmp->chan = chan;
05196                if (sync > 1) {
05197                   if (locked_channel)
05198                      ast_channel_unlock(chan);
05199                   ast_pbx_run_app(tmp);
05200                } else {
05201                   pthread_attr_init(&attr);
05202                   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
05203                   if (locked_channel)
05204                      ast_channel_lock(chan);
05205                   if (ast_pthread_create(&tmp->t, &attr, ast_pbx_run_app, tmp)) {
05206                      ast_log(LOG_WARNING, "Unable to spawn execute thread on %s: %s\n", chan->name, strerror(errno));
05207                      free(tmp);
05208                      if (locked_channel)
05209                         ast_channel_unlock(chan);
05210                      ast_hangup(chan);
05211                      res = -1;
05212                   } else {
05213                      if (locked_channel)
05214                         *locked_channel = chan;
05215                   }
05216                   pthread_attr_destroy(&attr);
05217                }
05218             }
05219          } else {
05220             if (option_verbose > 3)
05221                ast_verbose(VERBOSE_PREFIX_4 "Channel %s was never answered.\n", chan->name);
05222             if (chan->cdr) { /* update the cdr */
05223                /* here we update the status of the call, which sould be busy.
05224                 * if that fails then we set the status to failed */
05225                if (ast_cdr_disposition(chan->cdr, chan->hangupcause))
05226                   ast_cdr_failed(chan->cdr);
05227             }
05228             ast_hangup(chan);
05229          }
05230       }
05231 
05232       if (res < 0) { /* the call failed for some reason */
05233          if (*reason == 0) { /* if the call failed (not busy or no answer)
05234                         * update the cdr with the failed message */
05235             cdr_res = ast_pbx_outgoing_cdr_failed();
05236             if (cdr_res != 0) {
05237                res = cdr_res;
05238                goto outgoing_app_cleanup;
05239             }
05240          }
05241       }
05242 
05243    } else {
05244       struct async_stat *as;
05245       if (!(as = ast_calloc(1, sizeof(*as)))) {
05246          res = -1;
05247          goto outgoing_app_cleanup;
05248       }
05249       chan = __ast_request_and_dial(type, format, data, timeout, reason, cid_num, cid_name, &oh);
05250       if (!chan) {
05251          free(as);
05252          res = -1;
05253          goto outgoing_app_cleanup;
05254       }
05255       as->chan = chan;
05256       ast_copy_string(as->app, app, sizeof(as->app));
05257       if (appdata)
05258          ast_copy_string(as->appdata,  appdata, sizeof(as->appdata));
05259       as->timeout = timeout;
05260       ast_set_variables(chan, vars);
05261       if (account)
05262          ast_cdr_setaccount(chan, account);
05263       /* Start a new thread, and get something handling this channel. */
05264       pthread_attr_init(&attr);
05265       pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
05266       if (locked_channel)
05267          ast_channel_lock(chan);
05268       if (ast_pthread_create(&as->p, &attr, async_wait, as)) {
05269          ast_log(LOG_WARNING, "Failed to start async wait\n");
05270          free(as);
05271          if (locked_channel)
05272             ast_channel_unlock(chan);
05273          ast_hangup(chan);
05274          res = -1;
05275          pthread_attr_destroy(&attr);
05276          goto outgoing_app_cleanup;
05277       } else {
05278          if (locked_channel)
05279             *locked_channel = chan;
05280       }
05281       pthread_attr_destroy(&attr);
05282       res = 0;
05283    }
05284 outgoing_app_cleanup:
05285    ast_variables_destroy(vars);
05286    return res;
05287 }
05288 
05289 void __ast_context_destroy(struct ast_context *con, const char *registrar)
05290 {
05291    struct ast_context *tmp, *tmpl=NULL;
05292    struct ast_include *tmpi;
05293    struct ast_sw *sw;
05294    struct ast_exten *e, *el, *en;
05295    struct ast_ignorepat *ipi;
05296 
05297    for (tmp = contexts; tmp; ) {
05298       struct ast_context *next;  /* next starting point */
05299       for (; tmp; tmpl = tmp, tmp = tmp->next) {
05300          if (option_debug)
05301             ast_log(LOG_DEBUG, "check ctx %s %s\n", tmp->name, tmp->registrar);
05302          if ( (!registrar || !strcasecmp(registrar, tmp->registrar)) &&
05303               (!con || !strcasecmp(tmp->name, con->name)) )
05304             break;   /* found it */
05305       }
05306       if (!tmp)   /* not found, we are done */
05307          break;
05308       ast_mutex_lock(&tmp->lock);
05309       if (option_debug)
05310          ast_log(LOG_DEBUG, "delete ctx %s %s\n", tmp->name, tmp->registrar);
05311       next = tmp->next;
05312       if (tmpl)
05313          tmpl->next = next;
05314       else
05315          contexts = next;
05316       /* Okay, now we're safe to let it go -- in a sense, we were
05317          ready to let it go as soon as we locked it. */
05318       ast_mutex_unlock(&tmp->lock);
05319       for (tmpi = tmp->includes; tmpi; ) { /* Free includes */
05320          struct ast_include *tmpil = tmpi;
05321          tmpi = tmpi->next;
05322          free(tmpil);
05323       }
05324       for (ipi = tmp->ignorepats; ipi; ) { /* Free ignorepats */
05325          struct ast_ignorepat *ipl = ipi;
05326          ipi = ipi->next;
05327          free(ipl);
05328       }
05329       while ((sw = AST_LIST_REMOVE_HEAD(&tmp->alts, list)))
05330          free(sw);
05331       for (e = tmp->root; e;) {
05332          for (en = e->peer; en;) {
05333             el = en;
05334             en = en->peer;
05335             destroy_exten(el);
05336          }
05337          el = e;
05338          e = e->next;
05339          destroy_exten(el);
05340       }
05341       ast_mutex_destroy(&tmp->lock);
05342       free(tmp);
05343       /* if we have a specific match, we are done, otherwise continue */
05344       tmp = con ? NULL : next;
05345    }
05346 }
05347 
05348 void ast_context_destroy(struct ast_context *con, const char *registrar)
05349 {
05350    ast_wrlock_contexts();
05351    __ast_context_destroy(con,registrar);
05352    ast_unlock_contexts();
05353 }
05354 
05355 static void wait_for_hangup(struct ast_channel *chan, void *data)
05356 {
05357    int res;
05358    struct ast_frame *f;
05359    int waittime;
05360 
05361    if (ast_strlen_zero(data) || (sscanf(data, "%d", &waittime) != 1) || (waittime < 0))
05362       waittime = -1;
05363    if (waittime > -1) {
05364       ast_safe_sleep(chan, waittime * 1000);
05365    } else do {
05366       res = ast_waitfor(chan, -1);
05367       if (res < 0)
05368          return;
05369       f = ast_read(chan);
05370       if (f)
05371          ast_frfree(f);
05372    } while(f);
05373 }
05374 
05375 /*!
05376  * \ingroup applications
05377  */
05378 static int pbx_builtin_progress(struct ast_channel *chan, void *data)
05379 {
05380    ast_indicate(chan, AST_CONTROL_PROGRESS);
05381    return 0;
05382 }
05383 
05384 /*!
05385  * \ingroup applications
05386  */
05387 static int pbx_builtin_ringing(struct ast_channel *chan, void *data)
05388 {
05389    ast_indicate(chan, AST_CONTROL_RINGING);
05390    return 0;
05391 }
05392 
05393 /*!
05394  * \ingroup applications
05395  */
05396 static int pbx_builtin_busy(struct ast_channel *chan, void *data)
05397 {
05398    ast_indicate(chan, AST_CONTROL_BUSY);
05399    /* Don't change state of an UP channel, just indicate
05400       busy in audio */
05401    if (chan->_state != AST_STATE_UP)
05402       ast_setstate(chan, AST_STATE_BUSY);
05403    if( ast_strlen_zero(data) )
05404       wait_for_hangup(chan, "10");
05405    else
05406       wait_for_hangup(chan, data);
05407    return -1;
05408 }
05409 
05410 /*!
05411  * \ingroup applications
05412  */
05413 static int pbx_builtin_congestion(struct ast_channel *chan, void *data)
05414 {
05415    ast_indicate(chan, AST_CONTROL_CONGESTION);
05416    /* Don't change state of an UP channel, just indicate
05417       congestion in audio */
05418    if (chan->_state != AST_STATE_UP)
05419       ast_setstate(chan, AST_STATE_BUSY);
05420    if( ast_strlen_zero(data) )
05421       wait_for_hangup(chan, "10");
05422    else
05423       wait_for_hangup(chan, data);
05424    return -1;
05425 }
05426 
05427 /*!
05428  * \ingroup applications
05429  */
05430 static int pbx_builtin_answer(struct ast_channel *chan, void *data)
05431 {
05432    int delay = 0;
05433    int res;
05434 
05435    if (chan->_state == AST_STATE_UP)
05436       delay = 0;
05437    else if (!ast_strlen_zero(data))
05438       delay = atoi(data);
05439 
05440    res = ast_answer(chan);
05441    if (res)
05442       return res;
05443 
05444    if (delay)
05445       res = ast_safe_sleep(chan, delay);
05446 
05447    return res;
05448 }
05449 
05450 AST_APP_OPTIONS(resetcdr_opts, {
05451    AST_APP_OPTION('w', AST_CDR_FLAG_POSTED),
05452    AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED),
05453    AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS),
05454 });
05455 
05456 /*!
05457  * \ingroup applications
05458  */
05459 static int pbx_builtin_resetcdr(struct ast_channel *chan, void *data)
05460 {
05461    char *args;
05462    struct ast_flags flags = { 0 };
05463 
05464    if (!ast_strlen_zero(data)) {
05465       args = ast_strdupa(data);
05466       ast_app_parse_options(resetcdr_opts, &flags, NULL, args);
05467    }
05468 
05469    ast_cdr_reset(chan->cdr, &flags);
05470 
05471    return 0;
05472 }
05473 
05474 /*!
05475  * \ingroup applications
05476  */
05477 static int pbx_builtin_setamaflags(struct ast_channel *chan, void *data)
05478 {
05479    /* Copy the AMA Flags as specified */
05480    ast_cdr_setamaflags(chan, data ? data : "");
05481    return 0;
05482 }
05483 
05484 /*!
05485  * \ingroup applications
05486  */
05487 static int pbx_builtin_hangup(struct ast_channel *chan, void *data)
05488 {
05489    if (!ast_strlen_zero(data)) {
05490       int cause;
05491       char *endptr;
05492 
05493       if ((cause = ast_str2cause(data)) > -1) {
05494          chan->hangupcause = cause;
05495          return -1;
05496       }
05497       
05498       cause = strtol((const char *) data, &endptr, 10);
05499       if (cause != 0 || (data != endptr)) {
05500          chan->hangupcause = cause;
05501          return -1;
05502       }
05503          
05504       ast_log(LOG_NOTICE, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data);
05505    }
05506 
05507    if (!chan->hangupcause) {
05508       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
05509    }
05510 
05511    return -1;
05512 }
05513 
05514 /*!
05515  * \ingroup applications
05516  */
05517 static int pbx_builtin_gotoiftime(struct ast_channel *chan, void *data)
05518 {
05519    int res=0;
05520    char *s, *ts;
05521    struct ast_timing timing;
05522 
05523    if (ast_strlen_zero(data)) {
05524       ast_log(LOG_WARNING, "GotoIfTime requires an argument:\n  <time range>|<days of week>|<days of month>|<months>?[[context|]extension|]priority\n");
05525       return -1;
05526    }
05527 
05528    ts = s = ast_strdupa(data);
05529 
05530    /* Separate the Goto path */
05531    strsep(&ts,"?");
05532 
05533    /* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */
05534    if (ast_build_timing(&timing, s) && ast_check_timing(&timing))
05535       res = pbx_builtin_goto(chan, ts);
05536    
05537    return res;
05538 }
05539 
05540 /*!
05541  * \ingroup applications
05542  */
05543 static int pbx_builtin_execiftime(struct ast_channel *chan, void *data)
05544 {
05545    char *s, *appname;
05546    struct ast_timing timing;
05547    struct ast_app *app;
05548    static const char *usage = "ExecIfTime requires an argument:\n  <time range>|<days of week>|<days of month>|<months>?<appname>[|<appargs>]";
05549 
05550    if (ast_strlen_zero(data)) {
05551       ast_log(LOG_WARNING, "%s\n", usage);
05552       return -1;
05553    }
05554 
05555    appname = ast_strdupa(data);
05556 
05557    s = strsep(&appname,"?");  /* Separate the timerange and application name/data */
05558    if (!appname) {   /* missing application */
05559       ast_log(LOG_WARNING, "%s\n", usage);
05560       return -1;
05561    }
05562 
05563    if (!ast_build_timing(&timing, s)) {
05564       ast_log(LOG_WARNING, "Invalid Time Spec: %s\nCorrect usage: %s\n", s, usage);
05565       return -1;
05566    }
05567 
05568    if (!ast_check_timing(&timing))  /* outside the valid time window, just return */
05569       return 0;
05570 
05571    /* now split appname|appargs */
05572    if ((s = strchr(appname, '|')))
05573       *s++ = '\0';
05574 
05575    if ((app = pbx_findapp(appname))) {
05576       return pbx_exec(chan, app, S_OR(s, ""));
05577    } else {
05578       ast_log(LOG_WARNING, "Cannot locate application %s\n", appname);
05579       return -1;
05580    }
05581 }
05582 
05583 /*!
05584  * \ingroup applications
05585  */
05586 static int pbx_builtin_wait(struct ast_channel *chan, void *data)
05587 {
05588    double s;
05589    int ms;
05590 
05591    /* Wait for "n" seconds */
05592    if (data && (s = atof(data)) > 0) {
05593       ms = s * 1000.0;
05594       return ast_safe_sleep(chan, ms);
05595    }
05596    return 0;
05597 }
05598 
05599 /*!
05600  * \ingroup applications
05601  */
05602 static int pbx_builtin_waitexten(struct ast_channel *chan, void *data)
05603 {
05604    int ms, res;
05605    double sec;
05606    struct ast_flags flags = {0};
05607    char *opts[1] = { NULL };
05608    char *parse;
05609    AST_DECLARE_APP_ARGS(args,
05610       AST_APP_ARG(timeout);
05611       AST_APP_ARG(options);
05612    );
05613 
05614    if (!ast_strlen_zero(data)) {
05615       parse = ast_strdupa(data);
05616       AST_STANDARD_APP_ARGS(args, parse);
05617    } else
05618       memset(&args, 0, sizeof(args));
05619 
05620    if (args.options)
05621       ast_app_parse_options(waitexten_opts, &flags, opts, args.options);
05622    
05623    if (ast_test_flag(&flags, WAITEXTEN_MOH) && !opts[0] ) {
05624       ast_log(LOG_WARNING, "The 'm' option has been specified for WaitExten without a class.\n"); 
05625    } else if (ast_test_flag(&flags, WAITEXTEN_MOH))
05626       ast_indicate_data(chan, AST_CONTROL_HOLD, opts[0], strlen(opts[0]));
05627 
05628    /* Wait for "n" seconds */
05629    if (args.timeout && (sec = atof(args.timeout)) > 0.0)
05630       ms = 1000 * sec;
05631    else if (chan->pbx)
05632       ms = chan->pbx->rtimeout * 1000;
05633    else
05634       ms = 10000;
05635    res = ast_waitfordigit(chan, ms);
05636    if (!res) {
05637       if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 1, chan->cid.cid_num)) {
05638          if (option_verbose > 2)
05639             ast_verbose(VERBOSE_PREFIX_3 "Timeout on %s, continuing...\n", chan->name);
05640       } else if (chan->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
05641          if (option_verbose > 2)
05642             ast_verbose(VERBOSE_PREFIX_3 "Call timeout on %s, checking for 'T'\n", chan->name);
05643          res = -1;
05644       } else if (ast_exists_extension(chan, chan->context, "t", 1, chan->cid.cid_num)) {
05645          if (option_verbose > 2)
05646             ast_verbose(VERBOSE_PREFIX_3 "Timeout on %s, going to 't'\n", chan->name);
05647          set_ext_pri(chan, "t", 0); /* 0 will become 1, next time through the loop */
05648       } else {
05649          ast_log(LOG_WARNING, "Timeout but no rule 't' in context '%s'\n", chan->context);
05650          res = -1;
05651       }
05652    }
05653 
05654    if (ast_test_flag(&flags, WAITEXTEN_MOH))
05655       ast_indicate(chan, AST_CONTROL_UNHOLD);
05656 
05657    return res;
05658 }
05659 
05660 /*!
05661  * \ingroup applications
05662  */
05663 static int pbx_builtin_background(struct ast_channel *chan, void *data)
05664 {
05665    int res = 0;
05666    struct ast_flags flags = {0};
05667    char *parse;
05668    AST_DECLARE_APP_ARGS(args,
05669       AST_APP_ARG(filename);
05670       AST_APP_ARG(options);
05671       AST_APP_ARG(lang);
05672       AST_APP_ARG(context);
05673    );
05674 
05675    if (ast_strlen_zero(data)) {
05676       ast_log(LOG_WARNING, "Background requires an argument (filename)\n");
05677       return -1;
05678    }
05679 
05680    parse = ast_strdupa(data);
05681 
05682    AST_STANDARD_APP_ARGS(args, parse);
05683 
05684    if (ast_strlen_zero(args.lang))
05685       args.lang = (char *)chan->language; /* XXX this is const */
05686 
05687    if (ast_strlen_zero(args.context))
05688       args.context = chan->context;
05689 
05690    if (args.options) {
05691       if (!strcasecmp(args.options, "skip"))
05692          flags.flags = BACKGROUND_SKIP;
05693       else if (!strcasecmp(args.options, "noanswer"))
05694          flags.flags = BACKGROUND_NOANSWER;
05695       else
05696          ast_app_parse_options(background_opts, &flags, NULL, args.options);
05697    }
05698 
05699    /* Answer if need be */
05700    if (chan->_state != AST_STATE_UP) {
05701       if (ast_test_flag(&flags, BACKGROUND_SKIP)) {
05702          return 0;
05703       } else if (!ast_test_flag(&flags, BACKGROUND_NOANSWER)) {
05704          res = ast_answer(chan);
05705       }
05706    }
05707 
05708    if (!res) {
05709       char *back = args.filename;
05710       char *front;
05711       ast_stopstream(chan);      /* Stop anything playing */
05712       /* Stream the list of files */
05713       while (!res && (front = strsep(&back, "&")) ) {
05714          if ( (res = ast_streamfile(chan, front, args.lang)) ) {
05715             ast_log(LOG_WARNING, "ast_streamfile failed on %s for %s\n", chan->name, (char*)data);
05716             res = 0;
05717             break;
05718          }
05719          if (ast_test_flag(&flags, BACKGROUND_PLAYBACK)) {
05720             res = ast_waitstream(chan, "");
05721          } else if (ast_test_flag(&flags, BACKGROUND_MATCHEXTEN)) {
05722             res = ast_waitstream_exten(chan, args.context);
05723          } else {
05724             res = ast_waitstream(chan, AST_DIGIT_ANY);
05725          }
05726          ast_stopstream(chan);
05727       }
05728    }
05729    if (args.context != chan->context && res) {
05730       snprintf(chan->exten, sizeof(chan->exten), "%c", res);
05731       ast_copy_string(chan->context, args.context, sizeof(chan->context));
05732       chan->priority = 0;
05733       res = 0;
05734    }
05735    return res;
05736 }
05737 
05738 /*! Goto
05739  * \ingroup applications
05740  */
05741 static int pbx_builtin_goto(struct ast_channel *chan, void *data)
05742 {
05743    int res = ast_parseable_goto(chan, data);
05744    if (!res && (option_verbose > 2))
05745       ast_verbose( VERBOSE_PREFIX_3 "Goto (%s,%s,%d)\n", chan->context,chan->exten, chan->priority+1);
05746    return res;
05747 }
05748 
05749 
05750 int pbx_builtin_serialize_variables(struct ast_channel *chan, char *buf, size_t size)
05751 {
05752    struct ast_var_t *variables;
05753    const char *var, *val;
05754    int total = 0;
05755 
05756    if (!chan)
05757       return 0;
05758 
05759    memset(buf, 0, size);
05760 
05761    ast_channel_lock(chan);
05762 
05763    AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
05764       if ((var=ast_var_name(variables)) && (val=ast_var_value(variables))
05765          /* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
05766          ) {
05767          if (ast_build_string(&buf, &size, "%s=%s\n", var, val)) {
05768             ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
05769             break;
05770          } else
05771             total++;
05772       } else
05773          break;
05774    }
05775 
05776    ast_channel_unlock(chan);
05777 
05778    return total;
05779 }
05780 
05781 const char *pbx_builtin_getvar_helper(struct ast_channel *chan, const char *name)
05782 {
05783    struct ast_var_t *variables;
05784    const char *ret = NULL;
05785    int i;
05786    struct varshead *places[2] = { NULL, &globals };
05787 
05788    if (!name)
05789       return NULL;
05790 
05791    if (chan) {
05792       ast_channel_lock(chan);
05793       places[0] = &chan->varshead;
05794    }
05795 
05796    for (i = 0; i < 2; i++) {
05797       if (!places[i])
05798          continue;
05799       if (places[i] == &globals)
05800          ast_mutex_lock(&globalslock);
05801       AST_LIST_TRAVERSE(places[i], variables, entries) {
05802          if (!strcmp(name, ast_var_name(variables))) {
05803             ret = ast_var_value(variables);
05804             break;
05805          }
05806       }
05807       if (places[i] == &globals)
05808          ast_mutex_unlock(&globalslock);
05809       if (ret)
05810          break;
05811    }
05812 
05813    if (chan)
05814       ast_channel_unlock(chan);
05815 
05816    return ret;
05817 }
05818 
05819 void pbx_builtin_pushvar_helper(struct ast_channel *chan, const char *name, const char *value)
05820 {
05821    struct ast_var_t *newvariable;
05822    struct varshead *headp;
05823 
05824    if (name[strlen(name)-1] == ')') {
05825       char *function = ast_strdupa(name);
05826 
05827       ast_log(LOG_WARNING, "Cannot push a value onto a function\n");
05828       ast_func_write(chan, function, value);
05829       return;
05830    }
05831 
05832    if (chan) {
05833       ast_channel_lock(chan);
05834       headp = &chan->varshead;
05835    } else {
05836       ast_mutex_lock(&globalslock);
05837       headp = &globals;
05838    }
05839 
05840    if (value) {
05841       if ((option_verbose > 1) && (headp == &globals))
05842          ast_verbose(VERBOSE_PREFIX_2 "Setting global variable '%s' to '%s'\n", name, value);
05843       newvariable = ast_var_assign(name, value);
05844       AST_LIST_INSERT_HEAD(headp, newvariable, entries);
05845    }
05846 
05847    if (chan)
05848       ast_channel_unlock(chan);
05849    else
05850       ast_mutex_unlock(&globalslock);
05851 }
05852 
05853 void pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
05854 {
05855    struct ast_var_t *newvariable;
05856    struct varshead *headp;
05857    const char *nametail = name;
05858 
05859    if (name[strlen(name)-1] == ')') {
05860       char *function = ast_strdupa(name);
05861 
05862       ast_func_write(chan, function, value);
05863       return;
05864    }
05865 
05866    if (chan) {
05867       ast_channel_lock(chan);
05868       headp = &chan->varshead;
05869    } else {
05870       ast_mutex_lock(&globalslock);
05871       headp = &globals;
05872    }
05873 
05874    /* For comparison purposes, we have to strip leading underscores */
05875    if (*nametail == '_') {
05876       nametail++;
05877       if (*nametail == '_')
05878          nametail++;
05879    }
05880 
05881    AST_LIST_TRAVERSE (headp, newvariable, entries) {
05882       if (strcasecmp(ast_var_name(newvariable), nametail) == 0) {
05883          /* there is already such a variable, delete it */
05884          AST_LIST_REMOVE(headp, newvariable, entries);
05885          ast_var_delete(newvariable);
05886          break;
05887       }
05888    }
05889 
05890    if (value) {
05891       if ((option_verbose > 1) && (headp == &globals))
05892          ast_verbose(VERBOSE_PREFIX_2 "Setting global variable '%s' to '%s'\n", name, value);
05893       newvariable = ast_var_assign(name, value);
05894       AST_LIST_INSERT_HEAD(headp, newvariable, entries);
05895    }
05896 
05897    if (chan)
05898       ast_channel_unlock(chan);
05899    else
05900       ast_mutex_unlock(&globalslock);
05901 }
05902 
05903 int pbx_builtin_setvar(struct ast_channel *chan, void *data)
05904 {
05905    char *name, *value, *mydata;
05906    int argc;
05907    char *argv[24];      /* this will only support a maximum of 24 variables being set in a single operation */
05908    int global = 0;
05909    int x;
05910 
05911    if (ast_strlen_zero(data)) {
05912       ast_log(LOG_WARNING, "Set requires at least one variable name/value pair.\n");
05913       return 0;
05914    }
05915 
05916    mydata = ast_strdupa(data);
05917    argc = ast_app_separate_args(mydata, '|', argv, sizeof(argv) / sizeof(argv[0]));
05918 
05919    /* check for a trailing flags argument */
05920    if ((argc > 1) && !strchr(argv[argc-1], '=')) {
05921       argc--;
05922       if (strchr(argv[argc], 'g')) {
05923          ast_log(LOG_WARNING, "The use of the 'g' flag is deprecated.  Please use Set(GLOBAL(foo)=bar) instead\n");
05924          global = 1;
05925       }
05926    }
05927 
05928    if (argc > 1)
05929       ast_log(LOG_WARNING, "Setting multiple variables at once within Set is deprecated.  Please separate each name/value pair into its own line.\n");
05930 
05931    for (x = 0; x < argc; x++) {
05932       name = argv[x];
05933       if ((value = strchr(name, '='))) {
05934          *value++ = '\0';
05935          pbx_builtin_setvar_helper((global) ? NULL : chan, name, value);
05936       } else
05937          ast_log(LOG_WARNING, "Ignoring entry '%s' with no = (and not last 'options' entry)\n", name);
05938    }
05939 
05940    return(0);
05941 }
05942 
05943 int pbx_builtin_importvar(struct ast_channel *chan, void *data)
05944 {
05945    char *name;
05946    char *value;
05947    char *channel;
05948    char tmp[VAR_BUF_SIZE]="";
05949 
05950    if (ast_strlen_zero(data)) {
05951       ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n");
05952       return 0;
05953    }
05954 
05955    value = ast_strdupa(data);
05956    name = strsep(&value,"=");
05957    channel = strsep(&value,"|");
05958    if (channel && value && name) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */
05959       struct ast_channel *chan2 = ast_get_channel_by_name_locked(channel);
05960       if (chan2) {
05961          char *s = alloca(strlen(value) + 4);
05962          if (s) {
05963             sprintf(s, "${%s}", value);
05964             pbx_substitute_variables_helper(chan2, s, tmp, sizeof(tmp) - 1);
05965          }
05966          ast_channel_unlock(chan2);
05967       }
05968       pbx_builtin_setvar_helper(chan, name, tmp);
05969    }
05970 
05971    return(0);
05972 }
05973 
05974 /*! \todo XXX overwrites data ? */
05975 static int pbx_builtin_setglobalvar(struct ast_channel *chan, void *data)
05976 {
05977    char *name;
05978    char *stringp = data;
05979    static int dep_warning = 0;
05980 
05981    if (ast_strlen_zero(data)) {
05982       ast_log(LOG_WARNING, "Ignoring, since there is no variable to set\n");
05983       return 0;
05984    }
05985 
05986    name = strsep(&stringp, "=");
05987 
05988    if (!dep_warning) {
05989       dep_warning = 1;
05990       ast_log(LOG_WARNING, "SetGlobalVar is deprecated.  Please use Set(GLOBAL(%s)=%s) instead.\n", name, stringp);
05991    }
05992 
05993    /*! \todo XXX watch out, leading whitespace ? */
05994    pbx_builtin_setvar_helper(NULL, name, stringp);
05995 
05996    return(0);
05997 }
05998 
05999 static int pbx_builtin_noop(struct ast_channel *chan, void *data)
06000 {
06001    return 0;
06002 }
06003 
06004 void pbx_builtin_clear_globals(void)
06005 {
06006    struct ast_var_t *vardata;
06007 
06008    ast_mutex_lock(&globalslock);
06009    while ((vardata = AST_LIST_REMOVE_HEAD(&globals, entries)))
06010       ast_var_delete(vardata);
06011    ast_mutex_unlock(&globalslock);
06012 }
06013 
06014 int pbx_checkcondition(const char *condition)
06015 {
06016    if (ast_strlen_zero(condition))  /* NULL or empty strings are false */
06017       return 0;
06018    else if (*condition >= '0' && *condition <= '9')   /* Numbers are evaluated for truth */
06019       return atoi(condition);
06020    else  /* Strings are true */
06021       return 1;
06022 }
06023 
06024 static int pbx_builtin_gotoif(struct ast_channel *chan, void *data)
06025 {
06026    char *condition, *branch1, *branch2, *branch;
06027    int rc;
06028    char *stringp;
06029 
06030    if (ast_strlen_zero(data)) {
06031       ast_log(LOG_WARNING, "Ignoring, since there is no variable to check\n");
06032       return 0;
06033    }
06034 
06035    stringp = ast_strdupa(data);
06036    condition = strsep(&stringp,"?");
06037    branch1 = strsep(&stringp,":");
06038    branch2 = strsep(&stringp,"");
06039    branch = pbx_checkcondition(condition) ? branch1 : branch2;
06040 
06041    if (ast_strlen_zero(branch)) {
06042       if (option_debug)
06043          ast_log(LOG_DEBUG, "Not taking any branch\n");
06044       return 0;
06045    }
06046 
06047    rc = pbx_builtin_goto(chan, branch);
06048 
06049    return rc;
06050 }
06051 
06052 static int pbx_builtin_saynumber(struct ast_channel *chan, void *data)
06053 {
06054    char tmp[256];
06055    char *number = tmp;
06056    char *options;
06057 
06058    if (ast_strlen_zero(data)) {
06059       ast_log(LOG_WARNING, "SayNumber requires an argument (number)\n");
06060       return -1;
06061    }
06062    ast_copy_string(tmp, data, sizeof(tmp));
06063    strsep(&number, "|");
06064    options = strsep(&number, "|");
06065    if (options) {
06066       if ( strcasecmp(options, "f") && strcasecmp(options,"m") &&
06067          strcasecmp(options, "c") && strcasecmp(options, "n") ) {
06068          ast_log(LOG_WARNING, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n");
06069          return -1;
06070       }
06071    }
06072 
06073    if (ast_say_number(chan, atoi(tmp), "", chan->language, options)) {
06074       ast_log(LOG_WARNING, "We were unable to say the number %s, is it too large?\n", tmp);
06075    }
06076 
06077    return 0;
06078 }
06079 
06080 static int pbx_builtin_saydigits(struct ast_channel *chan, void *data)
06081 {
06082    int res = 0;
06083 
06084    if (data)
06085       res = ast_say_digit_str(chan, data, "", chan->language);
06086    return res;
06087 }
06088 
06089 static int pbx_builtin_saycharacters(struct ast_channel *chan, void *data)
06090 {
06091    int res = 0;
06092 
06093    if (data)
06094       res = ast_say_character_str(chan, data, "", chan->language);
06095    return res;
06096 }
06097 
06098 static int pbx_builtin_sayphonetic(struct ast_channel *chan, void *data)
06099 {
06100    int res = 0;
06101 
06102    if (data)
06103       res = ast_say_phonetic_str(chan, data, "", chan->language);
06104    return res;
06105 }
06106 
06107 int load_pbx(void)
06108 {
06109    int x;
06110 
06111    /* Initialize the PBX */
06112    if (option_verbose) {
06113       ast_verbose( "Asterisk PBX Core Initializing\n");
06114       ast_verbose( "Registering builtin applications:\n");
06115    }
06116    ast_cli_register_multiple(pbx_cli, sizeof(pbx_cli) / sizeof(struct ast_cli_entry));
06117 
06118    /* Register builtin applications */
06119    for (x=0; x<sizeof(builtins) / sizeof(struct pbx_builtin); x++) {
06120       if (option_verbose)
06121          ast_verbose( VERBOSE_PREFIX_1 "[%s]\n", builtins[x].name);
06122       if (ast_register_application(builtins[x].name, builtins[x].execute, builtins[x].synopsis, builtins[x].description)) {
06123          ast_log(LOG_ERROR, "Unable to register builtin application '%s'\n", builtins[x].name);
06124          return -1;
06125       }
06126    }
06127    return 0;
06128 }
06129 
06130 /*
06131  * Lock context list functions ...
06132  */
06133 int ast_lock_contexts()
06134 {
06135    return ast_rwlock_wrlock(&conlock);
06136 }
06137 
06138 int ast_rdlock_contexts(void)
06139 {
06140    return ast_rwlock_rdlock(&conlock);
06141 }
06142 
06143 int ast_wrlock_contexts(void)
06144 {
06145    return ast_rwlock_wrlock(&conlock);
06146 }
06147 
06148 int ast_unlock_contexts()
06149 {
06150    return ast_rwlock_unlock(&conlock);
06151 }
06152 
06153 /*
06154  * Lock context ...
06155  */
06156 int ast_lock_context(struct ast_context *con)
06157 {
06158    return ast_mutex_lock(&con->lock);
06159 }
06160 
06161 int ast_unlock_context(struct ast_context *con)
06162 {
06163    return ast_mutex_unlock(&con->lock);
06164 }
06165 
06166 /*
06167  * Name functions ...
06168  */
06169 const char *ast_get_context_name(struct ast_context *con)
06170 {
06171    return con ? con->name : NULL;
06172 }
06173 
06174 struct ast_context *ast_get_extension_context(struct ast_exten *exten)
06175 {
06176    return exten ? exten->parent : NULL;
06177 }
06178 
06179 const char *ast_get_extension_name(struct ast_exten *exten)
06180 {
06181    return exten ? exten->exten : NULL;
06182 }
06183 
06184 const char *ast_get_extension_label(struct ast_exten *exten)
06185 {
06186    return exten ? exten->label : NULL;
06187 }
06188 
06189 const char *ast_get_include_name(struct ast_include *inc)
06190 {
06191    return inc ? inc->name : NULL;
06192 }
06193 
06194 const char *ast_get_ignorepat_name(struct ast_ignorepat *ip)
06195 {
06196    return ip ? ip->pattern : NULL;
06197 }
06198 
06199 int ast_get_extension_priority(struct ast_exten *exten)
06200 {
06201    return exten ? exten->priority : -1;
06202 }
06203 
06204 /*
06205  * Registrar info functions ...
06206  */
06207 const char *ast_get_context_registrar(struct ast_context *c)
06208 {
06209    return c ? c->registrar : NULL;
06210 }
06211 
06212 const char *ast_get_extension_registrar(struct ast_exten *e)
06213 {
06214    return e ? e->registrar : NULL;
06215 }
06216 
06217 const char *ast_get_include_registrar(struct ast_include *i)
06218 {
06219    return i ? i->registrar : NULL;
06220 }
06221 
06222 const char *ast_get_ignorepat_registrar(struct ast_ignorepat *ip)
06223 {
06224    return ip ? ip->registrar : NULL;
06225 }
06226 
06227 int ast_get_extension_matchcid(struct ast_exten *e)
06228 {
06229    return e ? e->matchcid : 0;
06230 }
06231 
06232 const char *ast_get_extension_cidmatch(struct ast_exten *e)
06233 {
06234    return e ? e->cidmatch : NULL;
06235 }
06236 
06237 const char *ast_get_extension_app(struct ast_exten *e)
06238 {
06239    return e ? e->app : NULL;
06240 }
06241 
06242 void *ast_get_extension_app_data(struct ast_exten *e)
06243 {
06244    return e ? e->data : NULL;
06245 }
06246 
06247 const char *ast_get_switch_name(struct ast_sw *sw)
06248 {
06249    return sw ? sw->name : NULL;
06250 }
06251 
06252 const char *ast_get_switch_data(struct ast_sw *sw)
06253 {
06254    return sw ? sw->data : NULL;
06255 }
06256 
06257 const char *ast_get_switch_registrar(struct ast_sw *sw)
06258 {
06259    return sw ? sw->registrar : NULL;
06260 }
06261 
06262 /*
06263  * Walking functions ...
06264  */
06265 struct ast_context *ast_walk_contexts(struct ast_context *con)
06266 {
06267    return con ? con->next : contexts;
06268 }
06269 
06270 struct ast_exten *ast_walk_context_extensions(struct ast_context *con,
06271    struct ast_exten *exten)
06272 {
06273    if (!exten)
06274       return con ? con->root : NULL;
06275    else
06276       return exten->next;
06277 }
06278 
06279 struct ast_sw *ast_walk_context_switches(struct ast_context *con,
06280    struct ast_sw *sw)
06281 {
06282    if (!sw)
06283       return con ? AST_LIST_FIRST(&con->alts) : NULL;
06284    else
06285       return AST_LIST_NEXT(sw, list);
06286 }
06287 
06288 struct ast_exten *ast_walk_extension_priorities(struct ast_exten *exten,
06289    struct ast_exten *priority)
06290 {
06291    return priority ? priority->peer : exten;
06292 }
06293 
06294 struct ast_include *ast_walk_context_includes(struct ast_context *con,
06295    struct ast_include *inc)
06296 {
06297    if (!inc)
06298       return con ? con->includes : NULL;
06299    else
06300       return inc->next;
06301 }
06302 
06303 struct ast_ignorepat *ast_walk_context_ignorepats(struct ast_context *con,
06304    struct ast_ignorepat *ip)
06305 {
06306    if (!ip)
06307       return con ? con->ignorepats : NULL;
06308    else
06309       return ip->next;
06310 }
06311 
06312 int ast_context_verify_includes(struct ast_context *con)
06313 {
06314    struct ast_include *inc = NULL;
06315    int res = 0;
06316 
06317    while ( (inc = ast_walk_context_includes(con, inc)) ) {
06318       if (ast_context_find(inc->rname))
06319          continue;
06320 
06321       res = -1;
06322       ast_log(LOG_WARNING, "Context '%s' tries to include nonexistent context '%s'\n",
06323          ast_get_context_name(con), inc->rname);
06324       break;
06325    }
06326 
06327    return res;
06328 }
06329 
06330 
06331 static int __ast_goto_if_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, int async)
06332 {
06333    int (*goto_func)(struct ast_channel *chan, const char *context, const char *exten, int priority);
06334 
06335    if (!chan)
06336       return -2;
06337 
06338    if (context == NULL)
06339       context = chan->context;
06340    if (exten == NULL)
06341       exten = chan->exten;
06342 
06343    goto_func = (async) ? ast_async_goto : ast_explicit_goto;
06344    if (ast_exists_extension(chan, context, exten, priority, chan->cid.cid_num))
06345       return goto_func(chan, context, exten, priority);
06346    else
06347       return -3;
06348 }
06349 
06350 int ast_goto_if_exists(struct ast_channel *chan, const char* context, const char *exten, int priority)
06351 {
06352    return __ast_goto_if_exists(chan, context, exten, priority, 0);
06353 }
06354 
06355 int ast_async_goto_if_exists(struct ast_channel *chan, const char * context, const char *exten, int priority)
06356 {
06357    return __ast_goto_if_exists(chan, context, exten, priority, 1);
06358 }
06359 
06360 int ast_parseable_goto(struct ast_channel *chan, const char *goto_string)
06361 {
06362    char *exten, *pri, *context;
06363    char *stringp;
06364    int ipri;
06365    int mode = 0;
06366 
06367    if (ast_strlen_zero(goto_string)) {
06368       ast_log(LOG_WARNING, "Goto requires an argument (optional context|optional extension|priority)\n");
06369       return -1;
06370    }
06371    stringp = ast_strdupa(goto_string);
06372    context = strsep(&stringp, "|"); /* guaranteed non-null */
06373    exten = strsep(&stringp, "|");
06374    pri = strsep(&stringp, "|");
06375    if (!exten) {  /* Only a priority in this one */
06376       pri = context;
06377       exten = NULL;
06378       context = NULL;
06379    } else if (!pri) {   /* Only an extension and priority in this one */
06380       pri = exten;
06381       exten = context;
06382       context = NULL;
06383    }
06384    if (*pri == '+') {
06385       mode = 1;
06386       pri++;
06387    } else if (*pri == '-') {
06388       mode = -1;
06389       pri++;
06390    }
06391    if (sscanf(pri, "%d", &ipri) != 1) {
06392       if ((ipri = ast_findlabel_extension(chan, context ? context : chan->context, exten ? exten : chan->exten,
06393          pri, chan->cid.cid_num)) < 1) {
06394          ast_log(LOG_WARNING, "Priority '%s' must be a number > 0, or valid label\n", pri);
06395          return -1;
06396       } else
06397          mode = 0;
06398    }
06399    /* At this point we have a priority and maybe an extension and a context */
06400 
06401    if (mode)
06402       ipri = chan->priority + (ipri * mode);
06403 
06404    ast_explicit_goto(chan, context, exten, ipri);
06405    return 0;
06406 
06407 }

Generated on Fri Jul 3 20:35:39 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9