Thu Oct 8 21:56:03 2009

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

Generated on Thu Oct 8 21:56:03 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.6