Wed Oct 28 13:30:47 2009

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

Generated on Wed Oct 28 13:30:47 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.6