Sat Feb 11 06:33:00 2012

Asterisk developer's documentation


app.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, 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 Convenient Application Routines
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  */
00025 
00026 #include "asterisk.h"
00027 
00028 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 352348 $")
00029 
00030 #ifdef HAVE_SYS_STAT_H
00031 #include <sys/stat.h>
00032 #endif
00033 #include <regex.h>          /* for regcomp(3) */
00034 #include <sys/file.h>       /* for flock(2) */
00035 #include <signal.h>         /* for pthread_sigmask(3) */
00036 #include <stdlib.h>         /* for closefrom(3) */
00037 #include <sys/types.h>
00038 #include <sys/wait.h>       /* for waitpid(2) */
00039 #ifndef HAVE_CLOSEFROM
00040 #include <dirent.h>         /* for opendir(3)   */
00041 #endif
00042 #ifdef HAVE_CAP
00043 #include <sys/capability.h>
00044 #endif /* HAVE_CAP */
00045 
00046 #include "asterisk/paths.h"   /* use ast_config_AST_DATA_DIR */
00047 #include "asterisk/channel.h"
00048 #include "asterisk/pbx.h"
00049 #include "asterisk/file.h"
00050 #include "asterisk/app.h"
00051 #include "asterisk/dsp.h"
00052 #include "asterisk/utils.h"
00053 #include "asterisk/lock.h"
00054 #include "asterisk/indications.h"
00055 #include "asterisk/linkedlists.h"
00056 #include "asterisk/threadstorage.h"
00057 #include "asterisk/test.h"
00058 
00059 AST_THREADSTORAGE_PUBLIC(ast_str_thread_global_buf);
00060 
00061 static pthread_t shaun_of_the_dead_thread = AST_PTHREADT_NULL;
00062 
00063 struct zombie {
00064    pid_t pid;
00065    AST_LIST_ENTRY(zombie) list;
00066 };
00067 
00068 static AST_LIST_HEAD_STATIC(zombies, zombie);
00069 
00070 static void *shaun_of_the_dead(void *data)
00071 {
00072    struct zombie *cur;
00073    int status;
00074    for (;;) {
00075       if (!AST_LIST_EMPTY(&zombies)) {
00076          /* Don't allow cancellation while we have a lock. */
00077          pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
00078          AST_LIST_LOCK(&zombies);
00079          AST_LIST_TRAVERSE_SAFE_BEGIN(&zombies, cur, list) {
00080             if (waitpid(cur->pid, &status, WNOHANG) != 0) {
00081                AST_LIST_REMOVE_CURRENT(list);
00082                ast_free(cur);
00083             }
00084          }
00085          AST_LIST_TRAVERSE_SAFE_END
00086          AST_LIST_UNLOCK(&zombies);
00087          pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
00088       }
00089       pthread_testcancel();
00090       /* Wait for 60 seconds, without engaging in a busy loop. */
00091       ast_poll(NULL, 0, AST_LIST_FIRST(&zombies) ? 5000 : 60000);
00092    }
00093    return NULL;
00094 }
00095 
00096 
00097 #define AST_MAX_FORMATS 10
00098 
00099 static AST_RWLIST_HEAD_STATIC(groups, ast_group_info);
00100 
00101 /*!
00102  * \brief This function presents a dialtone and reads an extension into 'collect'
00103  * which must be a pointer to a **pre-initialized** array of char having a
00104  * size of 'size' suitable for writing to.  It will collect no more than the smaller
00105  * of 'maxlen' or 'size' minus the original strlen() of collect digits.
00106  * \param chan struct.
00107  * \param context
00108  * \param collect
00109  * \param size
00110  * \param maxlen
00111  * \param timeout timeout in milliseconds
00112  *
00113  * \return 0 if extension does not exist, 1 if extension exists
00114 */
00115 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout)
00116 {
00117    struct ast_tone_zone_sound *ts;
00118    int res = 0, x = 0;
00119 
00120    if (maxlen > size) {
00121       maxlen = size;
00122    }
00123 
00124    if (!timeout) {
00125       if (chan->pbx && chan->pbx->dtimeoutms) {
00126          timeout = chan->pbx->dtimeoutms;
00127       } else {
00128          timeout = 5000;
00129       }
00130    }
00131 
00132    if ((ts = ast_get_indication_tone(chan->zone, "dial"))) {
00133       res = ast_playtones_start(chan, 0, ts->data, 0);
00134       ts = ast_tone_zone_sound_unref(ts);
00135    } else {
00136       ast_log(LOG_NOTICE, "Huh....? no dial for indications?\n");
00137    }
00138 
00139    for (x = strlen(collect); x < maxlen; ) {
00140       res = ast_waitfordigit(chan, timeout);
00141       if (!ast_ignore_pattern(context, collect)) {
00142          ast_playtones_stop(chan);
00143       }
00144       if (res < 1) {
00145          break;
00146       }
00147       if (res == '#') {
00148          break;
00149       }
00150       collect[x++] = res;
00151       if (!ast_matchmore_extension(chan, context, collect, 1,
00152          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
00153          break;
00154       }
00155    }
00156 
00157    if (res >= 0) {
00158       res = ast_exists_extension(chan, context, collect, 1,
00159          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL)) ? 1 : 0;
00160    }
00161 
00162    return res;
00163 }
00164 
00165 /*!
00166  * \brief ast_app_getdata
00167  * \param c The channel to read from
00168  * \param prompt The file to stream to the channel
00169  * \param s The string to read in to.  Must be at least the size of your length
00170  * \param maxlen How many digits to read (maximum)
00171  * \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
00172  *      "ludicrous time" (essentially never times out) */
00173 enum ast_getdata_result ast_app_getdata(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout)
00174 {
00175    int res = 0, to, fto;
00176    char *front, *filename;
00177 
00178    /* XXX Merge with full version? XXX */
00179 
00180    if (maxlen)
00181       s[0] = '\0';
00182 
00183    if (!prompt)
00184       prompt = "";
00185 
00186    filename = ast_strdupa(prompt);
00187    while ((front = strsep(&filename, "&"))) {
00188       ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", front, ast_channel_name(c));
00189       if (!ast_strlen_zero(front)) {
00190          res = ast_streamfile(c, front, ast_channel_language(c));
00191          if (res)
00192             continue;
00193       }
00194       if (ast_strlen_zero(filename)) {
00195          /* set timeouts for the last prompt */
00196          fto = c->pbx ? c->pbx->rtimeoutms : 6000;
00197          to = c->pbx ? c->pbx->dtimeoutms : 2000;
00198 
00199          if (timeout > 0) {
00200             fto = to = timeout;
00201          }
00202          if (timeout < 0) {
00203             fto = to = 1000000000;
00204          }
00205       } else {
00206          /* there is more than one prompt, so
00207           * get rid of the long timeout between
00208           * prompts, and make it 50ms */
00209          fto = 50;
00210          to = c->pbx ? c->pbx->dtimeoutms : 2000;
00211       }
00212       res = ast_readstring(c, s, maxlen, to, fto, "#");
00213       if (res == AST_GETDATA_EMPTY_END_TERMINATED) {
00214          return res;
00215       }
00216       if (!ast_strlen_zero(s)) {
00217          return res;
00218       }
00219    }
00220 
00221    return res;
00222 }
00223 
00224 /* The lock type used by ast_lock_path() / ast_unlock_path() */
00225 static enum AST_LOCK_TYPE ast_lock_type = AST_LOCK_TYPE_LOCKFILE;
00226 
00227 int ast_app_getdata_full(struct ast_channel *c, const char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
00228 {
00229    int res, to = 2000, fto = 6000;
00230 
00231    if (!ast_strlen_zero(prompt)) {
00232       res = ast_streamfile(c, prompt, ast_channel_language(c));
00233       if (res < 0) {
00234          return res;
00235       }
00236    }
00237 
00238    if (timeout > 0) {
00239       fto = to = timeout;
00240    }
00241    if (timeout < 0) {
00242       fto = to = 1000000000;
00243    }
00244 
00245    res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
00246 
00247    return res;
00248 }
00249 
00250 int ast_app_run_macro(struct ast_channel *autoservice_chan, struct ast_channel *macro_chan, const char * const macro_name, const char * const macro_args)
00251 {
00252    struct ast_app *macro_app;
00253    int res;
00254    char buf[1024];
00255 
00256    macro_app = pbx_findapp("Macro");
00257    if (!macro_app) {
00258       ast_log(LOG_WARNING, "Cannot run macro '%s' because the 'Macro' application in not available\n", macro_name);
00259       return -1;
00260    }
00261    snprintf(buf, sizeof(buf), "%s%s%s", macro_name, ast_strlen_zero(macro_args) ? "" : ",", S_OR(macro_args, ""));
00262    if (autoservice_chan) {
00263       ast_autoservice_start(autoservice_chan);
00264    }
00265    res = pbx_exec(macro_chan, macro_app, buf);
00266    if (autoservice_chan) {
00267       ast_autoservice_stop(autoservice_chan);
00268    }
00269    return res;
00270 }
00271 
00272 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
00273 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
00274 static int (*ast_inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs) = NULL;
00275 static int (*ast_sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context) = NULL;
00276 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
00277 
00278 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
00279                int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
00280                int (*inboxcount2_func)(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs),
00281                int (*messagecount_func)(const char *context, const char *mailbox, const char *folder),
00282                int (*sayname_func)(struct ast_channel *chan, const char *mailbox, const char *context))
00283 {
00284    ast_has_voicemail_func = has_voicemail_func;
00285    ast_inboxcount_func = inboxcount_func;
00286    ast_inboxcount2_func = inboxcount2_func;
00287    ast_messagecount_func = messagecount_func;
00288    ast_sayname_func = sayname_func;
00289 }
00290 
00291 void ast_uninstall_vm_functions(void)
00292 {
00293    ast_has_voicemail_func = NULL;
00294    ast_inboxcount_func = NULL;
00295    ast_inboxcount2_func = NULL;
00296    ast_messagecount_func = NULL;
00297    ast_sayname_func = NULL;
00298 }
00299 
00300 int ast_app_has_voicemail(const char *mailbox, const char *folder)
00301 {
00302    static int warned = 0;
00303    if (ast_has_voicemail_func) {
00304       return ast_has_voicemail_func(mailbox, folder);
00305    }
00306 
00307    if (warned++ % 10 == 0) {
00308       ast_verb(3, "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
00309    }
00310    return 0;
00311 }
00312 
00313 
00314 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
00315 {
00316    static int warned = 0;
00317    if (newmsgs) {
00318       *newmsgs = 0;
00319    }
00320    if (oldmsgs) {
00321       *oldmsgs = 0;
00322    }
00323    if (ast_inboxcount_func) {
00324       return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
00325    }
00326 
00327    if (warned++ % 10 == 0) {
00328       ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
00329    }
00330 
00331    return 0;
00332 }
00333 
00334 int ast_app_inboxcount2(const char *mailbox, int *urgentmsgs, int *newmsgs, int *oldmsgs)
00335 {
00336    static int warned = 0;
00337    if (newmsgs) {
00338       *newmsgs = 0;
00339    }
00340    if (oldmsgs) {
00341       *oldmsgs = 0;
00342    }
00343    if (urgentmsgs) {
00344       *urgentmsgs = 0;
00345    }
00346    if (ast_inboxcount_func) {
00347       return ast_inboxcount2_func(mailbox, urgentmsgs, newmsgs, oldmsgs);
00348    }
00349 
00350    if (warned++ % 10 == 0) {
00351       ast_verb(3, "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
00352    }
00353 
00354    return 0;
00355 }
00356 
00357 int ast_app_sayname(struct ast_channel *chan, const char *mailbox, const char *context)
00358 {
00359    if (ast_sayname_func) {
00360       return ast_sayname_func(chan, mailbox, context);
00361    }
00362    return -1;
00363 }
00364 
00365 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
00366 {
00367    static int warned = 0;
00368    if (ast_messagecount_func) {
00369       return ast_messagecount_func(context, mailbox, folder);
00370    }
00371 
00372    if (!warned) {
00373       warned++;
00374       ast_verb(3, "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
00375    }
00376 
00377    return 0;
00378 }
00379 
00380 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between, unsigned int duration)
00381 {
00382    const char *ptr;
00383    int res = 0;
00384    struct ast_silence_generator *silgen = NULL;
00385 
00386    if (!between) {
00387       between = 100;
00388    }
00389 
00390    if (peer) {
00391       res = ast_autoservice_start(peer);
00392    }
00393 
00394    if (!res) {
00395       res = ast_waitfor(chan, 100);
00396    }
00397 
00398    /* ast_waitfor will return the number of remaining ms on success */
00399    if (res < 0) {
00400       if (peer) {
00401          ast_autoservice_stop(peer);
00402       }
00403       return res;
00404    }
00405 
00406    if (ast_opt_transmit_silence) {
00407       silgen = ast_channel_start_silence_generator(chan);
00408    }
00409 
00410    for (ptr = digits; *ptr; ptr++) {
00411       if (*ptr == 'w') {
00412          /* 'w' -- wait half a second */
00413          if ((res = ast_safe_sleep(chan, 500))) {
00414             break;
00415          }
00416       } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
00417          /* Character represents valid DTMF */
00418          if (*ptr == 'f' || *ptr == 'F') {
00419             /* ignore return values if not supported by channel */
00420             ast_indicate(chan, AST_CONTROL_FLASH);
00421          } else {
00422             ast_senddigit(chan, *ptr, duration);
00423          }
00424          /* pause between digits */
00425          if ((res = ast_safe_sleep(chan, between))) {
00426             break;
00427          }
00428       } else {
00429          ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n", *ptr);
00430       }
00431    }
00432 
00433    if (peer) {
00434       /* Stop autoservice on the peer channel, but don't overwrite any error condition
00435          that has occurred previously while acting on the primary channel */
00436       if (ast_autoservice_stop(peer) && !res) {
00437          res = -1;
00438       }
00439    }
00440 
00441    if (silgen) {
00442       ast_channel_stop_silence_generator(chan, silgen);
00443    }
00444 
00445    return res;
00446 }
00447 
00448 struct linear_state {
00449    int fd;
00450    int autoclose;
00451    int allowoverride;
00452    struct ast_format origwfmt;
00453 };
00454 
00455 static void linear_release(struct ast_channel *chan, void *params)
00456 {
00457    struct linear_state *ls = params;
00458 
00459    if (ls->origwfmt.id && ast_set_write_format(chan, &ls->origwfmt)) {
00460       ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", ast_channel_name(chan), ls->origwfmt.id);
00461    }
00462 
00463    if (ls->autoclose) {
00464       close(ls->fd);
00465    }
00466 
00467    ast_free(params);
00468 }
00469 
00470 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
00471 {
00472    short buf[2048 + AST_FRIENDLY_OFFSET / 2];
00473    struct linear_state *ls = data;
00474    struct ast_frame f = {
00475       .frametype = AST_FRAME_VOICE,
00476       .data.ptr = buf + AST_FRIENDLY_OFFSET / 2,
00477       .offset = AST_FRIENDLY_OFFSET,
00478    };
00479    int res;
00480 
00481    ast_format_set(&f.subclass.format, AST_FORMAT_SLINEAR, 0);
00482 
00483    len = samples * 2;
00484    if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
00485       ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" , len);
00486       len = sizeof(buf) - AST_FRIENDLY_OFFSET;
00487    }
00488    res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
00489    if (res > 0) {
00490       f.datalen = res;
00491       f.samples = res / 2;
00492       ast_write(chan, &f);
00493       if (res == len) {
00494          return 0;
00495       }
00496    }
00497    return -1;
00498 }
00499 
00500 static void *linear_alloc(struct ast_channel *chan, void *params)
00501 {
00502    struct linear_state *ls = params;
00503 
00504    if (!params) {
00505       return NULL;
00506    }
00507 
00508    /* In this case, params is already malloc'd */
00509    if (ls->allowoverride) {
00510       ast_set_flag(chan, AST_FLAG_WRITE_INT);
00511    } else {
00512       ast_clear_flag(chan, AST_FLAG_WRITE_INT);
00513    }
00514 
00515    ast_format_copy(&ls->origwfmt, &chan->writeformat);
00516 
00517    if (ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR)) {
00518       ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", ast_channel_name(chan));
00519       ast_free(ls);
00520       ls = params = NULL;
00521    }
00522 
00523    return params;
00524 }
00525 
00526 static struct ast_generator linearstream =
00527 {
00528    alloc: linear_alloc,
00529    release: linear_release,
00530    generate: linear_generator,
00531 };
00532 
00533 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
00534 {
00535    struct linear_state *lin;
00536    char tmpf[256];
00537    int res = -1;
00538    int autoclose = 0;
00539    if (fd < 0) {
00540       if (ast_strlen_zero(filename)) {
00541          return -1;
00542       }
00543       autoclose = 1;
00544       if (filename[0] == '/') {
00545          ast_copy_string(tmpf, filename, sizeof(tmpf));
00546       } else {
00547          snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", ast_config_AST_DATA_DIR, "sounds", filename);
00548       }
00549       if ((fd = open(tmpf, O_RDONLY)) < 0) {
00550          ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
00551          return -1;
00552       }
00553    }
00554    if ((lin = ast_calloc(1, sizeof(*lin)))) {
00555       lin->fd = fd;
00556       lin->allowoverride = allowoverride;
00557       lin->autoclose = autoclose;
00558       res = ast_activate_generator(chan, &linearstream, lin);
00559    }
00560    return res;
00561 }
00562 
00563 int ast_control_streamfile(struct ast_channel *chan, const char *file,
00564             const char *fwd, const char *rev,
00565             const char *stop, const char *suspend,
00566             const char *restart, int skipms, long *offsetms)
00567 {
00568    char *breaks = NULL;
00569    char *end = NULL;
00570    int blen = 2;
00571    int res;
00572    long pause_restart_point = 0;
00573    long offset = 0;
00574 
00575    if (offsetms) {
00576       offset = *offsetms * 8; /* XXX Assumes 8kHz */
00577    }
00578 
00579    if (stop) {
00580       blen += strlen(stop);
00581    }
00582    if (suspend) {
00583       blen += strlen(suspend);
00584    }
00585    if (restart) {
00586       blen += strlen(restart);
00587    }
00588 
00589    if (blen > 2) {
00590       breaks = alloca(blen + 1);
00591       breaks[0] = '\0';
00592       if (stop) {
00593          strcat(breaks, stop);
00594       }
00595       if (suspend) {
00596          strcat(breaks, suspend);
00597       }
00598       if (restart) {
00599          strcat(breaks, restart);
00600       }
00601    }
00602    if (chan->_state != AST_STATE_UP) {
00603       res = ast_answer(chan);
00604    }
00605 
00606    if (file) {
00607       if ((end = strchr(file, ':'))) {
00608          if (!strcasecmp(end, ":end")) {
00609             *end = '\0';
00610             end++;
00611          }
00612       }
00613    }
00614 
00615    for (;;) {
00616       ast_stopstream(chan);
00617       res = ast_streamfile(chan, file, ast_channel_language(chan));
00618       if (!res) {
00619          if (pause_restart_point) {
00620             ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
00621             pause_restart_point = 0;
00622          }
00623          else if (end || offset < 0) {
00624             if (offset == -8) {
00625                offset = 0;
00626             }
00627             ast_verb(3, "ControlPlayback seek to offset %ld from end\n", offset);
00628 
00629             ast_seekstream(chan->stream, offset, SEEK_END);
00630             end = NULL;
00631             offset = 0;
00632          } else if (offset) {
00633             ast_verb(3, "ControlPlayback seek to offset %ld\n", offset);
00634             ast_seekstream(chan->stream, offset, SEEK_SET);
00635             offset = 0;
00636          }
00637          res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
00638       }
00639 
00640       if (res < 1) {
00641          break;
00642       }
00643 
00644       /* We go at next loop if we got the restart char */
00645       if (restart && strchr(restart, res)) {
00646          ast_debug(1, "we'll restart the stream here at next loop\n");
00647          pause_restart_point = 0;
00648          continue;
00649       }
00650 
00651       if (suspend && strchr(suspend, res)) {
00652          pause_restart_point = ast_tellstream(chan->stream);
00653          for (;;) {
00654             ast_stopstream(chan);
00655             if (!(res = ast_waitfordigit(chan, 1000))) {
00656                continue;
00657             } else if (res == -1 || strchr(suspend, res) || (stop && strchr(stop, res))) {
00658                break;
00659             }
00660          }
00661          if (res == *suspend) {
00662             res = 0;
00663             continue;
00664          }
00665       }
00666 
00667       if (res == -1) {
00668          break;
00669       }
00670 
00671       /* if we get one of our stop chars, return it to the calling function */
00672       if (stop && strchr(stop, res)) {
00673          break;
00674       }
00675    }
00676 
00677    if (pause_restart_point) {
00678       offset = pause_restart_point;
00679    } else {
00680       if (chan->stream) {
00681          offset = ast_tellstream(chan->stream);
00682       } else {
00683          offset = -8;  /* indicate end of file */
00684       }
00685    }
00686 
00687    if (offsetms) {
00688       *offsetms = offset / 8; /* samples --> ms ... XXX Assumes 8 kHz */
00689    }
00690 
00691    /* If we are returning a digit cast it as char */
00692    if (res > 0 || chan->stream) {
00693       res = (char)res;
00694    }
00695 
00696    ast_stopstream(chan);
00697 
00698    return res;
00699 }
00700 
00701 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
00702 {
00703    int d = 0;
00704 
00705    ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", fn, ast_channel_name(chan));
00706    if ((d = ast_streamfile(chan, fn, ast_channel_language(chan)))) {
00707       return d;
00708    }
00709 
00710    d = ast_waitstream(chan, AST_DIGIT_ANY);
00711 
00712    ast_stopstream(chan);
00713 
00714    return d;
00715 }
00716 
00717 static int global_silence_threshold = 128;
00718 static int global_maxsilence = 0;
00719 
00720 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
00721  * \param chan Channel to playback to/record from.
00722  * \param playfile Filename of sound to play before recording begins.
00723  * \param recordfile Filename to record to.
00724  * \param maxtime Maximum length of recording (in seconds).
00725  * \param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
00726  * \param duration Where to store actual length of the recorded message (in milliseconds).
00727  * \param sound_duration Where to store the length of the recorded message (in milliseconds), minus any silence
00728  * \param beep Whether to play a beep before starting to record.
00729  * \param silencethreshold
00730  * \param maxsilence Length of silence that will end a recording (in milliseconds).
00731  * \param path Optional filesystem path to unlock.
00732  * \param prepend If true, prepend the recorded audio to an existing file and follow prepend mode recording rules
00733  * \param acceptdtmf DTMF digits that will end the recording.
00734  * \param canceldtmf DTMF digits that will cancel the recording.
00735  * \param skip_confirmation_sound If true, don't play auth-thankyou at end. Nice for custom recording prompts in apps.
00736  *
00737  * \retval -1 failure or hangup
00738  * \retval 'S' Recording ended from silence timeout
00739  * \retval 't' Recording ended from the message exceeding the maximum duration, or via DTMF in prepend mode
00740  * \retval dtmfchar Recording ended via the return value's DTMF character for either cancel or accept.
00741  */
00742 static int __ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence, const char *path, int prepend, const char *acceptdtmf, const char *canceldtmf, int skip_confirmation_sound)
00743 {
00744    int d = 0;
00745    char *fmts;
00746    char comment[256];
00747    int x, fmtcnt = 1, res = -1, outmsg = 0;
00748    struct ast_filestream *others[AST_MAX_FORMATS];
00749    char *sfmt[AST_MAX_FORMATS];
00750    char *stringp = NULL;
00751    time_t start, end;
00752    struct ast_dsp *sildet = NULL;   /* silence detector dsp */
00753    int totalsilence = 0;
00754    int dspsilence = 0;
00755    int olddspsilence = 0;
00756    struct ast_format rfmt;
00757    struct ast_silence_generator *silgen = NULL;
00758    char prependfile[PATH_MAX];
00759 
00760    ast_format_clear(&rfmt);
00761    if (silencethreshold < 0) {
00762       silencethreshold = global_silence_threshold;
00763    }
00764 
00765    if (maxsilence < 0) {
00766       maxsilence = global_maxsilence;
00767    }
00768 
00769    /* barf if no pointer passed to store duration in */
00770    if (!duration) {
00771       ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
00772       return -1;
00773    }
00774 
00775    ast_debug(1, "play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
00776    snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, ast_channel_name(chan));
00777 
00778    if (playfile || beep) {
00779       if (!beep) {
00780          d = ast_play_and_wait(chan, playfile);
00781       }
00782       if (d > -1) {
00783          d = ast_stream_and_wait(chan, "beep", "");
00784       }
00785       if (d < 0) {
00786          return -1;
00787       }
00788    }
00789 
00790    if (prepend) {
00791       ast_copy_string(prependfile, recordfile, sizeof(prependfile));
00792       strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
00793    }
00794 
00795    fmts = ast_strdupa(fmt);
00796 
00797    stringp = fmts;
00798    strsep(&stringp, "|");
00799    ast_debug(1, "Recording Formats: sfmts=%s\n", fmts);
00800    sfmt[0] = ast_strdupa(fmts);
00801 
00802    while ((fmt = strsep(&stringp, "|"))) {
00803       if (fmtcnt > AST_MAX_FORMATS - 1) {
00804          ast_log(LOG_WARNING, "Please increase AST_MAX_FORMATS in file.h\n");
00805          break;
00806       }
00807       sfmt[fmtcnt++] = ast_strdupa(fmt);
00808    }
00809 
00810    end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
00811    for (x = 0; x < fmtcnt; x++) {
00812       others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, AST_FILE_MODE);
00813       ast_verb(3, "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
00814 
00815       if (!others[x]) {
00816          break;
00817       }
00818    }
00819 
00820    if (path) {
00821       ast_unlock_path(path);
00822    }
00823 
00824    if (maxsilence > 0) {
00825       sildet = ast_dsp_new(); /* Create the silence detector */
00826       if (!sildet) {
00827          ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
00828          return -1;
00829       }
00830       ast_dsp_set_threshold(sildet, silencethreshold);
00831       ast_format_copy(&rfmt, &chan->readformat);
00832       res = ast_set_read_format_by_id(chan, AST_FORMAT_SLINEAR);
00833       if (res < 0) {
00834          ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
00835          ast_dsp_free(sildet);
00836          return -1;
00837       }
00838    }
00839 
00840    if (!prepend) {
00841       /* Request a video update */
00842       ast_indicate(chan, AST_CONTROL_VIDUPDATE);
00843 
00844       if (ast_opt_transmit_silence) {
00845          silgen = ast_channel_start_silence_generator(chan);
00846       }
00847    }
00848 
00849    if (x == fmtcnt) {
00850       /* Loop forever, writing the packets we read to the writer(s), until
00851          we read a digit or get a hangup */
00852       struct ast_frame *f;
00853       for (;;) {
00854          if (!(res = ast_waitfor(chan, 2000))) {
00855             ast_debug(1, "One waitfor failed, trying another\n");
00856             /* Try one more time in case of masq */
00857             if (!(res = ast_waitfor(chan, 2000))) {
00858                ast_log(LOG_WARNING, "No audio available on %s??\n", ast_channel_name(chan));
00859                res = -1;
00860             }
00861          }
00862 
00863          if (res < 0) {
00864             f = NULL;
00865             break;
00866          }
00867          if (!(f = ast_read(chan))) {
00868             break;
00869          }
00870          if (f->frametype == AST_FRAME_VOICE) {
00871             /* write each format */
00872             for (x = 0; x < fmtcnt; x++) {
00873                if (prepend && !others[x]) {
00874                   break;
00875                }
00876                res = ast_writestream(others[x], f);
00877             }
00878 
00879             /* Silence Detection */
00880             if (maxsilence > 0) {
00881                dspsilence = 0;
00882                ast_dsp_silence(sildet, f, &dspsilence);
00883                if (olddspsilence > dspsilence) {
00884                   totalsilence += olddspsilence;
00885                }
00886                olddspsilence = dspsilence;
00887 
00888                if (dspsilence > maxsilence) {
00889                   /* Ended happily with silence */
00890                   ast_verb(3, "Recording automatically stopped after a silence of %d seconds\n", dspsilence/1000);
00891                   res = 'S';
00892                   outmsg = 2;
00893                   break;
00894                }
00895             }
00896             /* Exit on any error */
00897             if (res) {
00898                ast_log(LOG_WARNING, "Error writing frame\n");
00899                break;
00900             }
00901          } else if (f->frametype == AST_FRAME_VIDEO) {
00902             /* Write only once */
00903             ast_writestream(others[0], f);
00904          } else if (f->frametype == AST_FRAME_DTMF) {
00905             if (prepend) {
00906             /* stop recording with any digit */
00907                ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
00908                res = 't';
00909                outmsg = 2;
00910                break;
00911             }
00912             if (strchr(acceptdtmf, f->subclass.integer)) {
00913                ast_verb(3, "User ended message by pressing %c\n", f->subclass.integer);
00914                res = f->subclass.integer;
00915                outmsg = 2;
00916                break;
00917             }
00918             if (strchr(canceldtmf, f->subclass.integer)) {
00919                ast_verb(3, "User cancelled message by pressing %c\n", f->subclass.integer);
00920                res = f->subclass.integer;
00921                outmsg = 0;
00922                break;
00923             }
00924          }
00925          if (maxtime) {
00926             end = time(NULL);
00927             if (maxtime < (end - start)) {
00928                ast_verb(3, "Took too long, cutting it short...\n");
00929                res = 't';
00930                outmsg = 2;
00931                break;
00932             }
00933          }
00934          ast_frfree(f);
00935       }
00936       if (!f) {
00937          ast_verb(3, "User hung up\n");
00938          res = -1;
00939          outmsg = 1;
00940       } else {
00941          ast_frfree(f);
00942       }
00943    } else {
00944       ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
00945    }
00946 
00947    if (!prepend) {
00948       if (silgen) {
00949          ast_channel_stop_silence_generator(chan, silgen);
00950       }
00951    }
00952 
00953    /*!\note
00954     * Instead of asking how much time passed (end - start), calculate the number
00955     * of seconds of audio which actually went into the file.  This fixes a
00956     * problem where audio is stopped up on the network and never gets to us.
00957     *
00958     * Note that we still want to use the number of seconds passed for the max
00959     * message, otherwise we could get a situation where this stream is never
00960     * closed (which would create a resource leak).
00961     */
00962    *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
00963    if (sound_duration) {
00964       *sound_duration = *duration;
00965    }
00966 
00967    if (!prepend) {
00968       /* Reduce duration by a total silence amount */
00969       if (olddspsilence <= dspsilence) {
00970          totalsilence += dspsilence;
00971       }
00972 
00973       if (sound_duration) {
00974          if (totalsilence > 0) {
00975             *sound_duration -= (totalsilence - 200) / 1000;
00976          }
00977          if (*sound_duration < 0) {
00978             *sound_duration = 0;
00979          }
00980       }
00981 
00982       if (dspsilence > 0) {
00983          *duration -= (dspsilence - 200) / 1000;
00984       }
00985 
00986       if (*duration < 0) {
00987          *duration = 0;
00988       }
00989 
00990       for (x = 0; x < fmtcnt; x++) {
00991          if (!others[x]) {
00992             break;
00993          }
00994          /*!\note
00995           * If we ended with silence, trim all but the first 200ms of silence
00996           * off the recording.  However, if we ended with '#', we don't want
00997           * to trim ANY part of the recording.
00998           */
00999          if (res > 0 && dspsilence) {
01000             /* rewind only the trailing silence */
01001             ast_stream_rewind(others[x], dspsilence - 200);
01002          }
01003          ast_truncstream(others[x]);
01004          ast_closestream(others[x]);
01005       }
01006    }
01007 
01008    if (prepend && outmsg) {
01009       struct ast_filestream *realfiles[AST_MAX_FORMATS];
01010       struct ast_frame *fr;
01011 
01012       for (x = 0; x < fmtcnt; x++) {
01013          snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
01014          realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
01015          if (!others[x] || !realfiles[x]) {
01016             break;
01017          }
01018          /*!\note Same logic as above. */
01019          if (dspsilence) {
01020             ast_stream_rewind(others[x], dspsilence - 200);
01021          }
01022          ast_truncstream(others[x]);
01023          /* add the original file too */
01024          while ((fr = ast_readframe(realfiles[x]))) {
01025             ast_writestream(others[x], fr);
01026             ast_frfree(fr);
01027          }
01028          ast_closestream(others[x]);
01029          ast_closestream(realfiles[x]);
01030          ast_filerename(prependfile, recordfile, sfmt[x]);
01031          ast_verb(4, "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
01032          ast_filedelete(prependfile, sfmt[x]);
01033       }
01034    }
01035    if (rfmt.id && ast_set_read_format(chan, &rfmt)) {
01036       ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(&rfmt), ast_channel_name(chan));
01037    }
01038    if ((outmsg == 2) && (!skip_confirmation_sound)) {
01039       ast_stream_and_wait(chan, "auth-thankyou", "");
01040    }
01041    if (sildet) {
01042       ast_dsp_free(sildet);
01043    }
01044    return res;
01045 }
01046 
01047 static const char default_acceptdtmf[] = "#";
01048 static const char default_canceldtmf[] = "";
01049 
01050 int ast_play_and_record_full(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int silencethreshold, int maxsilence, const char *path, const char *acceptdtmf, const char *canceldtmf)
01051 {
01052    return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, S_OR(acceptdtmf, default_acceptdtmf), S_OR(canceldtmf, default_canceldtmf), 0);
01053 }
01054 
01055 int ast_play_and_record(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, int *sound_duration, int silencethreshold, int maxsilence, const char *path)
01056 {
01057    return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf, 0);
01058 }
01059 
01060 int ast_play_and_prepend(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt, int *duration, int *sound_duration, int beep, int silencethreshold, int maxsilence)
01061 {
01062    return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, sound_duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf, 1);
01063 }
01064 
01065 /* Channel group core functions */
01066 
01067 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
01068 {
01069    int res = 0;
01070    char tmp[256];
01071    char *grp = NULL, *cat = NULL;
01072 
01073    if (!ast_strlen_zero(data)) {
01074       ast_copy_string(tmp, data, sizeof(tmp));
01075       grp = tmp;
01076       if ((cat = strchr(tmp, '@'))) {
01077          *cat++ = '\0';
01078       }
01079    }
01080 
01081    if (!ast_strlen_zero(grp)) {
01082       ast_copy_string(group, grp, group_max);
01083    } else {
01084       *group = '\0';
01085    }
01086 
01087    if (!ast_strlen_zero(cat)) {
01088       ast_copy_string(category, cat, category_max);
01089    }
01090 
01091    return res;
01092 }
01093 
01094 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
01095 {
01096    int res = 0;
01097    char group[80] = "", category[80] = "";
01098    struct ast_group_info *gi = NULL;
01099    size_t len = 0;
01100 
01101    if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category))) {
01102       return -1;
01103    }
01104 
01105    /* Calculate memory we will need if this is new */
01106    len = sizeof(*gi) + strlen(group) + 1;
01107    if (!ast_strlen_zero(category)) {
01108       len += strlen(category) + 1;
01109    }
01110 
01111    AST_RWLIST_WRLOCK(&groups);
01112    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
01113       if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
01114          AST_RWLIST_REMOVE_CURRENT(group_list);
01115          free(gi);
01116          break;
01117       }
01118    }
01119    AST_RWLIST_TRAVERSE_SAFE_END;
01120 
01121    if (ast_strlen_zero(group)) {
01122       /* Enable unsetting the group */
01123    } else if ((gi = calloc(1, len))) {
01124       gi->chan = chan;
01125       gi->group = (char *) gi + sizeof(*gi);
01126       strcpy(gi->group, group);
01127       if (!ast_strlen_zero(category)) {
01128          gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
01129          strcpy(gi->category, category);
01130       }
01131       AST_RWLIST_INSERT_TAIL(&groups, gi, group_list);
01132    } else {
01133       res = -1;
01134    }
01135 
01136    AST_RWLIST_UNLOCK(&groups);
01137 
01138    return res;
01139 }
01140 
01141 int ast_app_group_get_count(const char *group, const char *category)
01142 {
01143    struct ast_group_info *gi = NULL;
01144    int count = 0;
01145 
01146    if (ast_strlen_zero(group)) {
01147       return 0;
01148    }
01149 
01150    AST_RWLIST_RDLOCK(&groups);
01151    AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
01152       if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
01153          count++;
01154       }
01155    }
01156    AST_RWLIST_UNLOCK(&groups);
01157 
01158    return count;
01159 }
01160 
01161 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
01162 {
01163    struct ast_group_info *gi = NULL;
01164    regex_t regexbuf_group;
01165    regex_t regexbuf_category;
01166    int count = 0;
01167 
01168    if (ast_strlen_zero(groupmatch)) {
01169       ast_log(LOG_NOTICE, "groupmatch empty\n");
01170       return 0;
01171    }
01172 
01173    /* if regex compilation fails, return zero matches */
01174    if (regcomp(&regexbuf_group, groupmatch, REG_EXTENDED | REG_NOSUB)) {
01175       ast_log(LOG_ERROR, "Regex compile failed on: %s\n", groupmatch);
01176       return 0;
01177    }
01178 
01179    if (!ast_strlen_zero(category) && regcomp(&regexbuf_category, category, REG_EXTENDED | REG_NOSUB)) {
01180       ast_log(LOG_ERROR, "Regex compile failed on: %s\n", category);
01181       return 0;
01182    }
01183 
01184    AST_RWLIST_RDLOCK(&groups);
01185    AST_RWLIST_TRAVERSE(&groups, gi, group_list) {
01186       if (!regexec(&regexbuf_group, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !regexec(&regexbuf_category, gi->category, 0, NULL, 0)))) {
01187          count++;
01188       }
01189    }
01190    AST_RWLIST_UNLOCK(&groups);
01191 
01192    regfree(&regexbuf_group);
01193    if (!ast_strlen_zero(category)) {
01194       regfree(&regexbuf_category);
01195    }
01196 
01197    return count;
01198 }
01199 
01200 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
01201 {
01202    struct ast_group_info *gi = NULL;
01203 
01204    AST_RWLIST_WRLOCK(&groups);
01205    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
01206       if (gi->chan == old) {
01207          gi->chan = new;
01208       } else if (gi->chan == new) {
01209          AST_RWLIST_REMOVE_CURRENT(group_list);
01210          ast_free(gi);
01211       }
01212    }
01213    AST_RWLIST_TRAVERSE_SAFE_END;
01214    AST_RWLIST_UNLOCK(&groups);
01215 
01216    return 0;
01217 }
01218 
01219 int ast_app_group_discard(struct ast_channel *chan)
01220 {
01221    struct ast_group_info *gi = NULL;
01222 
01223    AST_RWLIST_WRLOCK(&groups);
01224    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&groups, gi, group_list) {
01225       if (gi->chan == chan) {
01226          AST_RWLIST_REMOVE_CURRENT(group_list);
01227          ast_free(gi);
01228       }
01229    }
01230    AST_RWLIST_TRAVERSE_SAFE_END;
01231    AST_RWLIST_UNLOCK(&groups);
01232 
01233    return 0;
01234 }
01235 
01236 int ast_app_group_list_wrlock(void)
01237 {
01238    return AST_RWLIST_WRLOCK(&groups);
01239 }
01240 
01241 int ast_app_group_list_rdlock(void)
01242 {
01243    return AST_RWLIST_RDLOCK(&groups);
01244 }
01245 
01246 struct ast_group_info *ast_app_group_list_head(void)
01247 {
01248    return AST_RWLIST_FIRST(&groups);
01249 }
01250 
01251 int ast_app_group_list_unlock(void)
01252 {
01253    return AST_RWLIST_UNLOCK(&groups);
01254 }
01255 
01256 #undef ast_app_separate_args
01257 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen);
01258 
01259 unsigned int __ast_app_separate_args(char *buf, char delim, int remove_chars, char **array, int arraylen)
01260 {
01261    int argc;
01262    char *scan, *wasdelim = NULL;
01263    int paren = 0, quote = 0, bracket = 0;
01264 
01265    if (!array || !arraylen) {
01266       return 0;
01267    }
01268 
01269    memset(array, 0, arraylen * sizeof(*array));
01270 
01271    if (!buf) {
01272       return 0;
01273    }
01274 
01275    scan = buf;
01276 
01277    for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
01278       array[argc] = scan;
01279       for (; *scan; scan++) {
01280          if (*scan == '(') {
01281             paren++;
01282          } else if (*scan == ')') {
01283             if (paren) {
01284                paren--;
01285             }
01286          } else if (*scan == '[') {
01287             bracket++;
01288          } else if (*scan == ']') {
01289             if (bracket) {
01290                bracket--;
01291             }
01292          } else if (*scan == '"' && delim != '"') {
01293             quote = quote ? 0 : 1;
01294             if (remove_chars) {
01295                /* Remove quote character from argument */
01296                memmove(scan, scan + 1, strlen(scan));
01297                scan--;
01298             }
01299          } else if (*scan == '\\') {
01300             if (remove_chars) {
01301                /* Literal character, don't parse */
01302                memmove(scan, scan + 1, strlen(scan));
01303             } else {
01304                scan++;
01305             }
01306          } else if ((*scan == delim) && !paren && !quote && !bracket) {
01307             wasdelim = scan;
01308             *scan++ = '\0';
01309             break;
01310          }
01311       }
01312    }
01313 
01314    /* If the last character in the original string was the delimiter, then
01315     * there is one additional argument. */
01316    if (*scan || (scan > buf && (scan - 1) == wasdelim)) {
01317       array[argc++] = scan;
01318    }
01319 
01320    return argc;
01321 }
01322 
01323 /* ABI compatible function */
01324 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
01325 {
01326    return __ast_app_separate_args(buf, delim, 1, array, arraylen);
01327 }
01328 
01329 static enum AST_LOCK_RESULT ast_lock_path_lockfile(const char *path)
01330 {
01331    char *s;
01332    char *fs;
01333    int res;
01334    int fd;
01335    int lp = strlen(path);
01336    time_t start;
01337 
01338    s = alloca(lp + 10);
01339    fs = alloca(lp + 20);
01340 
01341    snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
01342    fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, AST_FILE_MODE);
01343    if (fd < 0) {
01344       ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
01345       return AST_LOCK_PATH_NOT_FOUND;
01346    }
01347    close(fd);
01348 
01349    snprintf(s, strlen(path) + 9, "%s/.lock", path);
01350    start = time(NULL);
01351    while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5)) {
01352       sched_yield();
01353    }
01354 
01355    unlink(fs);
01356 
01357    if (res) {
01358       ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
01359       return AST_LOCK_TIMEOUT;
01360    } else {
01361       ast_debug(1, "Locked path '%s'\n", path);
01362       return AST_LOCK_SUCCESS;
01363    }
01364 }
01365 
01366 static int ast_unlock_path_lockfile(const char *path)
01367 {
01368    char *s;
01369    int res;
01370 
01371    s = alloca(strlen(path) + 10);
01372 
01373    snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
01374 
01375    if ((res = unlink(s))) {
01376       ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
01377    } else {
01378       ast_debug(1, "Unlocked path '%s'\n", path);
01379    }
01380 
01381    return res;
01382 }
01383 
01384 struct path_lock {
01385    AST_LIST_ENTRY(path_lock) le;
01386    int fd;
01387    char *path;
01388 };
01389 
01390 static AST_LIST_HEAD_STATIC(path_lock_list, path_lock);
01391 
01392 static void path_lock_destroy(struct path_lock *obj)
01393 {
01394    if (obj->fd >= 0) {
01395       close(obj->fd);
01396    }
01397    if (obj->path) {
01398       free(obj->path);
01399    }
01400    free(obj);
01401 }
01402 
01403 static enum AST_LOCK_RESULT ast_lock_path_flock(const char *path)
01404 {
01405    char *fs;
01406    int res;
01407    int fd;
01408    time_t start;
01409    struct path_lock *pl;
01410    struct stat st, ost;
01411 
01412    fs = alloca(strlen(path) + 20);
01413 
01414    snprintf(fs, strlen(path) + 19, "%s/lock", path);
01415    if (lstat(fs, &st) == 0) {
01416       if ((st.st_mode & S_IFMT) == S_IFLNK) {
01417          ast_log(LOG_WARNING, "Unable to create lock file "
01418                "'%s': it's already a symbolic link\n",
01419                fs);
01420          return AST_LOCK_FAILURE;
01421       }
01422       if (st.st_nlink > 1) {
01423          ast_log(LOG_WARNING, "Unable to create lock file "
01424                "'%s': %u hard links exist\n",
01425                fs, (unsigned int) st.st_nlink);
01426          return AST_LOCK_FAILURE;
01427       }
01428    }
01429    if ((fd = open(fs, O_WRONLY | O_CREAT, 0600)) < 0) {
01430       ast_log(LOG_WARNING, "Unable to create lock file '%s': %s\n",
01431             fs, strerror(errno));
01432       return AST_LOCK_PATH_NOT_FOUND;
01433    }
01434    if (!(pl = ast_calloc(1, sizeof(*pl)))) {
01435       /* We don't unlink the lock file here, on the possibility that
01436        * someone else created it - better to leave a little mess
01437        * than create a big one by destroying someone else's lock
01438        * and causing something to be corrupted.
01439        */
01440       close(fd);
01441       return AST_LOCK_FAILURE;
01442    }
01443    pl->fd = fd;
01444    pl->path = strdup(path);
01445 
01446    time(&start);
01447    while (
01448       #ifdef SOLARIS
01449       ((res = fcntl(pl->fd, F_SETLK, fcntl(pl->fd, F_GETFL) | O_NONBLOCK)) < 0) &&
01450       #else
01451       ((res = flock(pl->fd, LOCK_EX | LOCK_NB)) < 0) &&
01452       #endif
01453          (errno == EWOULDBLOCK) &&
01454          (time(NULL) - start < 5))
01455       usleep(1000);
01456    if (res) {
01457       ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n",
01458             path, strerror(errno));
01459       /* No unlinking of lock done, since we tried and failed to
01460        * flock() it.
01461        */
01462       path_lock_destroy(pl);
01463       return AST_LOCK_TIMEOUT;
01464    }
01465 
01466    /* Check for the race where the file is recreated or deleted out from
01467     * underneath us.
01468     */
01469    if (lstat(fs, &st) != 0 && fstat(pl->fd, &ost) != 0 &&
01470          st.st_dev != ost.st_dev &&
01471          st.st_ino != ost.st_ino) {
01472       ast_log(LOG_WARNING, "Unable to create lock file '%s': "
01473             "file changed underneath us\n", fs);
01474       path_lock_destroy(pl);
01475       return AST_LOCK_FAILURE;
01476    }
01477 
01478    /* Success: file created, flocked, and is the one we started with */
01479    AST_LIST_LOCK(&path_lock_list);
01480    AST_LIST_INSERT_TAIL(&path_lock_list, pl, le);
01481    AST_LIST_UNLOCK(&path_lock_list);
01482 
01483    ast_debug(1, "Locked path '%s'\n", path);
01484 
01485    return AST_LOCK_SUCCESS;
01486 }
01487 
01488 static int ast_unlock_path_flock(const char *path)
01489 {
01490    char *s;
01491    struct path_lock *p;
01492 
01493    s = alloca(strlen(path) + 20);
01494 
01495    AST_LIST_LOCK(&path_lock_list);
01496    AST_LIST_TRAVERSE_SAFE_BEGIN(&path_lock_list, p, le) {
01497       if (!strcmp(p->path, path)) {
01498          AST_LIST_REMOVE_CURRENT(le);
01499          break;
01500       }
01501    }
01502    AST_LIST_TRAVERSE_SAFE_END;
01503    AST_LIST_UNLOCK(&path_lock_list);
01504 
01505    if (p) {
01506       snprintf(s, strlen(path) + 19, "%s/lock", path);
01507       unlink(s);
01508       path_lock_destroy(p);
01509       ast_debug(1, "Unlocked path '%s'\n", path);
01510    } else {
01511       ast_debug(1, "Failed to unlock path '%s': "
01512             "lock not found\n", path);
01513    }
01514 
01515    return 0;
01516 }
01517 
01518 void ast_set_lock_type(enum AST_LOCK_TYPE type)
01519 {
01520    ast_lock_type = type;
01521 }
01522 
01523 enum AST_LOCK_RESULT ast_lock_path(const char *path)
01524 {
01525    enum AST_LOCK_RESULT r = AST_LOCK_FAILURE;
01526 
01527    switch (ast_lock_type) {
01528    case AST_LOCK_TYPE_LOCKFILE:
01529       r = ast_lock_path_lockfile(path);
01530       break;
01531    case AST_LOCK_TYPE_FLOCK:
01532       r = ast_lock_path_flock(path);
01533       break;
01534    }
01535 
01536    return r;
01537 }
01538 
01539 int ast_unlock_path(const char *path)
01540 {
01541    int r = 0;
01542 
01543    switch (ast_lock_type) {
01544    case AST_LOCK_TYPE_LOCKFILE:
01545       r = ast_unlock_path_lockfile(path);
01546       break;
01547    case AST_LOCK_TYPE_FLOCK:
01548       r = ast_unlock_path_flock(path);
01549       break;
01550    }
01551 
01552    return r;
01553 }
01554 
01555 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
01556 {
01557    int silencethreshold;
01558    int maxsilence = 0;
01559    int res = 0;
01560    int cmd = 0;
01561    int max_attempts = 3;
01562    int attempts = 0;
01563    int recorded = 0;
01564    int message_exists = 0;
01565    /* Note that urgent and private are for flagging messages as such in the future */
01566 
01567    /* barf if no pointer passed to store duration in */
01568    if (!duration) {
01569       ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
01570       return -1;
01571    }
01572 
01573    cmd = '3';   /* Want to start by recording */
01574 
01575    silencethreshold = ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE);
01576 
01577    while ((cmd >= 0) && (cmd != 't')) {
01578       switch (cmd) {
01579       case '1':
01580          if (!message_exists) {
01581             /* In this case, 1 is to record a message */
01582             cmd = '3';
01583             break;
01584          } else {
01585             ast_stream_and_wait(chan, "vm-msgsaved", "");
01586             cmd = 't';
01587             return res;
01588          }
01589       case '2':
01590          /* Review */
01591          ast_verb(3, "Reviewing the recording\n");
01592          cmd = ast_stream_and_wait(chan, recordfile, AST_DIGIT_ANY);
01593          break;
01594       case '3':
01595          message_exists = 0;
01596          /* Record */
01597          ast_verb(3, "R%secording\n", recorded == 1 ? "e-r" : "");
01598          recorded = 1;
01599          if ((cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, NULL, silencethreshold, maxsilence, path)) == -1) {
01600             /* User has hung up, no options to give */
01601             return cmd;
01602          }
01603          if (cmd == '0') {
01604             break;
01605          } else if (cmd == '*') {
01606             break;
01607          } else {
01608             /* If all is well, a message exists */
01609             message_exists = 1;
01610             cmd = 0;
01611          }
01612          break;
01613       case '4':
01614       case '5':
01615       case '6':
01616       case '7':
01617       case '8':
01618       case '9':
01619       case '*':
01620       case '#':
01621          cmd = ast_play_and_wait(chan, "vm-sorry");
01622          break;
01623       default:
01624          if (message_exists) {
01625             cmd = ast_play_and_wait(chan, "vm-review");
01626          } else {
01627             if (!(cmd = ast_play_and_wait(chan, "vm-torerecord"))) {
01628                cmd = ast_waitfordigit(chan, 600);
01629             }
01630          }
01631 
01632          if (!cmd) {
01633             cmd = ast_waitfordigit(chan, 6000);
01634          }
01635          if (!cmd) {
01636             attempts++;
01637          }
01638          if (attempts > max_attempts) {
01639             cmd = 't';
01640          }
01641       }
01642    }
01643    if (cmd == 't') {
01644       cmd = 0;
01645    }
01646    return cmd;
01647 }
01648 
01649 #define RES_UPONE (1 << 16)
01650 #define RES_EXIT  (1 << 17)
01651 #define RES_REPEAT (1 << 18)
01652 #define RES_RESTART ((1 << 19) | RES_REPEAT)
01653 
01654 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
01655 
01656 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
01657 {
01658    int res;
01659    int (*ivr_func)(struct ast_channel *, void *);
01660    char *c;
01661    char *n;
01662 
01663    switch (option->action) {
01664    case AST_ACTION_UPONE:
01665       return RES_UPONE;
01666    case AST_ACTION_EXIT:
01667       return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
01668    case AST_ACTION_REPEAT:
01669       return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
01670    case AST_ACTION_RESTART:
01671       return RES_RESTART ;
01672    case AST_ACTION_NOOP:
01673       return 0;
01674    case AST_ACTION_BACKGROUND:
01675       res = ast_stream_and_wait(chan, (char *)option->adata, AST_DIGIT_ANY);
01676       if (res < 0) {
01677          ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
01678          res = 0;
01679       }
01680       return res;
01681    case AST_ACTION_PLAYBACK:
01682       res = ast_stream_and_wait(chan, (char *)option->adata, "");
01683       if (res < 0) {
01684          ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
01685          res = 0;
01686       }
01687       return res;
01688    case AST_ACTION_MENU:
01689       if ((res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata)) == -2) {
01690          /* Do not pass entry errors back up, treat as though it was an "UPONE" */
01691          res = 0;
01692       }
01693       return res;
01694    case AST_ACTION_WAITOPTION:
01695       if (!(res = ast_waitfordigit(chan, chan->pbx ? chan->pbx->rtimeoutms : 10000))) {
01696          return 't';
01697       }
01698       return res;
01699    case AST_ACTION_CALLBACK:
01700       ivr_func = option->adata;
01701       res = ivr_func(chan, cbdata);
01702       return res;
01703    case AST_ACTION_TRANSFER:
01704       res = ast_parseable_goto(chan, option->adata);
01705       return 0;
01706    case AST_ACTION_PLAYLIST:
01707    case AST_ACTION_BACKLIST:
01708       res = 0;
01709       c = ast_strdupa(option->adata);
01710       while ((n = strsep(&c, ";"))) {
01711          if ((res = ast_stream_and_wait(chan, n,
01712                (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : ""))) {
01713             break;
01714          }
01715       }
01716       ast_stopstream(chan);
01717       return res;
01718    default:
01719       ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
01720       return 0;
01721    }
01722    return -1;
01723 }
01724 
01725 static int option_exists(struct ast_ivr_menu *menu, char *option)
01726 {
01727    int x;
01728    for (x = 0; menu->options[x].option; x++) {
01729       if (!strcasecmp(menu->options[x].option, option)) {
01730          return x;
01731       }
01732    }
01733    return -1;
01734 }
01735 
01736 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
01737 {
01738    int x;
01739    for (x = 0; menu->options[x].option; x++) {
01740       if ((!strncasecmp(menu->options[x].option, option, strlen(option))) &&
01741             (menu->options[x].option[strlen(option)])) {
01742          return x;
01743       }
01744    }
01745    return -1;
01746 }
01747 
01748 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
01749 {
01750    int res = 0;
01751    int ms;
01752    while (option_matchmore(menu, exten)) {
01753       ms = chan->pbx ? chan->pbx->dtimeoutms : 5000;
01754       if (strlen(exten) >= maxexten - 1) {
01755          break;
01756       }
01757       if ((res = ast_waitfordigit(chan, ms)) < 1) {
01758          break;
01759       }
01760       exten[strlen(exten) + 1] = '\0';
01761       exten[strlen(exten)] = res;
01762    }
01763    return res > 0 ? 0 : res;
01764 }
01765 
01766 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
01767 {
01768    /* Execute an IVR menu structure */
01769    int res = 0;
01770    int pos = 0;
01771    int retries = 0;
01772    char exten[AST_MAX_EXTENSION] = "s";
01773    if (option_exists(menu, "s") < 0) {
01774       strcpy(exten, "g");
01775       if (option_exists(menu, "g") < 0) {
01776          ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
01777          return -1;
01778       }
01779    }
01780    while (!res) {
01781       while (menu->options[pos].option) {
01782          if (!strcasecmp(menu->options[pos].option, exten)) {
01783             res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
01784             ast_debug(1, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
01785             if (res < 0) {
01786                break;
01787             } else if (res & RES_UPONE) {
01788                return 0;
01789             } else if (res & RES_EXIT) {
01790                return res;
01791             } else if (res & RES_REPEAT) {
01792                int maxretries = res & 0xffff;
01793                if ((res & RES_RESTART) == RES_RESTART) {
01794                   retries = 0;
01795                } else {
01796                   retries++;
01797                }
01798                if (!maxretries) {
01799                   maxretries = 3;
01800                }
01801                if ((maxretries > 0) && (retries >= maxretries)) {
01802                   ast_debug(1, "Max retries %d exceeded\n", maxretries);
01803                   return -2;
01804                } else {
01805                   if (option_exists(menu, "g") > -1) {
01806                      strcpy(exten, "g");
01807                   } else if (option_exists(menu, "s") > -1) {
01808                      strcpy(exten, "s");
01809                   }
01810                }
01811                pos = 0;
01812                continue;
01813             } else if (res && strchr(AST_DIGIT_ANY, res)) {
01814                ast_debug(1, "Got start of extension, %c\n", res);
01815                exten[1] = '\0';
01816                exten[0] = res;
01817                if ((res = read_newoption(chan, menu, exten, sizeof(exten)))) {
01818                   break;
01819                }
01820                if (option_exists(menu, exten) < 0) {
01821                   if (option_exists(menu, "i")) {
01822                      ast_debug(1, "Invalid extension entered, going to 'i'!\n");
01823                      strcpy(exten, "i");
01824                      pos = 0;
01825                      continue;
01826                   } else {
01827                      ast_debug(1, "Aborting on invalid entry, with no 'i' option!\n");
01828                      res = -2;
01829                      break;
01830                   }
01831                } else {
01832                   ast_debug(1, "New existing extension: %s\n", exten);
01833                   pos = 0;
01834                   continue;
01835                }
01836             }
01837          }
01838          pos++;
01839       }
01840       ast_debug(1, "Stopping option '%s', res is %d\n", exten, res);
01841       pos = 0;
01842       if (!strcasecmp(exten, "s")) {
01843          strcpy(exten, "g");
01844       } else {
01845          break;
01846       }
01847    }
01848    return res;
01849 }
01850 
01851 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
01852 {
01853    int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
01854    /* Hide internal coding */
01855    return res > 0 ? 0 : res;
01856 }
01857 
01858 char *ast_read_textfile(const char *filename)
01859 {
01860    int fd, count = 0, res;
01861    char *output = NULL;
01862    struct stat filesize;
01863 
01864    if (stat(filename, &filesize) == -1) {
01865       ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
01866       return NULL;
01867    }
01868 
01869    count = filesize.st_size + 1;
01870 
01871    if ((fd = open(filename, O_RDONLY)) < 0) {
01872       ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
01873       return NULL;
01874    }
01875 
01876    if ((output = ast_malloc(count))) {
01877       res = read(fd, output, count - 1);
01878       if (res == count - 1) {
01879          output[res] = '\0';
01880       } else {
01881          ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
01882          ast_free(output);
01883          output = NULL;
01884       }
01885    }
01886 
01887    close(fd);
01888 
01889    return output;
01890 }
01891 
01892 static int parse_options(const struct ast_app_option *options, void *_flags, char **args, char *optstr, int flaglen)
01893 {
01894    char *s, *arg;
01895    int curarg, res = 0;
01896    unsigned int argloc;
01897    struct ast_flags *flags = _flags;
01898    struct ast_flags64 *flags64 = _flags;
01899 
01900    if (flaglen == 32) {
01901       ast_clear_flag(flags, AST_FLAGS_ALL);
01902    } else {
01903       flags64->flags = 0;
01904    }
01905 
01906    if (!optstr) {
01907       return 0;
01908    }
01909 
01910    s = optstr;
01911    while (*s) {
01912       curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
01913       argloc = options[curarg].arg_index;
01914       if (*s == '(') {
01915          int paren = 1, quote = 0;
01916          int parsequotes = (s[1] == '"') ? 1 : 0;
01917 
01918          /* Has argument */
01919          arg = ++s;
01920          for (; *s; s++) {
01921             if (*s == '(' && !quote) {
01922                paren++;
01923             } else if (*s == ')' && !quote) {
01924                /* Count parentheses, unless they're within quotes (or backslashed, below) */
01925                paren--;
01926             } else if (*s == '"' && parsequotes) {
01927                /* Leave embedded quotes alone, unless they are the first character */
01928                quote = quote ? 0 : 1;
01929                ast_copy_string(s, s + 1, INT_MAX);
01930                s--;
01931             } else if (*s == '\\') {
01932                if (!quote) {
01933                   /* If a backslash is found outside of quotes, remove it */
01934                   ast_copy_string(s, s + 1, INT_MAX);
01935                } else if (quote && s[1] == '"') {
01936                   /* Backslash for a quote character within quotes, remove the backslash */
01937                   ast_copy_string(s, s + 1, INT_MAX);
01938                } else {
01939                   /* Backslash within quotes, keep both characters */
01940                   s++;
01941                }
01942             }
01943 
01944             if (paren == 0) {
01945                break;
01946             }
01947          }
01948          /* This will find the closing paren we found above, or none, if the string ended before we found one. */
01949          if ((s = strchr(s, ')'))) {
01950             if (argloc) {
01951                args[argloc - 1] = arg;
01952             }
01953             *s++ = '\0';
01954          } else {
01955             ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
01956             res = -1;
01957             break;
01958          }
01959       } else if (argloc) {
01960          args[argloc - 1] = "";
01961       }
01962       if (flaglen == 32) {
01963          ast_set_flag(flags, options[curarg].flag);
01964       } else {
01965          ast_set_flag64(flags64, options[curarg].flag);
01966       }
01967    }
01968 
01969    return res;
01970 }
01971 
01972 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
01973 {
01974    return parse_options(options, flags, args, optstr, 32);
01975 }
01976 
01977 int ast_app_parse_options64(const struct ast_app_option *options, struct ast_flags64 *flags, char **args, char *optstr)
01978 {
01979    return parse_options(options, flags, args, optstr, 64);
01980 }
01981 
01982 void ast_app_options2str64(const struct ast_app_option *options, struct ast_flags64 *flags, char *buf, size_t len)
01983 {
01984    unsigned int i, found = 0;
01985    for (i = 32; i < 128 && found < len; i++) {
01986       if (ast_test_flag64(flags, options[i].flag)) {
01987          buf[found++] = i;
01988       }
01989    }
01990    buf[found] = '\0';
01991 }
01992 
01993 int ast_get_encoded_char(const char *stream, char *result, size_t *consumed)
01994 {
01995    int i;
01996    *consumed = 1;
01997    *result = 0;
01998    if (ast_strlen_zero(stream)) {
01999       *consumed = 0;
02000       return -1;
02001    }
02002 
02003    if (*stream == '\\') {
02004       *consumed = 2;
02005       switch (*(stream + 1)) {
02006       case 'n':
02007          *result = '\n';
02008          break;
02009       case 'r':
02010          *result = '\r';
02011          break;
02012       case 't':
02013          *result = '\t';
02014          break;
02015       case 'x':
02016          /* Hexadecimal */
02017          if (strchr("0123456789ABCDEFabcdef", *(stream + 2)) && *(stream + 2) != '\0') {
02018             *consumed = 3;
02019             if (*(stream + 2) <= '9') {
02020                *result = *(stream + 2) - '0';
02021             } else if (*(stream + 2) <= 'F') {
02022                *result = *(stream + 2) - 'A' + 10;
02023             } else {
02024                *result = *(stream + 2) - 'a' + 10;
02025             }
02026          } else {
02027             ast_log(LOG_ERROR, "Illegal character '%c' in hexadecimal string\n", *(stream + 2));
02028             return -1;
02029          }
02030 
02031          if (strchr("0123456789ABCDEFabcdef", *(stream + 3)) && *(stream + 3) != '\0') {
02032             *consumed = 4;
02033             *result <<= 4;
02034             if (*(stream + 3) <= '9') {
02035                *result += *(stream + 3) - '0';
02036             } else if (*(stream + 3) <= 'F') {
02037                *result += *(stream + 3) - 'A' + 10;
02038             } else {
02039                *result += *(stream + 3) - 'a' + 10;
02040             }
02041          }
02042          break;
02043       case '0':
02044          /* Octal */
02045          *consumed = 2;
02046          for (i = 2; ; i++) {
02047             if (strchr("01234567", *(stream + i)) && *(stream + i) != '\0') {
02048                (*consumed)++;
02049                ast_debug(5, "result was %d, ", *result);
02050                *result <<= 3;
02051                *result += *(stream + i) - '0';
02052                ast_debug(5, "is now %d\n", *result);
02053             } else {
02054                break;
02055             }
02056          }
02057          break;
02058       default:
02059          *result = *(stream + 1);
02060       }
02061    } else {
02062       *result = *stream;
02063       *consumed = 1;
02064    }
02065    return 0;
02066 }
02067 
02068 char *ast_get_encoded_str(const char *stream, char *result, size_t result_size)
02069 {
02070    char *cur = result;
02071    size_t consumed;
02072 
02073    while (cur < result + result_size - 1 && !ast_get_encoded_char(stream, cur, &consumed)) {
02074       cur++;
02075       stream += consumed;
02076    }
02077    *cur = '\0';
02078    return result;
02079 }
02080 
02081 int ast_str_get_encoded_str(struct ast_str **str, int maxlen, const char *stream)
02082 {
02083    char next, *buf;
02084    size_t offset = 0;
02085    size_t consumed;
02086 
02087    if (strchr(stream, '\\')) {
02088       while (!ast_get_encoded_char(stream, &next, &consumed)) {
02089          if (offset + 2 > ast_str_size(*str) && maxlen > -1) {
02090             ast_str_make_space(str, maxlen > 0 ? maxlen : (ast_str_size(*str) + 48) * 2 - 48);
02091          }
02092          if (offset + 2 > ast_str_size(*str)) {
02093             break;
02094          }
02095          buf = ast_str_buffer(*str);
02096          buf[offset++] = next;
02097          stream += consumed;
02098       }
02099       buf = ast_str_buffer(*str);
02100       buf[offset++] = '\0';
02101       ast_str_update(*str);
02102    } else {
02103       ast_str_set(str, maxlen, "%s", stream);
02104    }
02105    return 0;
02106 }
02107 
02108 void ast_close_fds_above_n(int n)
02109 {
02110    closefrom(n + 1);
02111 }
02112 
02113 int ast_safe_fork(int stop_reaper)
02114 {
02115    sigset_t signal_set, old_set;
02116    int pid;
02117 
02118    /* Don't let the default signal handler for children reap our status */
02119    if (stop_reaper) {
02120       ast_replace_sigchld();
02121    }
02122 
02123    sigfillset(&signal_set);
02124    pthread_sigmask(SIG_BLOCK, &signal_set, &old_set);
02125 
02126    pid = fork();
02127 
02128    if (pid != 0) {
02129       /* Fork failed or parent */
02130       pthread_sigmask(SIG_SETMASK, &old_set, NULL);
02131       if (!stop_reaper && pid > 0) {
02132          struct zombie *cur = ast_calloc(1, sizeof(*cur));
02133          if (cur) {
02134             cur->pid = pid;
02135             AST_LIST_LOCK(&zombies);
02136             AST_LIST_INSERT_TAIL(&zombies, cur, list);
02137             AST_LIST_UNLOCK(&zombies);
02138             if (shaun_of_the_dead_thread == AST_PTHREADT_NULL) {
02139                if (ast_pthread_create_background(&shaun_of_the_dead_thread, NULL, shaun_of_the_dead, NULL)) {
02140                   ast_log(LOG_ERROR, "Shaun of the Dead wants to kill zombies, but can't?!!\n");
02141                   shaun_of_the_dead_thread = AST_PTHREADT_NULL;
02142                }
02143             }
02144          }
02145       }
02146       return pid;
02147    } else {
02148       /* Child */
02149 #ifdef HAVE_CAP
02150       cap_t cap = cap_from_text("cap_net_admin-eip");
02151 
02152       if (cap_set_proc(cap)) {
02153          ast_log(LOG_WARNING, "Unable to remove capabilities.\n");
02154       }
02155       cap_free(cap);
02156 #endif
02157 
02158       /* Before we unblock our signals, return our trapped signals back to the defaults */
02159       signal(SIGHUP, SIG_DFL);
02160       signal(SIGCHLD, SIG_DFL);
02161       signal(SIGINT, SIG_DFL);
02162       signal(SIGURG, SIG_DFL);
02163       signal(SIGTERM, SIG_DFL);
02164       signal(SIGPIPE, SIG_DFL);
02165       signal(SIGXFSZ, SIG_DFL);
02166 
02167       /* unblock important signal handlers */
02168       if (pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL)) {
02169          ast_log(LOG_WARNING, "unable to unblock signals: %s\n", strerror(errno));
02170          _exit(1);
02171       }
02172 
02173       return pid;
02174    }
02175 }
02176 
02177 void ast_safe_fork_cleanup(void)
02178 {
02179    ast_unreplace_sigchld();
02180 }
02181 
02182 int ast_app_parse_timelen(const char *timestr, int *result, enum ast_timelen unit)
02183 {
02184    int res;
02185    char u[10];
02186 #ifdef HAVE_LONG_DOUBLE_WIDER
02187    long double amount;
02188    #define FMT "%30Lf%9s"
02189 #else
02190    double amount;
02191    #define FMT "%30lf%9s"
02192 #endif
02193    if (!timestr) {
02194       return -1;
02195    }
02196 
02197    if ((res = sscanf(timestr, FMT, &amount, u)) == 0) {
02198 #undef FMT
02199       return -1;
02200    } else if (res == 2) {
02201       switch (u[0]) {
02202       case 'h':
02203       case 'H':
02204          unit = TIMELEN_HOURS;
02205          break;
02206       case 's':
02207       case 'S':
02208          unit = TIMELEN_SECONDS;
02209          break;
02210       case 'm':
02211       case 'M':
02212          if (toupper(u[1]) == 'S') {
02213             unit = TIMELEN_MILLISECONDS;
02214          } else if (u[1] == '\0') {
02215             unit = TIMELEN_MINUTES;
02216          }
02217          break;
02218       }
02219    }
02220 
02221    switch (unit) {
02222    case TIMELEN_HOURS:
02223       amount *= 60;
02224       /* fall-through */
02225    case TIMELEN_MINUTES:
02226       amount *= 60;
02227       /* fall-through */
02228    case TIMELEN_SECONDS:
02229       amount *= 1000;
02230       /* fall-through */
02231    case TIMELEN_MILLISECONDS:
02232       ;
02233    }
02234    *result = amount > INT_MAX ? INT_MAX : (int) amount;
02235    return 0;
02236 }
02237 

Generated on Sat Feb 11 06:33:00 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6