Sat Mar 26 11:07:59 2011

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 - 2010, 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: 292083 $")
00028 
00029 /* Handling of call files using inotify is not functioning correctly currently:
00030  * Issue 18089 - https://issues.asterisk.org/view.php?id=18089 
00031  */
00032 #undef HAVE_INOTIFY
00033 
00034 #include <sys/stat.h>
00035 #include <time.h>
00036 #include <utime.h>
00037 #include <dirent.h>
00038 #ifdef HAVE_INOTIFY
00039 #include <sys/inotify.h>
00040 #elif defined(HAVE_KQUEUE)
00041 #include <sys/types.h>
00042 #include <sys/time.h>
00043 #include <sys/event.h>
00044 #include <fcntl.h>
00045 #endif
00046 
00047 #include "asterisk/paths.h"   /* use ast_config_AST_SPOOL_DIR */
00048 #include "asterisk/lock.h"
00049 #include "asterisk/file.h"
00050 #include "asterisk/logger.h"
00051 #include "asterisk/channel.h"
00052 #include "asterisk/callerid.h"
00053 #include "asterisk/pbx.h"
00054 #include "asterisk/module.h"
00055 #include "asterisk/utils.h"
00056 #include "asterisk/options.h"
00057 
00058 /*
00059  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
00060  * The spool file contains a header 
00061  */
00062 
00063 enum {
00064    /*! Always delete the call file after a call succeeds or the
00065     * maximum number of retries is exceeded, even if the
00066     * modification time of the call file is in the future.
00067     */
00068    SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
00069    /* Don't unlink the call file after processing, move in qdonedir */
00070    SPOOL_FLAG_ARCHIVE = (1 << 1)
00071 };
00072 
00073 static char qdir[255];
00074 static char qdonedir[255];
00075 
00076 struct outgoing {
00077    int retries;                              /*!< Current number of retries */
00078    int maxretries;                           /*!< Maximum number of retries permitted */
00079    int retrytime;                            /*!< How long to wait between retries (in seconds) */
00080    int waittime;                             /*!< How long to wait for an answer */
00081    long callingpid;                          /*!< PID which is currently calling */
00082    format_t format;                          /*!< Formats (codecs) for this call */
00083    AST_DECLARE_STRING_FIELDS (
00084       AST_STRING_FIELD(fn);                 /*!< File name of call file */
00085       AST_STRING_FIELD(tech);               /*!< Which channel technology to use for outgoing call */
00086       AST_STRING_FIELD(dest);               /*!< Which device/line to use for outgoing call */
00087       AST_STRING_FIELD(app);                /*!< If application: Application name */
00088       AST_STRING_FIELD(data);               /*!< If application: Application data */
00089       AST_STRING_FIELD(exten);              /*!< If extension/context/priority: Extension in dialplan */
00090       AST_STRING_FIELD(context);            /*!< If extension/context/priority: Dialplan context */
00091       AST_STRING_FIELD(cid_num);            /*!< CallerID Information: Number/extension */
00092       AST_STRING_FIELD(cid_name);           /*!< CallerID Information: Name */
00093       AST_STRING_FIELD(account);            /*!< account code */
00094    );
00095    int priority;                             /*!< If extension/context/priority: Dialplan priority */
00096    struct ast_variable *vars;                /*!< Variables and Functions */
00097    int maxlen;                               /*!< Maximum length of call */
00098    struct ast_flags options;                 /*!< options */
00099 };
00100 
00101 static int init_outgoing(struct outgoing *o)
00102 {
00103    o->priority = 1;
00104    o->retrytime = 300;
00105    o->waittime = 45;
00106    o->format = AST_FORMAT_SLINEAR;
00107    ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
00108    if (ast_string_field_init(o, 128)) {
00109       return -1;
00110    }
00111    return 0;
00112 }
00113 
00114 static void free_outgoing(struct outgoing *o)
00115 {
00116    if (o->vars) {
00117       ast_variables_destroy(o->vars);
00118    }
00119    ast_string_field_free_memory(o);
00120    ast_free(o);
00121 }
00122 
00123 static int apply_outgoing(struct outgoing *o, const char *fn, FILE *f)
00124 {
00125    char buf[256];
00126    char *c, *c2;
00127    int lineno = 0;
00128    struct ast_variable *var, *last = o->vars;
00129 
00130    while (last && last->next) {
00131       last = last->next;
00132    }
00133 
00134    while(fgets(buf, sizeof(buf), f)) {
00135       lineno++;
00136       /* Trim comments */
00137       c = buf;
00138       while ((c = strchr(c, '#'))) {
00139          if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
00140             *c = '\0';
00141          else
00142             c++;
00143       }
00144 
00145       c = buf;
00146       while ((c = strchr(c, ';'))) {
00147          if ((c > buf) && (c[-1] == '\\')) {
00148             memmove(c - 1, c, strlen(c) + 1);
00149             c++;
00150          } else {
00151             *c = '\0';
00152             break;
00153          }
00154       }
00155 
00156       /* Trim trailing white space */
00157       while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
00158          buf[strlen(buf) - 1] = '\0';
00159       if (!ast_strlen_zero(buf)) {
00160          c = strchr(buf, ':');
00161          if (c) {
00162             *c = '\0';
00163             c++;
00164             while ((*c) && (*c < 33))
00165                c++;
00166 #if 0
00167             printf("'%s' is '%s' at line %d\n", buf, c, lineno);
00168 #endif
00169             if (!strcasecmp(buf, "channel")) {
00170                if ((c2 = strchr(c, '/'))) {
00171                   *c2 = '\0';
00172                   c2++;
00173                   ast_string_field_set(o, tech, c);
00174                   ast_string_field_set(o, dest, c2);
00175                } else {
00176                   ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
00177                }
00178             } else if (!strcasecmp(buf, "callerid")) {
00179                char cid_name[80] = {0}, cid_num[80] = {0};
00180                ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
00181                ast_string_field_set(o, cid_num, cid_num);
00182                ast_string_field_set(o, cid_name, cid_name);
00183             } else if (!strcasecmp(buf, "application")) {
00184                ast_string_field_set(o, app, c);
00185             } else if (!strcasecmp(buf, "data")) {
00186                ast_string_field_set(o, data, c);
00187             } else if (!strcasecmp(buf, "maxretries")) {
00188                if (sscanf(c, "%30d", &o->maxretries) != 1) {
00189                   ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
00190                   o->maxretries = 0;
00191                }
00192             } else if (!strcasecmp(buf, "codecs")) {
00193                ast_parse_allow_disallow(NULL, &o->format, c, 1);
00194             } else if (!strcasecmp(buf, "context")) {
00195                ast_string_field_set(o, context, c);
00196             } else if (!strcasecmp(buf, "extension")) {
00197                ast_string_field_set(o, exten, c);
00198             } else if (!strcasecmp(buf, "priority")) {
00199                if ((sscanf(c, "%30d", &o->priority) != 1) || (o->priority < 1)) {
00200                   ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
00201                   o->priority = 1;
00202                }
00203             } else if (!strcasecmp(buf, "retrytime")) {
00204                if ((sscanf(c, "%30d", &o->retrytime) != 1) || (o->retrytime < 1)) {
00205                   ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
00206                   o->retrytime = 300;
00207                }
00208             } else if (!strcasecmp(buf, "waittime")) {
00209                if ((sscanf(c, "%30d", &o->waittime) != 1) || (o->waittime < 1)) {
00210                   ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
00211                   o->waittime = 45;
00212                }
00213             } else if (!strcasecmp(buf, "retry")) {
00214                o->retries++;
00215             } else if (!strcasecmp(buf, "startretry")) {
00216                if (sscanf(c, "%30ld", &o->callingpid) != 1) {
00217                   ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
00218                   o->callingpid = 0;
00219                }
00220             } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
00221                o->callingpid = 0;
00222                o->retries++;
00223             } else if (!strcasecmp(buf, "delayedretry")) {
00224             } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
00225                c2 = c;
00226                strsep(&c2, "=");
00227                if (c2) {
00228                   var = ast_variable_new(c, c2, fn);
00229                   if (var) {
00230                      /* Always insert at the end, because some people want to treat the spool file as a script */
00231                      if (last) {
00232                         last->next = var;
00233                      } else {
00234                         o->vars = var;
00235                      }
00236                      last = var;
00237                   }
00238                } else
00239                   ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
00240             } else if (!strcasecmp(buf, "account")) {
00241                ast_string_field_set(o, account, c);
00242             } else if (!strcasecmp(buf, "alwaysdelete")) {
00243                ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
00244             } else if (!strcasecmp(buf, "archive")) {
00245                ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
00246             } else {
00247                ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
00248             }
00249          } else
00250             ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
00251       }
00252    }
00253    ast_string_field_set(o, fn, fn);
00254    if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
00255       ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
00256       return -1;
00257    }
00258    return 0;
00259 }
00260 
00261 static void safe_append(struct outgoing *o, time_t now, char *s)
00262 {
00263    int fd;
00264    FILE *f;
00265    struct utimbuf tbuf;
00266 
00267    if ((fd = open(o->fn, O_WRONLY | O_APPEND)) < 0)
00268       return;
00269 
00270    if ((f = fdopen(fd, "a"))) {
00271       fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
00272       fclose(f);
00273    } else
00274       close(fd);
00275 
00276    /* Update the file time */
00277    tbuf.actime = now;
00278    tbuf.modtime = now + o->retrytime;
00279    if (utime(o->fn, &tbuf))
00280       ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
00281 }
00282 
00283 /*!
00284  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
00285  *
00286  * \param o the pointer to outgoing struct
00287  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
00288  */
00289 static int remove_from_queue(struct outgoing *o, const char *status)
00290 {
00291    int fd;
00292    FILE *f;
00293    char newfn[256];
00294    const char *bname;
00295 
00296    if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
00297       struct stat current_file_status;
00298 
00299       if (!stat(o->fn, &current_file_status)) {
00300          if (time(NULL) < current_file_status.st_mtime)
00301             return 0;
00302       }
00303    }
00304 
00305    if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
00306       unlink(o->fn);
00307       return 0;
00308    }
00309 
00310    if (ast_mkdir(qdonedir, 0777)) {
00311       ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
00312       unlink(o->fn);
00313       return -1;
00314    }
00315 
00316    if ((fd = open(o->fn, O_WRONLY | O_APPEND))) {
00317       if ((f = fdopen(fd, "a"))) {
00318          fprintf(f, "Status: %s\n", status);
00319          fclose(f);
00320       } else
00321          close(fd);
00322    }
00323 
00324    if (!(bname = strrchr(o->fn, '/')))
00325       bname = o->fn;
00326    else
00327       bname++; 
00328    snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
00329    /* a existing call file the archive dir is overwritten */
00330    unlink(newfn);
00331    if (rename(o->fn, newfn) != 0) {
00332       unlink(o->fn);
00333       return -1;
00334    } else
00335       return 0;
00336 }
00337 
00338 static void *attempt_thread(void *data)
00339 {
00340    struct outgoing *o = data;
00341    int res, reason;
00342    if (!ast_strlen_zero(o->app)) {
00343       ast_verb(3, "Attempting call on %s/%s for application %s(%s) (Retry %d)\n", o->tech, o->dest, o->app, o->data, o->retries);
00344       res = ast_pbx_outgoing_app(o->tech, o->format, (void *) 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);
00345       o->vars = NULL;
00346    } else {
00347       ast_verb(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);
00348       res = ast_pbx_outgoing_exten(o->tech, o->format, (void *) 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);
00349       o->vars = NULL;
00350    }
00351    if (res) {
00352       ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
00353       if (o->retries >= o->maxretries + 1) {
00354          /* Max retries exceeded */
00355          ast_log(LOG_NOTICE, "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" : "");
00356          remove_from_queue(o, "Expired");
00357       } else {
00358          /* Notate that the call is still active */
00359          safe_append(o, time(NULL), "EndRetry");
00360       }
00361    } else {
00362       ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
00363       remove_from_queue(o, "Completed");
00364    }
00365    free_outgoing(o);
00366    return NULL;
00367 }
00368 
00369 static void launch_service(struct outgoing *o)
00370 {
00371    pthread_t t;
00372    int ret;
00373 
00374    if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
00375       ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
00376       free_outgoing(o);
00377    }
00378 }
00379 
00380 /* Called from scan_thread or queue_file */
00381 static int scan_service(const char *fn, time_t now)
00382 {
00383    struct outgoing *o = NULL;
00384    FILE *f;
00385    int res = 0;
00386 
00387    if (!(o = ast_calloc(1, sizeof(*o)))) {
00388       ast_log(LOG_WARNING, "Out of memory ;(\n");
00389       return -1;
00390    }
00391    
00392    if (init_outgoing(o)) {
00393       /* No need to call free_outgoing here since we know the failure
00394        * was to allocate string fields and no variables have been allocated
00395        * yet.
00396        */
00397       ast_free(o);
00398       return -1;
00399    }
00400 
00401    /* Attempt to open the file */
00402    if (!(f = fopen(fn, "r+"))) {
00403       remove_from_queue(o, "Failed");
00404       free_outgoing(o);
00405       ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
00406       return -1;
00407    }
00408 
00409    /* Read in and verify the contents */
00410    if (apply_outgoing(o, fn, f)) {
00411       remove_from_queue(o, "Failed");
00412       free_outgoing(o);
00413       ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
00414       fclose(f);
00415       return -1;
00416    }
00417    
00418 #if 0
00419    printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
00420 #endif
00421    fclose(f);
00422    if (o->retries <= o->maxretries) {
00423       now += o->retrytime;
00424       if (o->callingpid && (o->callingpid == ast_mainpid)) {
00425          safe_append(o, time(NULL), "DelayedRetry");
00426          ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
00427          free_outgoing(o);
00428       } else {
00429          /* Increment retries */
00430          o->retries++;
00431          /* If someone else was calling, they're presumably gone now
00432             so abort their retry and continue as we were... */
00433          if (o->callingpid)
00434             safe_append(o, time(NULL), "AbortRetry");
00435          
00436          safe_append(o, now, "StartRetry");
00437          launch_service(o);
00438       }
00439       res = now;
00440    } else {
00441       ast_log(LOG_NOTICE, "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" : "");
00442       remove_from_queue(o, "Expired");
00443       free_outgoing(o);
00444    }
00445 
00446    return res;
00447 }
00448 
00449 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
00450 struct direntry {
00451    AST_LIST_ENTRY(direntry) list;
00452    time_t mtime;
00453    char name[0];
00454 };
00455 
00456 /* Only one thread is accessing this list, so no lock is necessary */
00457 static AST_LIST_HEAD_NOLOCK_STATIC(dirlist, direntry);
00458 
00459 static void queue_file(const char *filename, time_t when)
00460 {
00461    struct stat st;
00462    struct direntry *cur, *new;
00463    int res;
00464    time_t now = time(NULL);
00465 
00466    if (filename[0] != '/') {
00467       char *fn = alloca(strlen(qdir) + strlen(filename) + 2);
00468       sprintf(fn, "%s/%s", qdir, filename); /* SAFE */
00469       filename = fn;
00470    }
00471 
00472    if (when == 0) {
00473       if (stat(filename, &st)) {
00474          ast_log(LOG_WARNING, "Unable to stat %s: %s\n", filename, strerror(errno));
00475          return;
00476       }
00477 
00478       if (!S_ISREG(st.st_mode)) {
00479          return;
00480       }
00481 
00482       when = st.st_mtime;
00483    }
00484 
00485 #ifndef HAVE_INOTIFY
00486    /* Need to check the existing list for kqueue(2), in order to avoid duplicates. */
00487    AST_LIST_TRAVERSE(&dirlist, cur, list) {
00488       if (cur->mtime == when && !strcmp(filename, cur->name)) {
00489          return;
00490       }
00491    }
00492 #endif
00493 
00494    if ((res = when) > now || (res = scan_service(filename, now)) > 0) {
00495       if (!(new = ast_calloc(1, sizeof(*new) + strlen(filename) + 1))) {
00496          return;
00497       }
00498       new->mtime = res;
00499       strcpy(new->name, filename);
00500       /* List is ordered by mtime */
00501       if (AST_LIST_EMPTY(&dirlist)) {
00502          AST_LIST_INSERT_HEAD(&dirlist, new, list);
00503       } else {
00504          int found = 0;
00505          AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
00506             if (cur->mtime > new->mtime) {
00507                AST_LIST_INSERT_BEFORE_CURRENT(new, list);
00508                found = 1;
00509                break;
00510             }
00511          }
00512          AST_LIST_TRAVERSE_SAFE_END
00513          if (!found) {
00514             AST_LIST_INSERT_TAIL(&dirlist, new, list);
00515          }
00516       }
00517    }
00518 }
00519 
00520 static void *scan_thread(void *unused)
00521 {
00522    DIR *dir;
00523    struct dirent *de;
00524    time_t now;
00525    struct timespec ts = { .tv_sec = 1 };
00526 #ifdef HAVE_INOTIFY
00527    int res;
00528    int inotify_fd = inotify_init();
00529    struct {
00530       struct inotify_event iev;
00531       /* It may not look like we're using this element, but when we read
00532        * from inotify_fd, the event is typically larger than the first
00533        * struct, and overflows into this second one. */
00534       char name[FILENAME_MAX + 1];
00535    } buf;
00536    struct pollfd pfd = { .fd = inotify_fd, .events = POLLIN };
00537 #else
00538    struct timespec nowait = { 0, 1 };
00539    int inotify_fd = kqueue();
00540    struct kevent kev;
00541 #endif
00542    struct direntry *cur;
00543 
00544    while (!ast_fully_booted) {
00545       nanosleep(&ts, NULL);
00546    }
00547 
00548    if (inotify_fd < 0) {
00549       ast_log(LOG_ERROR, "Unable to initialize "
00550 #ifdef HAVE_INOTIFY
00551          "inotify(7)"
00552 #else
00553          "kqueue(2)"
00554 #endif
00555          "\n");
00556       return NULL;
00557    }
00558 
00559 #ifdef HAVE_INOTIFY
00560    inotify_add_watch(inotify_fd, qdir, IN_CLOSE_WRITE | IN_MOVED_TO);
00561 #endif
00562 
00563    /* First, run through the directory and clear existing entries */
00564    if (!(dir = opendir(qdir))) {
00565       ast_log(LOG_ERROR, "Unable to open directory %s: %s\n", qdir, strerror(errno));
00566       return NULL;
00567    }
00568 
00569 #ifndef HAVE_INOTIFY
00570    EV_SET(&kev, dirfd(dir), EVFILT_VNODE, EV_ADD | EV_ENABLE, NOTE_WRITE | NOTE_EXTEND | NOTE_DELETE | NOTE_REVOKE | NOTE_ATTRIB, 0, NULL);
00571    if (kevent(inotify_fd, &kev, 1, NULL, 0, &nowait) < 0 && errno != 0) {
00572       ast_log(LOG_ERROR, "Unable to watch directory %s: %s\n", qdir, strerror(errno));
00573    }
00574 #endif
00575    now = time(NULL);
00576    while ((de = readdir(dir))) {
00577       queue_file(de->d_name, 0);
00578    }
00579 
00580 #ifdef HAVE_INOTIFY
00581    /* Directory needs to remain open for kqueue(2) */
00582    closedir(dir);
00583 #endif
00584 
00585    /* Wait for either a) next timestamp to occur, or b) a change to happen */
00586    for (;/* ever */;) {
00587       time_t next = AST_LIST_EMPTY(&dirlist) ? INT_MAX : AST_LIST_FIRST(&dirlist)->mtime;
00588 
00589       time(&now);
00590       if (next > now) {
00591 #ifdef HAVE_INOTIFY
00592          int stage = 0;
00593          /* Convert from seconds to milliseconds, unless there's nothing
00594           * in the queue already, in which case, we wait forever. */
00595          int waittime = next == INT_MAX ? -1 : (next - now) * 1000;
00596          /* When a file arrives, add it to the queue, in mtime order. */
00597          if ((res = poll(&pfd, 1, waittime)) > 0 && (stage = 1) &&
00598             (res = read(inotify_fd, &buf, sizeof(buf))) >= sizeof(buf.iev)) {
00599             /* File(s) added to directory, add them to my list */
00600             do {
00601                queue_file(buf.iev.name, 0);
00602                res -= sizeof(buf.iev) + buf.iev.len;
00603                if (res >= sizeof(buf.iev)) {
00604                   memmove(&buf.iev, &buf.iev.name[buf.iev.len], res);
00605                   continue;
00606                }
00607                break;
00608             } while (1);
00609          } else if (res < 0 && errno != EINTR && errno != EAGAIN) {
00610             ast_debug(1, "Got an error back from %s(2): %s\n", stage ? "read" : "poll", strerror(errno));
00611          }
00612 #else
00613          struct timespec ts2 = { next - now, 0 };
00614          if (kevent(inotify_fd, NULL, 0, &kev, 1, &ts2) <= 0) {
00615             /* Interrupt or timeout, restart calculations */
00616             continue;
00617          } else {
00618             /* Directory changed, rescan */
00619             rewinddir(dir);
00620             while ((de = readdir(dir))) {
00621                queue_file(de->d_name, 0);
00622             }
00623          }
00624 #endif
00625          time(&now);
00626       }
00627 
00628       /* Empty the list of all entries ready to be processed */
00629       while (!AST_LIST_EMPTY(&dirlist) && AST_LIST_FIRST(&dirlist)->mtime <= now) {
00630          cur = AST_LIST_REMOVE_HEAD(&dirlist, list);
00631          queue_file(cur->name, cur->mtime);
00632          ast_free(cur);
00633       }
00634    }
00635    return NULL;
00636 }
00637 
00638 #else
00639 static void *scan_thread(void *unused)
00640 {
00641    struct stat st;
00642    DIR *dir;
00643    struct dirent *de;
00644    char fn[256];
00645    int res;
00646    time_t last = 0, next = 0, now;
00647    struct timespec ts = { .tv_sec = 1 };
00648   
00649    while (!ast_fully_booted) {
00650       nanosleep(&ts, NULL);
00651    }
00652 
00653    for(;;) {
00654       /* Wait a sec */
00655       nanosleep(&ts, NULL);
00656       time(&now);
00657 
00658       if (stat(qdir, &st)) {
00659          ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
00660          continue;
00661       }
00662 
00663       /* Make sure it is time for us to execute our check */
00664       if ((st.st_mtime == last) && (next && (next > now)))
00665          continue;
00666       
00667 #if 0
00668       printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
00669       printf("Ooh, something changed / timeout\n");
00670 #endif
00671       next = 0;
00672       last = st.st_mtime;
00673 
00674       if (!(dir = opendir(qdir))) {
00675          ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
00676          continue;
00677       }
00678 
00679       while ((de = readdir(dir))) {
00680          snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
00681          if (stat(fn, &st)) {
00682             ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
00683             continue;
00684          }
00685          if (!S_ISREG(st.st_mode))
00686             continue;
00687          if (st.st_mtime <= now) {
00688             res = scan_service(fn, now);
00689             if (res > 0) {
00690                /* Update next service time */
00691                if (!next || (res < next)) {
00692                   next = res;
00693                }
00694             } else if (res) {
00695                ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
00696             } else if (!next) {
00697                /* Expired entry: must recheck on the next go-around */
00698                next = st.st_mtime;
00699             }
00700          } else {
00701             /* Update "next" update if necessary */
00702             if (!next || (st.st_mtime < next))
00703                next = st.st_mtime;
00704          }
00705       }
00706       closedir(dir);
00707    }
00708    return NULL;
00709 }
00710 #endif
00711 
00712 static int unload_module(void)
00713 {
00714    return -1;
00715 }
00716 
00717 static int load_module(void)
00718 {
00719    pthread_t thread;
00720    int ret;
00721    snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
00722    if (ast_mkdir(qdir, 0777)) {
00723       ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
00724       return AST_MODULE_LOAD_DECLINE;
00725    }
00726    snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
00727 
00728    if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
00729       ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
00730       return AST_MODULE_LOAD_FAILURE;
00731    }
00732 
00733    return AST_MODULE_LOAD_SUCCESS;
00734 }
00735 
00736 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");

Generated on Sat Mar 26 11:07:59 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9