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

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