Mon Nov 24 15:34:20 2008

Asterisk developer's documentation


pbx_spool.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 Full-featured outgoing call spool support
00022  * 
00023  */
00024 
00025 #include "asterisk.h"
00026 
00027 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 134976 $")
00028 
00029 #include <sys/stat.h>
00030 #include <errno.h>
00031 #include <time.h>
00032 #include <utime.h>
00033 #include <stdlib.h>
00034 #include <unistd.h>
00035 #include <dirent.h>
00036 #include <string.h>
00037 #include <string.h>
00038 #include <stdio.h>
00039 #include <unistd.h>
00040 
00041 #include "asterisk/lock.h"
00042 #include "asterisk/file.h"
00043 #include "asterisk/logger.h"
00044 #include "asterisk/channel.h"
00045 #include "asterisk/callerid.h"
00046 #include "asterisk/pbx.h"
00047 #include "asterisk/module.h"
00048 #include "asterisk/options.h"
00049 #include "asterisk/utils.h"
00050 
00051 /*
00052  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
00053  * The spool file contains a header 
00054  */
00055 
00056 enum {
00057    /*! Always delete the call file after a call succeeds or the
00058     * maximum number of retries is exceeded, even if the
00059     * modification time of the call file is in the future.
00060     */
00061    SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
00062    /* Don't unlink the call file after processing, move in qdonedir */
00063    SPOOL_FLAG_ARCHIVE = (1 << 1)
00064 };
00065 
00066 static char qdir[255];
00067 static char qdonedir[255];
00068 
00069 struct outgoing {
00070    char fn[256];
00071    /* Current number of retries */
00072    int retries;
00073    /* Maximum number of retries permitted */
00074    int maxretries;
00075    /* How long to wait between retries (in seconds) */
00076    int retrytime;
00077    /* How long to wait for an answer */
00078    int waittime;
00079    /* PID which is currently calling */
00080    long callingpid;
00081    /* Formats (codecs) for this call */
00082    int format;
00083    
00084    /* What to connect to outgoing */
00085    char tech[256];
00086    char dest[256];
00087    
00088    /* If application */
00089    char app[256];
00090    char data[256];
00091 
00092    /* If extension/context/priority */
00093    char exten[256];
00094    char context[256];
00095    int priority;
00096 
00097    /* CallerID Information */
00098    char cid_num[256];
00099    char cid_name[256];
00100 
00101    /* account code */
00102    char account[AST_MAX_ACCOUNT_CODE];
00103 
00104    /* Variables and Functions */
00105    struct ast_variable *vars;
00106    
00107    /* Maximum length of call */
00108    int maxlen;
00109 
00110    /* options */
00111    struct ast_flags options;
00112 };
00113 
00114 static void init_outgoing(struct outgoing *o)
00115 {
00116    memset(o, 0, sizeof(struct outgoing));
00117    o->priority = 1;
00118    o->retrytime = 300;
00119    o->waittime = 45;
00120    o->format = AST_FORMAT_SLINEAR;
00121    ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
00122 }
00123 
00124 static void free_outgoing(struct outgoing *o)
00125 {
00126    free(o);
00127 }
00128 
00129 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
00130 {
00131    char buf[256];
00132    char *c, *c2;
00133    int lineno = 0;
00134    struct ast_variable *var, *last = o->vars;
00135 
00136    while (last && last->next) {
00137       last = last->next;
00138    }
00139 
00140    while(fgets(buf, sizeof(buf), f)) {
00141       lineno++;
00142       /* Trim comments */
00143       c = buf;
00144       while ((c = strchr(c, '#'))) {
00145          if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
00146             *c = '\0';
00147          else
00148             c++;
00149       }
00150 
00151       c = buf;
00152       while ((c = strchr(c, ';'))) {
00153          if ((c > buf) && (c[-1] == '\\')) {
00154             memmove(c - 1, c, strlen(c) + 1);
00155             c++;
00156          } else {
00157             *c = '\0';
00158             break;
00159          }
00160       }
00161 
00162       /* Trim trailing white space */
00163       while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
00164          buf[strlen(buf) - 1] = '\0';
00165       if (!ast_strlen_zero(buf)) {
00166          c = strchr(buf, ':');
00167          if (c) {
00168             *c = '\0';
00169             c++;
00170             while ((*c) && (*c < 33))
00171                c++;
00172 #if 0
00173             printf("'%s' is '%s' at line %d\n", buf, c, lineno);
00174 #endif
00175             if (!strcasecmp(buf, "channel")) {
00176                ast_copy_string(o->tech, c, sizeof(o->tech));
00177                if ((c2 = strchr(o->tech, '/'))) {
00178                   *c2 = '\0';
00179                   c2++;
00180                   ast_copy_string(o->dest, c2, sizeof(o->dest));
00181                } else {
00182                   ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
00183                   o->tech[0] = '\0';
00184                }
00185             } else if (!strcasecmp(buf, "callerid")) {
00186                ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
00187             } else if (!strcasecmp(buf, "application")) {
00188                ast_copy_string(o->app, c, sizeof(o->app));
00189             } else if (!strcasecmp(buf, "data")) {
00190                ast_copy_string(o->data, c, sizeof(o->data));
00191             } else if (!strcasecmp(buf, "maxretries")) {
00192                if (sscanf(c, "%d", &o->maxretries) != 1) {
00193                   ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
00194                   o->maxretries = 0;
00195                }
00196             } else if (!strcasecmp(buf, "codecs")) {
00197                ast_parse_allow_disallow(NULL, &o->format, c, 1);
00198             } else if (!strcasecmp(buf, "context")) {
00199                ast_copy_string(o->context, c, sizeof(o->context));
00200             } else if (!strcasecmp(buf, "extension")) {
00201                ast_copy_string(o->exten, c, sizeof(o->exten));
00202             } else if (!strcasecmp(buf, "priority")) {
00203                if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
00204                   ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
00205                   o->priority = 1;
00206                }
00207             } else if (!strcasecmp(buf, "retrytime")) {
00208                if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
00209                   ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
00210                   o->retrytime = 300;
00211                }
00212             } else if (!strcasecmp(buf, "waittime")) {
00213                if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
00214                   ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
00215                   o->waittime = 45;
00216                }
00217             } else if (!strcasecmp(buf, "retry")) {
00218                o->retries++;
00219             } else if (!strcasecmp(buf, "startretry")) {
00220                if (sscanf(c, "%ld", &o->callingpid) != 1) {
00221                   ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
00222                   o->callingpid = 0;
00223                }
00224             } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
00225                o->callingpid = 0;
00226                o->retries++;
00227             } else if (!strcasecmp(buf, "delayedretry")) {
00228             } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
00229                c2 = c;
00230                strsep(&c2, "=");
00231                if (c2) {
00232                   var = ast_variable_new(c, c2);
00233                   if (var) {
00234                      /* Always insert at the end, because some people want to treat the spool file as a script */
00235                      if (last) {
00236                         last->next = var;
00237                      } else {
00238                         o->vars = var;
00239                      }
00240                      last = var;
00241                   }
00242                } else
00243                   ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
00244             } else if (!strcasecmp(buf, "account")) {
00245                ast_copy_string(o->account, c, sizeof(o->account));
00246             } else if (!strcasecmp(buf, "alwaysdelete")) {
00247                ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
00248             } else if (!strcasecmp(buf, "archive")) {
00249                ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
00250             } else {
00251                ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
00252             }
00253          } else
00254             ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
00255       }
00256    }
00257    ast_copy_string(o->fn, fn, sizeof(o->fn));
00258    if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
00259       ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
00260       return -1;
00261    }
00262    return 0;
00263 }
00264 
00265 static void safe_append(struct outgoing *o, time_t now, char *s)
00266 {
00267    int fd;
00268    FILE *f;
00269    struct utimbuf tbuf;
00270    fd = open(o->fn, O_WRONLY|O_APPEND);
00271    if (fd > -1) {
00272       f = fdopen(fd, "a");
00273       if (f) {
00274          fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
00275          fclose(f);
00276       } else
00277          close(fd);
00278       /* Update the file time */
00279       tbuf.actime = now;
00280       tbuf.modtime = now + o->retrytime;
00281       if (utime(o->fn, &tbuf))
00282          ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
00283    }
00284 }
00285 
00286 /*!
00287  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
00288  *
00289  * \param o the pointer to outgoing struct
00290  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
00291  */
00292 static int remove_from_queue(struct outgoing *o, const char *status)
00293 {
00294    int fd;
00295    FILE *f;
00296    char newfn[256];
00297    const char *bname;
00298 
00299    if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
00300       struct stat current_file_status;
00301 
00302       if (!stat(o->fn, &current_file_status))
00303          if (time(NULL) < current_file_status.st_mtime)
00304             return 0;
00305    }
00306 
00307    if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
00308       unlink(o->fn);
00309       return 0;
00310    }
00311    if (mkdir(qdonedir, 0700) && (errno != EEXIST)) {
00312       ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
00313       unlink(o->fn);
00314       return -1;
00315    }
00316    fd = open(o->fn, O_WRONLY|O_APPEND);
00317    if (fd > -1) {
00318       f = fdopen(fd, "a");
00319       if (f) {
00320          fprintf(f, "Status: %s\n", status);
00321          fclose(f);
00322       } else
00323          close(fd);
00324    }
00325 
00326    bname = strrchr(o->fn,'/');
00327    if (bname == NULL) 
00328       bname = o->fn;
00329    else 
00330       bname++; 
00331    snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
00332    /* a existing call file the archive dir is overwritten */
00333    unlink(newfn);
00334    if (rename(o->fn, newfn) != 0) {
00335       unlink(o->fn);
00336       return -1;
00337    } else
00338       return 0;
00339 }
00340 
00341 static void *attempt_thread(void *data)
00342 {
00343    struct outgoing *o = data;
00344    int res, reason;
00345    if (!ast_strlen_zero(o->app)) {
00346       if (option_verbose > 2)
00347          ast_verbose(VERBOSE_PREFIX_3 "Attempting call on %s/%s for application %s(%s) (Retry %d)\n", o->tech, o->dest, o->app, o->data, o->retries);
00348       res = ast_pbx_outgoing_app(o->tech, o->format, o->dest, o->waittime * 1000, o->app, o->data, &reason, 2 /* wait to finish */, o->cid_num, o->cid_name, o->vars, o->account, NULL);
00349    } else {
00350       if (option_verbose > 2)
00351          ast_verbose(VERBOSE_PREFIX_3 "Attempting call on %s/%s for %s@%s:%d (Retry %d)\n", o->tech, o->dest, o->exten, o->context,o->priority, o->retries);
00352       res = ast_pbx_outgoing_exten(o->tech, o->format, o->dest, o->waittime * 1000, o->context, o->exten, o->priority, &reason, 2 /* wait to finish */, o->cid_num, o->cid_name, o->vars, o->account, NULL);
00353    }
00354    if (res) {
00355       ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
00356       if (o->retries >= o->maxretries + 1) {
00357          /* Max retries exceeded */
00358          ast_log(LOG_EVENT, "Queued call to %s/%s expired without completion after %d attempt%s\n", o->tech, o->dest, o->retries - 1, ((o->retries - 1) != 1) ? "s" : "");
00359          remove_from_queue(o, "Expired");
00360       } else {
00361          /* Notate that the call is still active */
00362          safe_append(o, time(NULL), "EndRetry");
00363       }
00364    } else {
00365       ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
00366       ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
00367       remove_from_queue(o, "Completed");
00368    }
00369    free_outgoing(o);
00370    return NULL;
00371 }
00372 
00373 static void launch_service(struct outgoing *o)
00374 {
00375    pthread_t t;
00376    pthread_attr_t attr;
00377    int ret;
00378    pthread_attr_init(&attr);
00379    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00380    if ((ret = ast_pthread_create(&t,&attr,attempt_thread, o)) != 0) {
00381       ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
00382       free_outgoing(o);
00383    }
00384    pthread_attr_destroy(&attr);
00385 }
00386 
00387 static int scan_service(char *fn, time_t now, time_t atime)
00388 {
00389    struct outgoing *o;
00390    FILE *f;
00391    o = malloc(sizeof(struct outgoing));
00392    if (o) {
00393       init_outgoing(o);
00394       f = fopen(fn, "r+");
00395       if (f) {
00396          if (!apply_outgoing(o, fn, f)) {
00397 #if 0
00398             printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
00399 #endif
00400             fclose(f);
00401             if (o->retries <= o->maxretries) {
00402                now += o->retrytime;
00403                if (o->callingpid && (o->callingpid == ast_mainpid)) {
00404                   safe_append(o, time(NULL), "DelayedRetry");
00405                   ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
00406                   free_outgoing(o);
00407                } else {
00408                   /* Increment retries */
00409                   o->retries++;
00410                   /* If someone else was calling, they're presumably gone now
00411                      so abort their retry and continue as we were... */
00412                   if (o->callingpid)
00413                      safe_append(o, time(NULL), "AbortRetry");
00414 
00415                   safe_append(o, now, "StartRetry");
00416                   launch_service(o);
00417                }
00418                return now;
00419             } else {
00420                ast_log(LOG_EVENT, "Queued call to %s/%s expired without completion after %d attempt%s\n", o->tech, o->dest, o->retries - 1, ((o->retries - 1) != 1) ? "s" : "");
00421                free_outgoing(o);
00422                remove_from_queue(o, "Expired");
00423                return 0;
00424             }
00425          } else {
00426             free_outgoing(o);
00427             ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
00428             fclose(f);
00429             remove_from_queue(o, "Failed");
00430          }
00431       } else {
00432          free_outgoing(o);
00433          ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
00434          remove_from_queue(o, "Failed");
00435       }
00436    } else
00437       ast_log(LOG_WARNING, "Out of memory :(\n");
00438    return -1;
00439 }
00440 
00441 static void *scan_thread(void *unused)
00442 {
00443    struct stat st;
00444    DIR *dir;
00445    struct dirent *de;
00446    char fn[256];
00447    int res;
00448    time_t last = 0, next = 0, now;
00449    for(;;) {
00450       /* Wait a sec */
00451       sleep(1);
00452       time(&now);
00453       if (!stat(qdir, &st)) {
00454          if ((st.st_mtime != last) || (next && (now > next))) {
00455 #if 0
00456             printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
00457             printf("Ooh, something changed / timeout\n");
00458 #endif            
00459             next = 0;
00460             last = st.st_mtime;
00461             dir = opendir(qdir);
00462             if (dir) {
00463                while((de = readdir(dir))) {
00464                   snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
00465                   if (!stat(fn, &st)) {
00466                      if (S_ISREG(st.st_mode)) {
00467                         if (st.st_mtime <= now) {
00468                            res = scan_service(fn, now, st.st_atime);
00469                            if (res > 0) {
00470                               /* Update next service time */
00471                               if (!next || (res < next)) {
00472                                  next = res;
00473                               }
00474                            } else if (res)
00475                               ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
00476                         } else {
00477                            /* Update "next" update if necessary */
00478                            if (!next || (st.st_mtime < next))
00479                               next = st.st_mtime;
00480                         }
00481                      }
00482                   } else
00483                      ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
00484                }
00485                closedir(dir);
00486             } else
00487                ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
00488          }
00489       } else
00490          ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
00491    }
00492    return NULL;
00493 }
00494 
00495 static int unload_module(void)
00496 {
00497    return -1;
00498 }
00499 
00500 static int load_module(void)
00501 {
00502    pthread_t thread;
00503    pthread_attr_t attr;
00504    int ret;
00505    snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
00506    if (mkdir(qdir, 0700) && (errno != EEXIST)) {
00507       ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
00508       return 0;
00509    }
00510    snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
00511    pthread_attr_init(&attr);
00512    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00513    if ((ret = ast_pthread_create_background(&thread,&attr,scan_thread, NULL)) != 0) {
00514       ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
00515       return -1;
00516    }
00517    pthread_attr_destroy(&attr);
00518    return 0;
00519 }
00520 
00521 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");

Generated on Mon Nov 24 15:34:20 2008 for Asterisk - the Open Source PBX by  doxygen 1.4.7