Tue Sep 30 01:19:28 2008

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: 110628 $")
00029 
00030 #include <stdio.h>
00031 #include <stdlib.h>
00032 #include <string.h>
00033 #include <sys/time.h>
00034 #include <signal.h>
00035 #include <errno.h>
00036 #include <unistd.h>
00037 #include <dirent.h>
00038 #include <sys/types.h>
00039 #include <sys/stat.h>
00040 #include <regex.h>
00041 
00042 #include "asterisk/channel.h"
00043 #include "asterisk/pbx.h"
00044 #include "asterisk/file.h"
00045 #include "asterisk/app.h"
00046 #include "asterisk/dsp.h"
00047 #include "asterisk/logger.h"
00048 #include "asterisk/options.h"
00049 #include "asterisk/utils.h"
00050 #include "asterisk/lock.h"
00051 #include "asterisk/indications.h"
00052 #include "asterisk/linkedlists.h"
00053 
00054 #define MAX_OTHER_FORMATS 10
00055 
00056 static AST_LIST_HEAD_STATIC(groups, ast_group_info);
00057 
00058 /* !
00059 This function presents a dialtone and reads an extension into 'collect' 
00060 which must be a pointer to a **pre-initialized** array of char having a 
00061 size of 'size' suitable for writing to.  It will collect no more than the smaller 
00062 of 'maxlen' or 'size' minus the original strlen() of collect digits.
00063 \return 0 if extension does not exist, 1 if extension exists
00064 */
00065 int ast_app_dtget(struct ast_channel *chan, const char *context, char *collect, size_t size, int maxlen, int timeout) 
00066 {
00067    struct tone_zone_sound *ts;
00068    int res=0, x=0;
00069 
00070    if (maxlen > size)
00071       maxlen = size;
00072    
00073    if (!timeout && chan->pbx)
00074       timeout = chan->pbx->dtimeout;
00075    else if (!timeout)
00076       timeout = 5;
00077    
00078    ts = ast_get_indication_tone(chan->zone,"dial");
00079    if (ts && ts->data[0])
00080       res = ast_playtones_start(chan, 0, ts->data, 0);
00081    else 
00082       ast_log(LOG_NOTICE,"Huh....? no dial for indications?\n");
00083    
00084    for (x = strlen(collect); x < maxlen; ) {
00085       res = ast_waitfordigit(chan, timeout);
00086       if (!ast_ignore_pattern(context, collect))
00087          ast_playtones_stop(chan);
00088       if (res < 1)
00089          break;
00090       if (res == '#')
00091          break;
00092       collect[x++] = res;
00093       if (!ast_matchmore_extension(chan, context, collect, 1, chan->cid.cid_num))
00094          break;
00095    }
00096    if (res >= 0)
00097       res = ast_exists_extension(chan, context, collect, 1, chan->cid.cid_num) ? 1 : 0;
00098    return res;
00099 }
00100 
00101 /*! \param c The channel to read from
00102  *  \param prompt The file to stream to the channel
00103  *  \param s The string to read in to.  Must be at least the size of your length
00104  *  \param maxlen How many digits to read (maximum)
00105  *  \param timeout set timeout to 0 for "standard" timeouts. Set timeout to -1 for 
00106  *      "ludicrous time" (essentially never times out) */
00107 int ast_app_getdata(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout)
00108 {
00109    int res,to,fto;
00110    /* XXX Merge with full version? XXX */
00111    if (maxlen)
00112       s[0] = '\0';
00113    if (prompt) {
00114       res = ast_streamfile(c, prompt, c->language);
00115       if (res < 0)
00116          return res;
00117    }
00118    fto = c->pbx ? c->pbx->rtimeout * 1000 : 6000;
00119    to = c->pbx ? c->pbx->dtimeout * 1000 : 2000;
00120 
00121    if (timeout > 0) 
00122       fto = to = timeout;
00123    if (timeout < 0) 
00124       fto = to = 1000000000;
00125    res = ast_readstring(c, s, maxlen, to, fto, "#");
00126    return res;
00127 }
00128 
00129 
00130 int ast_app_getdata_full(struct ast_channel *c, char *prompt, char *s, int maxlen, int timeout, int audiofd, int ctrlfd)
00131 {
00132    int res, to, fto;
00133    if (prompt) {
00134       res = ast_streamfile(c, prompt, c->language);
00135       if (res < 0)
00136          return res;
00137    }
00138    fto = 6000;
00139    to = 2000;
00140    if (timeout > 0) 
00141       fto = to = timeout;
00142    if (timeout < 0) 
00143       fto = to = 1000000000;
00144    res = ast_readstring_full(c, s, maxlen, to, fto, "#", audiofd, ctrlfd);
00145    return res;
00146 }
00147 
00148 static int (*ast_has_voicemail_func)(const char *mailbox, const char *folder) = NULL;
00149 static int (*ast_inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs) = NULL;
00150 static int (*ast_messagecount_func)(const char *context, const char *mailbox, const char *folder) = NULL;
00151 
00152 void ast_install_vm_functions(int (*has_voicemail_func)(const char *mailbox, const char *folder),
00153                int (*inboxcount_func)(const char *mailbox, int *newmsgs, int *oldmsgs),
00154                int (*messagecount_func)(const char *context, const char *mailbox, const char *folder))
00155 {
00156    ast_has_voicemail_func = has_voicemail_func;
00157    ast_inboxcount_func = inboxcount_func;
00158    ast_messagecount_func = messagecount_func;
00159 }
00160 
00161 void ast_uninstall_vm_functions(void)
00162 {
00163    ast_has_voicemail_func = NULL;
00164    ast_inboxcount_func = NULL;
00165    ast_messagecount_func = NULL;
00166 }
00167 
00168 int ast_app_has_voicemail(const char *mailbox, const char *folder)
00169 {
00170    static int warned = 0;
00171    if (ast_has_voicemail_func)
00172       return ast_has_voicemail_func(mailbox, folder);
00173 
00174    if ((option_verbose > 2) && !warned) {
00175       ast_verbose(VERBOSE_PREFIX_3 "Message check requested for mailbox %s/folder %s but voicemail not loaded.\n", mailbox, folder ? folder : "INBOX");
00176       warned++;
00177    }
00178    return 0;
00179 }
00180 
00181 
00182 int ast_app_inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
00183 {
00184    static int warned = 0;
00185    if (newmsgs)
00186       *newmsgs = 0;
00187    if (oldmsgs)
00188       *oldmsgs = 0;
00189    if (ast_inboxcount_func)
00190       return ast_inboxcount_func(mailbox, newmsgs, oldmsgs);
00191 
00192    if (!warned && (option_verbose > 2)) {
00193       warned++;
00194       ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s but voicemail not loaded.\n", mailbox);
00195    }
00196 
00197    return 0;
00198 }
00199 
00200 int ast_app_messagecount(const char *context, const char *mailbox, const char *folder)
00201 {
00202    static int warned = 0;
00203    if (ast_messagecount_func)
00204       return ast_messagecount_func(context, mailbox, folder);
00205 
00206    if (!warned && (option_verbose > 2)) {
00207       warned++;
00208       ast_verbose(VERBOSE_PREFIX_3 "Message count requested for mailbox %s@%s/%s but voicemail not loaded.\n", mailbox, context, folder);
00209    }
00210 
00211    return 0;
00212 }
00213 
00214 int ast_dtmf_stream(struct ast_channel *chan, struct ast_channel *peer, const char *digits, int between) 
00215 {
00216    const char *ptr;
00217    int res = 0;
00218    struct ast_silence_generator *silgen = NULL;
00219 
00220    if (!between)
00221       between = 100;
00222 
00223    if (peer)
00224       res = ast_autoservice_start(peer);
00225 
00226    if (!res)
00227       res = ast_waitfor(chan, 100);
00228 
00229    /* ast_waitfor will return the number of remaining ms on success */
00230    if (res < 0)
00231       return res;
00232 
00233    if (ast_opt_transmit_silence) {
00234       silgen = ast_channel_start_silence_generator(chan);
00235    }
00236 
00237    for (ptr = digits; *ptr; ptr++) {
00238       if (*ptr == 'w') {
00239          /* 'w' -- wait half a second */
00240          if ((res = ast_safe_sleep(chan, 500)))
00241             break;
00242       } else if (strchr("0123456789*#abcdfABCDF", *ptr)) {
00243          /* Character represents valid DTMF */
00244          if (*ptr == 'f' || *ptr == 'F') {
00245             /* ignore return values if not supported by channel */
00246             ast_indicate(chan, AST_CONTROL_FLASH);
00247          } else
00248             ast_senddigit(chan, *ptr);
00249          /* pause between digits */
00250          if ((res = ast_safe_sleep(chan, between)))
00251             break;
00252       } else
00253          ast_log(LOG_WARNING, "Illegal DTMF character '%c' in string. (0-9*#aAbBcCdD allowed)\n",*ptr);
00254    }
00255 
00256    if (peer) {
00257       /* Stop autoservice on the peer channel, but don't overwrite any error condition 
00258          that has occurred previously while acting on the primary channel */
00259       if (ast_autoservice_stop(peer) && !res)
00260          res = -1;
00261    }
00262 
00263    if (silgen) {
00264       ast_channel_stop_silence_generator(chan, silgen);
00265    }
00266 
00267    return res;
00268 }
00269 
00270 struct linear_state {
00271    int fd;
00272    int autoclose;
00273    int allowoverride;
00274    int origwfmt;
00275 };
00276 
00277 static void linear_release(struct ast_channel *chan, void *params)
00278 {
00279    struct linear_state *ls = params;
00280    if (ls->origwfmt && ast_set_write_format(chan, ls->origwfmt)) {
00281       ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%d'\n", chan->name, ls->origwfmt);
00282    }
00283    if (ls->autoclose)
00284       close(ls->fd);
00285    free(params);
00286 }
00287 
00288 static int linear_generator(struct ast_channel *chan, void *data, int len, int samples)
00289 {
00290    struct ast_frame f;
00291    short buf[2048 + AST_FRIENDLY_OFFSET / 2];
00292    struct linear_state *ls = data;
00293    int res;
00294    len = samples * 2;
00295    if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
00296       ast_log(LOG_WARNING, "Can't generate %d bytes of data!\n" ,len);
00297       len = sizeof(buf) - AST_FRIENDLY_OFFSET;
00298    }
00299    memset(&f, 0, sizeof(f));
00300    res = read(ls->fd, buf + AST_FRIENDLY_OFFSET/2, len);
00301    if (res > 0) {
00302       f.frametype = AST_FRAME_VOICE;
00303       f.subclass = AST_FORMAT_SLINEAR;
00304       f.data = buf + AST_FRIENDLY_OFFSET/2;
00305       f.datalen = res;
00306       f.samples = res / 2;
00307       f.offset = AST_FRIENDLY_OFFSET;
00308       ast_write(chan, &f);
00309       if (res == len)
00310          return 0;
00311    }
00312    return -1;
00313 }
00314 
00315 static void *linear_alloc(struct ast_channel *chan, void *params)
00316 {
00317    struct linear_state *ls;
00318    /* In this case, params is already malloc'd */
00319    if (params) {
00320       ls = params;
00321       if (ls->allowoverride)
00322          ast_set_flag(chan, AST_FLAG_WRITE_INT);
00323       else
00324          ast_clear_flag(chan, AST_FLAG_WRITE_INT);
00325       ls->origwfmt = chan->writeformat;
00326       if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
00327          ast_log(LOG_WARNING, "Unable to set '%s' to linear format (write)\n", chan->name);
00328          free(ls);
00329          ls = params = NULL;
00330       }
00331    }
00332    return params;
00333 }
00334 
00335 static struct ast_generator linearstream = 
00336 {
00337    alloc: linear_alloc,
00338    release: linear_release,
00339    generate: linear_generator,
00340 };
00341 
00342 int ast_linear_stream(struct ast_channel *chan, const char *filename, int fd, int allowoverride)
00343 {
00344    struct linear_state *lin;
00345    char tmpf[256];
00346    int res = -1;
00347    int autoclose = 0;
00348    if (fd < 0) {
00349       if (ast_strlen_zero(filename))
00350          return -1;
00351       autoclose = 1;
00352       if (filename[0] == '/') 
00353          ast_copy_string(tmpf, filename, sizeof(tmpf));
00354       else
00355          snprintf(tmpf, sizeof(tmpf), "%s/%s/%s", (char *)ast_config_AST_DATA_DIR, "sounds", filename);
00356       fd = open(tmpf, O_RDONLY);
00357       if (fd < 0){
00358          ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", tmpf, strerror(errno));
00359          return -1;
00360       }
00361    }
00362    if ((lin = ast_calloc(1, sizeof(*lin)))) {
00363       lin->fd = fd;
00364       lin->allowoverride = allowoverride;
00365       lin->autoclose = autoclose;
00366       res = ast_activate_generator(chan, &linearstream, lin);
00367    }
00368    return res;
00369 }
00370 
00371 int ast_control_streamfile(struct ast_channel *chan, const char *file,
00372             const char *fwd, const char *rev,
00373             const char *stop, const char *pause,
00374             const char *restart, int skipms) 
00375 {
00376    char *breaks = NULL;
00377    char *end = NULL;
00378    int blen = 2;
00379    int res;
00380    long pause_restart_point = 0;
00381 
00382    if (stop)
00383       blen += strlen(stop);
00384    if (pause)
00385       blen += strlen(pause);
00386    if (restart)
00387       blen += strlen(restart);
00388 
00389    if (blen > 2) {
00390       breaks = alloca(blen + 1);
00391       breaks[0] = '\0';
00392       if (stop)
00393          strcat(breaks, stop);
00394       if (pause)
00395          strcat(breaks, pause);
00396       if (restart)
00397          strcat(breaks, restart);
00398    }
00399    if (chan->_state != AST_STATE_UP)
00400       res = ast_answer(chan);
00401 
00402    if (file) {
00403       if ((end = strchr(file,':'))) {
00404          if (!strcasecmp(end, ":end")) {
00405             *end = '\0';
00406             end++;
00407          }
00408       }
00409    }
00410 
00411    for (;;) {
00412       ast_stopstream(chan);
00413       res = ast_streamfile(chan, file, chan->language);
00414       if (!res) {
00415          if (pause_restart_point) {
00416             ast_seekstream(chan->stream, pause_restart_point, SEEK_SET);
00417             pause_restart_point = 0;
00418          }
00419          else if (end) {
00420             ast_seekstream(chan->stream, 0, SEEK_END);
00421             end = NULL;
00422          };
00423          res = ast_waitstream_fr(chan, breaks, fwd, rev, skipms);
00424       }
00425 
00426       if (res < 1)
00427          break;
00428 
00429       /* We go at next loop if we got the restart char */
00430       if (restart && strchr(restart, res)) {
00431          if (option_debug)
00432             ast_log(LOG_DEBUG, "we'll restart the stream here at next loop\n");
00433          pause_restart_point = 0;
00434          continue;
00435       }
00436 
00437       if (pause && strchr(pause, res)) {
00438          pause_restart_point = ast_tellstream(chan->stream);
00439          for (;;) {
00440             ast_stopstream(chan);
00441             res = ast_waitfordigit(chan, 1000);
00442             if (!res)
00443                continue;
00444             else if (res == -1 || strchr(pause, res) || (stop && strchr(stop, res)))
00445                break;
00446          }
00447          if (res == *pause) {
00448             res = 0;
00449             continue;
00450          }
00451       }
00452 
00453       if (res == -1)
00454          break;
00455 
00456       /* if we get one of our stop chars, return it to the calling function */
00457       if (stop && strchr(stop, res))
00458          break;
00459    }
00460 
00461    /* If we are returning a digit cast it as char */
00462    if (res > 0 || chan->stream)
00463       res = (char)res;
00464 
00465    ast_stopstream(chan);
00466 
00467    return res;
00468 }
00469 
00470 int ast_play_and_wait(struct ast_channel *chan, const char *fn)
00471 {
00472    int d;
00473    d = ast_streamfile(chan, fn, chan->language);
00474    if (d)
00475       return d;
00476    d = ast_waitstream(chan, AST_DIGIT_ANY);
00477    ast_stopstream(chan);
00478    return d;
00479 }
00480 
00481 static int global_silence_threshold = 128;
00482 static int global_maxsilence = 0;
00483 
00484 /*! Optionally play a sound file or a beep, then record audio and video from the channel.
00485  * @param chan Channel to playback to/record from.
00486  * @param playfile Filename of sound to play before recording begins.
00487  * @param recordfile Filename to record to.
00488  * @param maxtime Maximum length of recording (in milliseconds).
00489  * @param fmt Format(s) to record message in. Multiple formats may be specified by separating them with a '|'.
00490  * @param duration Where to store actual length of the recorded message (in milliseconds).
00491  * @param beep Whether to play a beep before starting to record.
00492  * @param silencethreshold 
00493  * @param maxsilence Length of silence that will end a recording (in milliseconds).
00494  * @param path Optional filesystem path to unlock.
00495  * @param prepend If true, prepend the recorded audio to an existing file.
00496  * @param acceptdtmf DTMF digits that will end the recording.
00497  * @param canceldtmf DTMF digits that will cancel the recording.
00498  */
00499 
00500 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)
00501 {
00502    int d = 0;
00503    char *fmts;
00504    char comment[256];
00505    int x, fmtcnt = 1, res = -1, outmsg = 0;
00506    struct ast_filestream *others[MAX_OTHER_FORMATS];
00507    char *sfmt[MAX_OTHER_FORMATS];
00508    char *stringp = NULL;
00509    time_t start, end;
00510    struct ast_dsp *sildet = NULL;   /* silence detector dsp */
00511    int totalsilence = 0;
00512    int rfmt = 0;
00513    struct ast_silence_generator *silgen = NULL;
00514    char prependfile[80];
00515 
00516    if (silencethreshold < 0)
00517       silencethreshold = global_silence_threshold;
00518 
00519    if (maxsilence < 0)
00520       maxsilence = global_maxsilence;
00521 
00522    /* barf if no pointer passed to store duration in */
00523    if (duration == NULL) {
00524       ast_log(LOG_WARNING, "Error play_and_record called without duration pointer\n");
00525       return -1;
00526    }
00527 
00528    if (option_debug)
00529       ast_log(LOG_DEBUG,"play_and_record: %s, %s, '%s'\n", playfile ? playfile : "<None>", recordfile, fmt);
00530    snprintf(comment, sizeof(comment), "Playing %s, Recording to: %s on %s\n", playfile ? playfile : "<None>", recordfile, chan->name);
00531 
00532    if (playfile || beep) {
00533       if (!beep)
00534          d = ast_play_and_wait(chan, playfile);
00535       if (d > -1)
00536          d = ast_stream_and_wait(chan, "beep", chan->language, "");
00537       if (d < 0)
00538          return -1;
00539    }
00540 
00541    if (prepend) {
00542       ast_copy_string(prependfile, recordfile, sizeof(prependfile)); 
00543       strncat(prependfile, "-prepend", sizeof(prependfile) - strlen(prependfile) - 1);
00544    }
00545 
00546    fmts = ast_strdupa(fmt);
00547 
00548    stringp = fmts;
00549    strsep(&stringp, "|");
00550    if (option_debug)
00551       ast_log(LOG_DEBUG, "Recording Formats: sfmts=%s\n", fmts);
00552    sfmt[0] = ast_strdupa(fmts);
00553 
00554    while ((fmt = strsep(&stringp, "|"))) {
00555       if (fmtcnt > MAX_OTHER_FORMATS - 1) {
00556          ast_log(LOG_WARNING, "Please increase MAX_OTHER_FORMATS in app.c\n");
00557          break;
00558       }
00559       sfmt[fmtcnt++] = ast_strdupa(fmt);
00560    }
00561 
00562    end = start = time(NULL);  /* pre-initialize end to be same as start in case we never get into loop */
00563    for (x = 0; x < fmtcnt; x++) {
00564       others[x] = ast_writefile(prepend ? prependfile : recordfile, sfmt[x], comment, O_TRUNC, 0, 0777);
00565       if (option_verbose > 2)
00566          ast_verbose(VERBOSE_PREFIX_3 "x=%d, open writing:  %s format: %s, %p\n", x, prepend ? prependfile : recordfile, sfmt[x], others[x]);
00567 
00568       if (!others[x])
00569          break;
00570    }
00571 
00572    if (path)
00573       ast_unlock_path(path);
00574 
00575    if (maxsilence > 0) {
00576       sildet = ast_dsp_new(); /* Create the silence detector */
00577       if (!sildet) {
00578          ast_log(LOG_WARNING, "Unable to create silence detector :(\n");
00579          return -1;
00580       }
00581       ast_dsp_set_threshold(sildet, silencethreshold);
00582       rfmt = chan->readformat;
00583       res = ast_set_read_format(chan, AST_FORMAT_SLINEAR);
00584       if (res < 0) {
00585          ast_log(LOG_WARNING, "Unable to set to linear mode, giving up\n");
00586          ast_dsp_free(sildet);
00587          return -1;
00588       }
00589    }
00590 
00591    if (!prepend) {
00592       /* Request a video update */
00593       ast_indicate(chan, AST_CONTROL_VIDUPDATE);
00594 
00595       if (ast_opt_transmit_silence)
00596          silgen = ast_channel_start_silence_generator(chan);
00597    }
00598 
00599    if (x == fmtcnt) {
00600       /* Loop forever, writing the packets we read to the writer(s), until
00601          we read a digit or get a hangup */
00602       struct ast_frame *f;
00603       for (;;) {
00604          res = ast_waitfor(chan, 2000);
00605          if (!res) {
00606             if (option_debug)
00607                ast_log(LOG_DEBUG, "One waitfor failed, trying another\n");
00608             /* Try one more time in case of masq */
00609             res = ast_waitfor(chan, 2000);
00610             if (!res) {
00611                ast_log(LOG_WARNING, "No audio available on %s??\n", chan->name);
00612                res = -1;
00613             }
00614          }
00615 
00616          if (res < 0) {
00617             f = NULL;
00618             break;
00619          }
00620          f = ast_read(chan);
00621          if (!f)
00622             break;
00623          if (f->frametype == AST_FRAME_VOICE) {
00624             /* write each format */
00625             for (x = 0; x < fmtcnt; x++) {
00626                if (prepend && !others[x])
00627                   break;
00628                res = ast_writestream(others[x], f);
00629             }
00630 
00631             /* Silence Detection */
00632             if (maxsilence > 0) {
00633                int dspsilence = 0;
00634                ast_dsp_silence(sildet, f, &dspsilence);
00635                if (dspsilence)
00636                   totalsilence = dspsilence;
00637                else
00638                   totalsilence = 0;
00639 
00640                if (totalsilence > maxsilence) {
00641                   /* Ended happily with silence */
00642                   if (option_verbose > 2)
00643                      ast_verbose( VERBOSE_PREFIX_3 "Recording automatically stopped after a silence of %d seconds\n", totalsilence/1000);
00644                   res = 'S';
00645                   outmsg = 2;
00646                   break;
00647                }
00648             }
00649             /* Exit on any error */
00650             if (res) {
00651                ast_log(LOG_WARNING, "Error writing frame\n");
00652                break;
00653             }
00654          } else if (f->frametype == AST_FRAME_VIDEO) {
00655             /* Write only once */
00656             ast_writestream(others[0], f);
00657          } else if (f->frametype == AST_FRAME_DTMF) {
00658             if (prepend) {
00659             /* stop recording with any digit */
00660                if (option_verbose > 2) 
00661                   ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
00662                res = 't';
00663                outmsg = 2;
00664                break;
00665             }
00666             if (strchr(acceptdtmf, f->subclass)) {
00667                if (option_verbose > 2)
00668                   ast_verbose(VERBOSE_PREFIX_3 "User ended message by pressing %c\n", f->subclass);
00669                res = f->subclass;
00670                outmsg = 2;
00671                break;
00672             }
00673             if (strchr(canceldtmf, f->subclass)) {
00674                if (option_verbose > 2)
00675                   ast_verbose(VERBOSE_PREFIX_3 "User cancelled message by pressing %c\n", f->subclass);
00676                res = f->subclass;
00677                outmsg = 0;
00678                break;
00679             }
00680          }
00681          if (maxtime) {
00682             end = time(NULL);
00683             if (maxtime < (end - start)) {
00684                if (option_verbose > 2)
00685                   ast_verbose(VERBOSE_PREFIX_3 "Took too long, cutting it short...\n");
00686                res = 't';
00687                outmsg = 2;
00688                break;
00689             }
00690          }
00691          ast_frfree(f);
00692       }
00693       if (!f) {
00694          if (option_verbose > 2)
00695             ast_verbose(VERBOSE_PREFIX_3 "User hung up\n");
00696          res = -1;
00697          outmsg = 1;
00698       } else {
00699          ast_frfree(f);
00700       }
00701    } else {
00702       ast_log(LOG_WARNING, "Error creating writestream '%s', format '%s'\n", recordfile, sfmt[x]);
00703    }
00704 
00705    if (!prepend) {
00706       if (silgen)
00707          ast_channel_stop_silence_generator(chan, silgen);
00708    }
00709 
00710    /*!\note
00711     * Instead of asking how much time passed (end - start), calculate the number
00712     * of seconds of audio which actually went into the file.  This fixes a
00713     * problem where audio is stopped up on the network and never gets to us.
00714     *
00715     * Note that we still want to use the number of seconds passed for the max
00716     * message, otherwise we could get a situation where this stream is never
00717     * closed (which would create a resource leak).
00718     */
00719    *duration = others[0] ? ast_tellstream(others[0]) / 8000 : 0;
00720 
00721    if (!prepend) {
00722       for (x = 0; x < fmtcnt; x++) {
00723          if (!others[x])
00724             break;
00725          /*!\note
00726           * If we ended with silence, trim all but the first 200ms of silence
00727           * off the recording.  However, if we ended with '#', we don't want
00728           * to trim ANY part of the recording.
00729           */
00730          if (res > 0 && totalsilence)
00731             ast_stream_rewind(others[x], totalsilence - 200);
00732          ast_truncstream(others[x]);
00733          ast_closestream(others[x]);
00734       }
00735    }
00736 
00737    if (prepend && outmsg) {
00738       struct ast_filestream *realfiles[MAX_OTHER_FORMATS];
00739       struct ast_frame *fr;
00740 
00741       for (x = 0; x < fmtcnt; x++) {
00742          snprintf(comment, sizeof(comment), "Opening the real file %s.%s\n", recordfile, sfmt[x]);
00743          realfiles[x] = ast_readfile(recordfile, sfmt[x], comment, O_RDONLY, 0, 0);
00744          if (!others[x] || !realfiles[x])
00745             break;
00746          /*!\note Same logic as above. */
00747          if (totalsilence)
00748             ast_stream_rewind(others[x], totalsilence - 200);
00749          ast_truncstream(others[x]);
00750          /* add the original file too */
00751          while ((fr = ast_readframe(realfiles[x]))) {
00752             ast_writestream(others[x], fr);
00753             ast_frfree(fr);
00754          }
00755          ast_closestream(others[x]);
00756          ast_closestream(realfiles[x]);
00757          ast_filerename(prependfile, recordfile, sfmt[x]);
00758          if (option_verbose > 3)
00759             ast_verbose(VERBOSE_PREFIX_4 "Recording Format: sfmts=%s, prependfile %s, recordfile %s\n", sfmt[x], prependfile, recordfile);
00760          ast_filedelete(prependfile, sfmt[x]);
00761       }
00762    }
00763    if (rfmt && ast_set_read_format(chan, rfmt)) {
00764       ast_log(LOG_WARNING, "Unable to restore format %s to channel '%s'\n", ast_getformatname(rfmt), chan->name);
00765    }
00766    if (outmsg == 2) {
00767       ast_stream_and_wait(chan, "auth-thankyou", chan->language, "");
00768    }
00769    if (sildet)
00770       ast_dsp_free(sildet);
00771    return res;
00772 }
00773 
00774 static char default_acceptdtmf[] = "#";
00775 static char default_canceldtmf[] = "";
00776 
00777 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)
00778 {
00779    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));
00780 }
00781 
00782 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)
00783 {
00784    return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, 0, silencethreshold, maxsilence, path, 0, default_acceptdtmf, default_canceldtmf);
00785 }
00786 
00787 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)
00788 {
00789    return __ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, beep, silencethreshold, maxsilence, NULL, 1, default_acceptdtmf, default_canceldtmf);
00790 }
00791 
00792 /* Channel group core functions */
00793 
00794 int ast_app_group_split_group(const char *data, char *group, int group_max, char *category, int category_max)
00795 {
00796    int res=0;
00797    char tmp[256];
00798    char *grp=NULL, *cat=NULL;
00799 
00800    if (!ast_strlen_zero(data)) {
00801       ast_copy_string(tmp, data, sizeof(tmp));
00802       grp = tmp;
00803       cat = strchr(tmp, '@');
00804       if (cat) {
00805          *cat = '\0';
00806          cat++;
00807       }
00808    }
00809 
00810    if (!ast_strlen_zero(grp))
00811       ast_copy_string(group, grp, group_max);
00812    else
00813       *group = '\0';
00814 
00815    if (!ast_strlen_zero(cat))
00816       ast_copy_string(category, cat, category_max);
00817 
00818    return res;
00819 }
00820 
00821 int ast_app_group_set_channel(struct ast_channel *chan, const char *data)
00822 {
00823    int res = 0;
00824    char group[80] = "", category[80] = "";
00825    struct ast_group_info *gi = NULL;
00826    size_t len = 0;
00827    
00828    if (ast_app_group_split_group(data, group, sizeof(group), category, sizeof(category)))
00829       return -1;
00830    
00831    /* Calculate memory we will need if this is new */
00832    len = sizeof(*gi) + strlen(group) + 1;
00833    if (!ast_strlen_zero(category))
00834       len += strlen(category) + 1;
00835    
00836    AST_LIST_LOCK(&groups);
00837    AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
00838       if ((gi->chan == chan) && ((ast_strlen_zero(category) && ast_strlen_zero(gi->category)) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category)))) {
00839          AST_LIST_REMOVE_CURRENT(&groups, list);
00840          free(gi);
00841          break;
00842       }
00843    }
00844    AST_LIST_TRAVERSE_SAFE_END
00845 
00846    if (ast_strlen_zero(group)) {
00847       /* Enable unsetting the group */
00848    } else if ((gi = calloc(1, len))) {
00849       gi->chan = chan;
00850       gi->group = (char *) gi + sizeof(*gi);
00851       strcpy(gi->group, group);
00852       if (!ast_strlen_zero(category)) {
00853          gi->category = (char *) gi + sizeof(*gi) + strlen(group) + 1;
00854          strcpy(gi->category, category);
00855       }
00856       AST_LIST_INSERT_TAIL(&groups, gi, list);
00857    } else {
00858       res = -1;
00859    }
00860    
00861    AST_LIST_UNLOCK(&groups);
00862    
00863    return res;
00864 }
00865 
00866 int ast_app_group_get_count(const char *group, const char *category)
00867 {
00868    struct ast_group_info *gi = NULL;
00869    int count = 0;
00870 
00871    if (ast_strlen_zero(group))
00872       return 0;
00873    
00874    AST_LIST_LOCK(&groups);
00875    AST_LIST_TRAVERSE(&groups, gi, list) {
00876       if (!strcasecmp(gi->group, group) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
00877          count++;
00878    }
00879    AST_LIST_UNLOCK(&groups);
00880 
00881    return count;
00882 }
00883 
00884 int ast_app_group_match_get_count(const char *groupmatch, const char *category)
00885 {
00886    struct ast_group_info *gi = NULL;
00887    regex_t regexbuf;
00888    int count = 0;
00889 
00890    if (ast_strlen_zero(groupmatch))
00891       return 0;
00892 
00893    /* if regex compilation fails, return zero matches */
00894    if (regcomp(&regexbuf, groupmatch, REG_EXTENDED | REG_NOSUB))
00895       return 0;
00896 
00897    AST_LIST_LOCK(&groups);
00898    AST_LIST_TRAVERSE(&groups, gi, list) {
00899       if (!regexec(&regexbuf, gi->group, 0, NULL, 0) && (ast_strlen_zero(category) || (!ast_strlen_zero(gi->category) && !strcasecmp(gi->category, category))))
00900          count++;
00901    }
00902    AST_LIST_UNLOCK(&groups);
00903 
00904    regfree(&regexbuf);
00905 
00906    return count;
00907 }
00908 
00909 int ast_app_group_update(struct ast_channel *old, struct ast_channel *new)
00910 {
00911    struct ast_group_info *gi = NULL;
00912 
00913    AST_LIST_LOCK(&groups);
00914    AST_LIST_TRAVERSE(&groups, gi, list) {
00915       if (gi->chan == old)
00916          gi->chan = new;
00917    }
00918    AST_LIST_UNLOCK(&groups);
00919 
00920    return 0;
00921 }
00922 
00923 int ast_app_group_discard(struct ast_channel *chan)
00924 {
00925    struct ast_group_info *gi = NULL;
00926    
00927    AST_LIST_LOCK(&groups);
00928    AST_LIST_TRAVERSE_SAFE_BEGIN(&groups, gi, list) {
00929       if (gi->chan == chan) {
00930          AST_LIST_REMOVE_CURRENT(&groups, list);
00931          free(gi);
00932       }
00933    }
00934         AST_LIST_TRAVERSE_SAFE_END
00935    AST_LIST_UNLOCK(&groups);
00936    
00937    return 0;
00938 }
00939 
00940 int ast_app_group_list_lock(void)
00941 {
00942    return AST_LIST_LOCK(&groups);
00943 }
00944 
00945 struct ast_group_info *ast_app_group_list_head(void)
00946 {
00947    return AST_LIST_FIRST(&groups);
00948 }
00949 
00950 int ast_app_group_list_unlock(void)
00951 {
00952    return AST_LIST_UNLOCK(&groups);
00953 }
00954 
00955 unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
00956 {
00957    int argc;
00958    char *scan;
00959    int paren = 0, quote = 0;
00960 
00961    if (!buf || !array || !arraylen)
00962       return 0;
00963 
00964    memset(array, 0, arraylen * sizeof(*array));
00965 
00966    scan = buf;
00967 
00968    for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
00969       array[argc] = scan;
00970       for (; *scan; scan++) {
00971          if (*scan == '(')
00972             paren++;
00973          else if (*scan == ')') {
00974             if (paren)
00975                paren--;
00976          } else if (*scan == '"' && delim != '"') {
00977             quote = quote ? 0 : 1;
00978             /* Remove quote character from argument */
00979             memmove(scan, scan + 1, strlen(scan));
00980             scan--;
00981          } else if (*scan == '\\') {
00982             /* Literal character, don't parse */
00983             memmove(scan, scan + 1, strlen(scan));
00984          } else if ((*scan == delim) && !paren && !quote) {
00985             *scan++ = '\0';
00986             break;
00987          }
00988       }
00989    }
00990 
00991    if (*scan)
00992       array[argc++] = scan;
00993 
00994    return argc;
00995 }
00996 
00997 enum AST_LOCK_RESULT ast_lock_path(const char *path)
00998 {
00999    char *s;
01000    char *fs;
01001    int res;
01002    int fd;
01003    int lp = strlen(path);
01004    time_t start;
01005 
01006    if (!(s = alloca(lp + 10)) || !(fs = alloca(lp + 20))) {
01007       ast_log(LOG_WARNING, "Out of memory!\n");
01008       return AST_LOCK_FAILURE;
01009    }
01010 
01011    snprintf(fs, strlen(path) + 19, "%s/.lock-%08lx", path, ast_random());
01012    fd = open(fs, O_WRONLY | O_CREAT | O_EXCL, 0600);
01013    if (fd < 0) {
01014       ast_log(LOG_ERROR, "Unable to create lock file '%s': %s\n", path, strerror(errno));
01015       return AST_LOCK_PATH_NOT_FOUND;
01016    }
01017    close(fd);
01018 
01019    snprintf(s, strlen(path) + 9, "%s/.lock", path);
01020    start = time(NULL);
01021    while (((res = link(fs, s)) < 0) && (errno == EEXIST) && (time(NULL) - start < 5))
01022       usleep(1);
01023 
01024    unlink(fs);
01025 
01026    if (res) {
01027       ast_log(LOG_WARNING, "Failed to lock path '%s': %s\n", path, strerror(errno));
01028       return AST_LOCK_TIMEOUT;
01029    } else {
01030       if (option_debug)
01031          ast_log(LOG_DEBUG, "Locked path '%s'\n", path);
01032       return AST_LOCK_SUCCESS;
01033    }
01034 }
01035 
01036 int ast_unlock_path(const char *path)
01037 {
01038    char *s;
01039    int res;
01040 
01041    if (!(s = alloca(strlen(path) + 10))) {
01042       ast_log(LOG_WARNING, "Out of memory!\n");
01043       return -1;
01044    }
01045 
01046    snprintf(s, strlen(path) + 9, "%s/%s", path, ".lock");
01047 
01048    if ((res = unlink(s)))
01049       ast_log(LOG_ERROR, "Could not unlock path '%s': %s\n", path, strerror(errno));
01050    else {
01051       if (option_debug)
01052          ast_log(LOG_DEBUG, "Unlocked path '%s'\n", path);
01053    }
01054 
01055    return res;
01056 }
01057 
01058 int ast_record_review(struct ast_channel *chan, const char *playfile, const char *recordfile, int maxtime, const char *fmt, int *duration, const char *path) 
01059 {
01060    int silencethreshold = 128; 
01061    int maxsilence=0;
01062    int res = 0;
01063    int cmd = 0;
01064    int max_attempts = 3;
01065    int attempts = 0;
01066    int recorded = 0;
01067    int message_exists = 0;
01068    /* Note that urgent and private are for flagging messages as such in the future */
01069 
01070    /* barf if no pointer passed to store duration in */
01071    if (duration == NULL) {
01072       ast_log(LOG_WARNING, "Error ast_record_review called without duration pointer\n");
01073       return -1;
01074    }
01075 
01076    cmd = '3';   /* Want to start by recording */
01077 
01078    while ((cmd >= 0) && (cmd != 't')) {
01079       switch (cmd) {
01080       case '1':
01081          if (!message_exists) {
01082             /* In this case, 1 is to record a message */
01083             cmd = '3';
01084             break;
01085          } else {
01086             ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
01087             cmd = 't';
01088             return res;
01089          }
01090       case '2':
01091          /* Review */
01092          ast_verbose(VERBOSE_PREFIX_3 "Reviewing the recording\n");
01093          cmd = ast_stream_and_wait(chan, recordfile, chan->language, AST_DIGIT_ANY);
01094          break;
01095       case '3':
01096          message_exists = 0;
01097          /* Record */
01098          if (recorded == 1)
01099             ast_verbose(VERBOSE_PREFIX_3 "Re-recording\n");
01100          else  
01101             ast_verbose(VERBOSE_PREFIX_3 "Recording\n");
01102          recorded = 1;
01103          cmd = ast_play_and_record(chan, playfile, recordfile, maxtime, fmt, duration, silencethreshold, maxsilence, path);
01104          if (cmd == -1) {
01105          /* User has hung up, no options to give */
01106             return cmd;
01107          }
01108          if (cmd == '0') {
01109             break;
01110          } else if (cmd == '*') {
01111             break;
01112          } 
01113          else {
01114             /* If all is well, a message exists */
01115             message_exists = 1;
01116             cmd = 0;
01117          }
01118          break;
01119       case '4':
01120       case '5':
01121       case '6':
01122       case '7':
01123       case '8':
01124       case '9':
01125       case '*':
01126       case '#':
01127          cmd = ast_play_and_wait(chan, "vm-sorry");
01128          break;
01129       default:
01130          if (message_exists) {
01131             cmd = ast_play_and_wait(chan, "vm-review");
01132          }
01133          else {
01134             cmd = ast_play_and_wait(chan, "vm-torerecord");
01135             if (!cmd)
01136                cmd = ast_waitfordigit(chan, 600);
01137          }
01138          
01139          if (!cmd)
01140             cmd = ast_waitfordigit(chan, 6000);
01141          if (!cmd) {
01142             attempts++;
01143          }
01144          if (attempts > max_attempts) {
01145             cmd = 't';
01146          }
01147       }
01148    }
01149    if (cmd == 't')
01150       cmd = 0;
01151    return cmd;
01152 }
01153 
01154 #define RES_UPONE (1 << 16)
01155 #define RES_EXIT  (1 << 17)
01156 #define RES_REPEAT (1 << 18)
01157 #define RES_RESTART ((1 << 19) | RES_REPEAT)
01158 
01159 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata);
01160 
01161 static int ivr_dispatch(struct ast_channel *chan, struct ast_ivr_option *option, char *exten, void *cbdata)
01162 {
01163    int res;
01164    int (*ivr_func)(struct ast_channel *, void *);
01165    char *c;
01166    char *n;
01167    
01168    switch(option->action) {
01169    case AST_ACTION_UPONE:
01170       return RES_UPONE;
01171    case AST_ACTION_EXIT:
01172       return RES_EXIT | (((unsigned long)(option->adata)) & 0xffff);
01173    case AST_ACTION_REPEAT:
01174       return RES_REPEAT | (((unsigned long)(option->adata)) & 0xffff);
01175    case AST_ACTION_RESTART:
01176       return RES_RESTART ;
01177    case AST_ACTION_NOOP:
01178       return 0;
01179    case AST_ACTION_BACKGROUND:
01180       res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, AST_DIGIT_ANY);
01181       if (res < 0) {
01182          ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
01183          res = 0;
01184       }
01185       return res;
01186    case AST_ACTION_PLAYBACK:
01187       res = ast_stream_and_wait(chan, (char *)option->adata, chan->language, "");
01188       if (res < 0) {
01189          ast_log(LOG_NOTICE, "Unable to find file '%s'!\n", (char *)option->adata);
01190          res = 0;
01191       }
01192       return res;
01193    case AST_ACTION_MENU:
01194       res = ast_ivr_menu_run_internal(chan, (struct ast_ivr_menu *)option->adata, cbdata);
01195       /* Do not pass entry errors back up, treaat ast though ti was an "UPONE" */
01196       if (res == -2)
01197          res = 0;
01198       return res;
01199    case AST_ACTION_WAITOPTION:
01200       res = ast_waitfordigit(chan, 1000 * (chan->pbx ? chan->pbx->rtimeout : 10));
01201       if (!res)
01202          return 't';
01203       return res;
01204    case AST_ACTION_CALLBACK:
01205       ivr_func = option->adata;
01206       res = ivr_func(chan, cbdata);
01207       return res;
01208    case AST_ACTION_TRANSFER:
01209       res = ast_parseable_goto(chan, option->adata);
01210       return 0;
01211    case AST_ACTION_PLAYLIST:
01212    case AST_ACTION_BACKLIST:
01213       res = 0;
01214       c = ast_strdupa(option->adata);
01215       while ((n = strsep(&c, ";"))) {
01216          if ((res = ast_stream_and_wait(chan, n, chan->language,
01217                (option->action == AST_ACTION_BACKLIST) ? AST_DIGIT_ANY : "")))
01218             break;
01219       }
01220       ast_stopstream(chan);
01221       return res;
01222    default:
01223       ast_log(LOG_NOTICE, "Unknown dispatch function %d, ignoring!\n", option->action);
01224       return 0;
01225    };
01226    return -1;
01227 }
01228 
01229 static int option_exists(struct ast_ivr_menu *menu, char *option)
01230 {
01231    int x;
01232    for (x = 0; menu->options[x].option; x++)
01233       if (!strcasecmp(menu->options[x].option, option))
01234          return x;
01235    return -1;
01236 }
01237 
01238 static int option_matchmore(struct ast_ivr_menu *menu, char *option)
01239 {
01240    int x;
01241    for (x = 0; menu->options[x].option; x++)
01242       if ((!strncasecmp(menu->options[x].option, option, strlen(option))) && 
01243             (menu->options[x].option[strlen(option)]))
01244          return x;
01245    return -1;
01246 }
01247 
01248 static int read_newoption(struct ast_channel *chan, struct ast_ivr_menu *menu, char *exten, int maxexten)
01249 {
01250    int res=0;
01251    int ms;
01252    while (option_matchmore(menu, exten)) {
01253       ms = chan->pbx ? chan->pbx->dtimeout : 5000;
01254       if (strlen(exten) >= maxexten - 1) 
01255          break;
01256       res = ast_waitfordigit(chan, ms);
01257       if (res < 1)
01258          break;
01259       exten[strlen(exten) + 1] = '\0';
01260       exten[strlen(exten)] = res;
01261    }
01262    return res > 0 ? 0 : res;
01263 }
01264 
01265 static int ast_ivr_menu_run_internal(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
01266 {
01267    /* Execute an IVR menu structure */
01268    int res=0;
01269    int pos = 0;
01270    int retries = 0;
01271    char exten[AST_MAX_EXTENSION] = "s";
01272    if (option_exists(menu, "s") < 0) {
01273       strcpy(exten, "g");
01274       if (option_exists(menu, "g") < 0) {
01275          ast_log(LOG_WARNING, "No 's' nor 'g' extension in menu '%s'!\n", menu->title);
01276          return -1;
01277       }
01278    }
01279    while(!res) {
01280       while(menu->options[pos].option) {
01281          if (!strcasecmp(menu->options[pos].option, exten)) {
01282             res = ivr_dispatch(chan, menu->options + pos, exten, cbdata);
01283             if (option_debug)
01284                ast_log(LOG_DEBUG, "IVR Dispatch of '%s' (pos %d) yields %d\n", exten, pos, res);
01285             if (res < 0)
01286                break;
01287             else if (res & RES_UPONE)
01288                return 0;
01289             else if (res & RES_EXIT)
01290                return res;
01291             else if (res & RES_REPEAT) {
01292                int maxretries = res & 0xffff;
01293                if ((res & RES_RESTART) == RES_RESTART) {
01294                   retries = 0;
01295                } else
01296                   retries++;
01297                if (!maxretries)
01298                   maxretries = 3;
01299                if ((maxretries > 0) && (retries >= maxretries)) {
01300                   if (option_debug)
01301                      ast_log(LOG_DEBUG, "Max retries %d exceeded\n", maxretries);
01302                   return -2;
01303                } else {
01304                   if (option_exists(menu, "g") > -1) 
01305                      strcpy(exten, "g");
01306                   else if (option_exists(menu, "s") > -1)
01307                      strcpy(exten, "s");
01308                }
01309                pos = 0;
01310                continue;
01311             } else if (res && strchr(AST_DIGIT_ANY, res)) {
01312                if (option_debug)
01313                   ast_log(LOG_DEBUG, "Got start of extension, %c\n", res);
01314                exten[1] = '\0';
01315                exten[0] = res;
01316                if ((res = read_newoption(chan, menu, exten, sizeof(exten))))
01317                   break;
01318                if (option_exists(menu, exten) < 0) {
01319                   if (option_exists(menu, "i")) {
01320                      if (option_debug)
01321                         ast_log(LOG_DEBUG, "Invalid extension entered, going to 'i'!\n");
01322                      strcpy(exten, "i");
01323                      pos = 0;
01324                      continue;
01325                   } else {
01326                      if (option_debug)
01327                         ast_log(LOG_DEBUG, "Aborting on invalid entry, with no 'i' option!\n");
01328                      res = -2;
01329                      break;
01330                   }
01331                } else {
01332                   if (option_debug)
01333                      ast_log(LOG_DEBUG, "New existing extension: %s\n", exten);
01334                   pos = 0;
01335                   continue;
01336                }
01337             }
01338          }
01339          pos++;
01340       }
01341       if (option_debug)
01342          ast_log(LOG_DEBUG, "Stopping option '%s', res is %d\n", exten, res);
01343       pos = 0;
01344       if (!strcasecmp(exten, "s"))
01345          strcpy(exten, "g");
01346       else
01347          break;
01348    }
01349    return res;
01350 }
01351 
01352 int ast_ivr_menu_run(struct ast_channel *chan, struct ast_ivr_menu *menu, void *cbdata)
01353 {
01354    int res = ast_ivr_menu_run_internal(chan, menu, cbdata);
01355    /* Hide internal coding */
01356    return res > 0 ? 0 : res;
01357 }
01358    
01359 char *ast_read_textfile(const char *filename)
01360 {
01361    int fd;
01362    char *output = NULL;
01363    struct stat filesize;
01364    int count = 0;
01365    int res;
01366    if (stat(filename, &filesize) == -1) {
01367       ast_log(LOG_WARNING, "Error can't stat %s\n", filename);
01368       return NULL;
01369    }
01370    count = filesize.st_size + 1;
01371    fd = open(filename, O_RDONLY);
01372    if (fd < 0) {
01373       ast_log(LOG_WARNING, "Cannot open file '%s' for reading: %s\n", filename, strerror(errno));
01374       return NULL;
01375    }
01376    if ((output = ast_malloc(count))) {
01377       res = read(fd, output, count - 1);
01378       if (res == count - 1) {
01379          output[res] = '\0';
01380       } else {
01381          ast_log(LOG_WARNING, "Short read of %s (%d of %d): %s\n", filename, res, count - 1, strerror(errno));
01382          free(output);
01383          output = NULL;
01384       }
01385    }
01386    close(fd);
01387    return output;
01388 }
01389 
01390 int ast_app_parse_options(const struct ast_app_option *options, struct ast_flags *flags, char **args, char *optstr)
01391 {
01392    char *s;
01393    int curarg;
01394    unsigned int argloc;
01395    char *arg;
01396    int res = 0;
01397 
01398    ast_clear_flag(flags, AST_FLAGS_ALL);
01399 
01400    if (!optstr)
01401       return 0;
01402 
01403    s = optstr;
01404    while (*s) {
01405       curarg = *s++ & 0x7f;   /* the array (in app.h) has 128 entries */
01406       argloc = options[curarg].arg_index;
01407       if (*s == '(') {
01408          /* Has argument */
01409          arg = ++s;
01410          if ((s = strchr(s, ')'))) {
01411             if (argloc)
01412                args[argloc - 1] = arg;
01413             *s++ = '\0';
01414          } else {
01415             ast_log(LOG_WARNING, "Missing closing parenthesis for argument '%c' in string '%s'\n", curarg, arg);
01416             res = -1;
01417             break;
01418          }
01419       } else if (argloc) {
01420          args[argloc - 1] = "";
01421       }
01422       ast_set_flag(flags, options[curarg].flag);
01423    }
01424 
01425    return res;
01426 }
01427 

Generated on Tue Sep 30 01:19:28 2008 for Asterisk - the Open Source PBX by  doxygen 1.5.6