Merged revisions 294605 via svnmerge from
[asterisk/asterisk.git] / pbx / pbx_spool.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Full-featured outgoing call spool support
22  * 
23  */
24
25 #include "asterisk.h"
26
27 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
28
29 #include <sys/stat.h>
30 #include <time.h>
31 #include <utime.h>
32 #include <dirent.h>
33 #ifdef HAVE_INOTIFY
34 #include <sys/inotify.h>
35 #elif defined(HAVE_KQUEUE)
36 #include <sys/types.h>
37 #include <sys/time.h>
38 #include <sys/event.h>
39 #include <fcntl.h>
40 #endif
41
42 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
43 #include "asterisk/lock.h"
44 #include "asterisk/file.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/pbx.h"
49 #include "asterisk/module.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/options.h"
52
53 /*
54  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
55  * The spool file contains a header 
56  */
57
58 enum {
59         /*! Always delete the call file after a call succeeds or the
60          * maximum number of retries is exceeded, even if the
61          * modification time of the call file is in the future.
62          */
63         SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
64         /* Don't unlink the call file after processing, move in qdonedir */
65         SPOOL_FLAG_ARCHIVE = (1 << 1),
66 };
67
68 static char qdir[255];
69 static char qdonedir[255];
70
71 struct outgoing {
72         int retries;                              /*!< Current number of retries */
73         int maxretries;                           /*!< Maximum number of retries permitted */
74         int retrytime;                            /*!< How long to wait between retries (in seconds) */
75         int waittime;                             /*!< How long to wait for an answer */
76         long callingpid;                          /*!< PID which is currently calling */
77         format_t format;                          /*!< Formats (codecs) for this call */
78         AST_DECLARE_STRING_FIELDS (
79                 AST_STRING_FIELD(fn);                 /*!< File name of call file */
80                 AST_STRING_FIELD(tech);               /*!< Which channel technology to use for outgoing call */
81                 AST_STRING_FIELD(dest);               /*!< Which device/line to use for outgoing call */
82                 AST_STRING_FIELD(app);                /*!< If application: Application name */
83                 AST_STRING_FIELD(data);               /*!< If application: Application data */
84                 AST_STRING_FIELD(exten);              /*!< If extension/context/priority: Extension in dialplan */
85                 AST_STRING_FIELD(context);            /*!< If extension/context/priority: Dialplan context */
86                 AST_STRING_FIELD(cid_num);            /*!< CallerID Information: Number/extension */
87                 AST_STRING_FIELD(cid_name);           /*!< CallerID Information: Name */
88                 AST_STRING_FIELD(account);            /*!< account code */
89         );
90         int priority;                             /*!< If extension/context/priority: Dialplan priority */
91         struct ast_variable *vars;                /*!< Variables and Functions */
92         int maxlen;                               /*!< Maximum length of call */
93         struct ast_flags options;                 /*!< options */
94 };
95
96 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
97 static void queue_file(const char *filename, time_t when);
98 #endif
99
100 static int init_outgoing(struct outgoing *o)
101 {
102         o->priority = 1;
103         o->retrytime = 300;
104         o->waittime = 45;
105         o->format = AST_FORMAT_SLINEAR;
106         ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
107         if (ast_string_field_init(o, 128)) {
108                 return -1;
109         }
110         return 0;
111 }
112
113 static void free_outgoing(struct outgoing *o)
114 {
115         if (o->vars) {
116                 ast_variables_destroy(o->vars);
117         }
118         ast_string_field_free_memory(o);
119         ast_free(o);
120 }
121
122 static int apply_outgoing(struct outgoing *o, const char *fn, FILE *f)
123 {
124         char buf[256];
125         char *c, *c2;
126         int lineno = 0;
127         struct ast_variable *var, *last = o->vars;
128
129         while (last && last->next) {
130                 last = last->next;
131         }
132
133         while(fgets(buf, sizeof(buf), f)) {
134                 lineno++;
135                 /* Trim comments */
136                 c = buf;
137                 while ((c = strchr(c, '#'))) {
138                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
139                                 *c = '\0';
140                         else
141                                 c++;
142                 }
143
144                 c = buf;
145                 while ((c = strchr(c, ';'))) {
146                         if ((c > buf) && (c[-1] == '\\')) {
147                                 memmove(c - 1, c, strlen(c) + 1);
148                                 c++;
149                         } else {
150                                 *c = '\0';
151                                 break;
152                         }
153                 }
154
155                 /* Trim trailing white space */
156                 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
157                         buf[strlen(buf) - 1] = '\0';
158                 if (!ast_strlen_zero(buf)) {
159                         c = strchr(buf, ':');
160                         if (c) {
161                                 *c = '\0';
162                                 c++;
163                                 while ((*c) && (*c < 33))
164                                         c++;
165 #if 0
166                                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
167 #endif
168                                 if (!strcasecmp(buf, "channel")) {
169                                         if ((c2 = strchr(c, '/'))) {
170                                                 *c2 = '\0';
171                                                 c2++;
172                                                 ast_string_field_set(o, tech, c);
173                                                 ast_string_field_set(o, dest, c2);
174                                         } else {
175                                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
176                                         }
177                                 } else if (!strcasecmp(buf, "callerid")) {
178                                         char cid_name[80] = {0}, cid_num[80] = {0};
179                                         ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
180                                         ast_string_field_set(o, cid_num, cid_num);
181                                         ast_string_field_set(o, cid_name, cid_name);
182                                 } else if (!strcasecmp(buf, "application")) {
183                                         ast_string_field_set(o, app, c);
184                                 } else if (!strcasecmp(buf, "data")) {
185                                         ast_string_field_set(o, data, c);
186                                 } else if (!strcasecmp(buf, "maxretries")) {
187                                         if (sscanf(c, "%30d", &o->maxretries) != 1) {
188                                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
189                                                 o->maxretries = 0;
190                                         }
191                                 } else if (!strcasecmp(buf, "codecs")) {
192                                         ast_parse_allow_disallow(NULL, &o->format, c, 1);
193                                 } else if (!strcasecmp(buf, "context")) {
194                                         ast_string_field_set(o, context, c);
195                                 } else if (!strcasecmp(buf, "extension")) {
196                                         ast_string_field_set(o, exten, c);
197                                 } else if (!strcasecmp(buf, "priority")) {
198                                         if ((sscanf(c, "%30d", &o->priority) != 1) || (o->priority < 1)) {
199                                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
200                                                 o->priority = 1;
201                                         }
202                                 } else if (!strcasecmp(buf, "retrytime")) {
203                                         if ((sscanf(c, "%30d", &o->retrytime) != 1) || (o->retrytime < 1)) {
204                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
205                                                 o->retrytime = 300;
206                                         }
207                                 } else if (!strcasecmp(buf, "waittime")) {
208                                         if ((sscanf(c, "%30d", &o->waittime) != 1) || (o->waittime < 1)) {
209                                                 ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
210                                                 o->waittime = 45;
211                                         }
212                                 } else if (!strcasecmp(buf, "retry")) {
213                                         o->retries++;
214                                 } else if (!strcasecmp(buf, "startretry")) {
215                                         if (sscanf(c, "%30ld", &o->callingpid) != 1) {
216                                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
217                                                 o->callingpid = 0;
218                                         }
219                                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
220                                         o->callingpid = 0;
221                                         o->retries++;
222                                 } else if (!strcasecmp(buf, "delayedretry")) {
223                                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
224                                         c2 = c;
225                                         strsep(&c2, "=");
226                                         if (c2) {
227                                                 var = ast_variable_new(c, c2, fn);
228                                                 if (var) {
229                                                         /* Always insert at the end, because some people want to treat the spool file as a script */
230                                                         if (last) {
231                                                                 last->next = var;
232                                                         } else {
233                                                                 o->vars = var;
234                                                         }
235                                                         last = var;
236                                                 }
237                                         } else
238                                                 ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
239                                 } else if (!strcasecmp(buf, "account")) {
240                                         ast_string_field_set(o, account, c);
241                                 } else if (!strcasecmp(buf, "alwaysdelete")) {
242                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
243                                 } else if (!strcasecmp(buf, "archive")) {
244                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
245                                 } else {
246                                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
247                                 }
248                         } else
249                                 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
250                 }
251         }
252         ast_string_field_set(o, fn, fn);
253         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
254                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
255                 return -1;
256         }
257         return 0;
258 }
259
260 static void safe_append(struct outgoing *o, time_t now, char *s)
261 {
262         FILE *f;
263         struct utimbuf tbuf = { .actime = now, .modtime = now + o->retrytime };
264
265         ast_debug(1, "Outgoing %s/%s: %s\n", o->tech, o->dest, s);
266
267         if ((f = fopen(o->fn, "a"))) {
268                 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
269                 fclose(f);
270         }
271
272         /* Update the file time */
273         if (utime(o->fn, &tbuf)) {
274                 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
275         }
276 }
277
278 /*!
279  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
280  *
281  * \param o the pointer to outgoing struct
282  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
283  */
284 static int remove_from_queue(struct outgoing *o, const char *status)
285 {
286         FILE *f;
287         char newfn[256];
288         const char *bname;
289
290         if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
291                 struct stat current_file_status;
292
293                 if (!stat(o->fn, &current_file_status)) {
294                         if (time(NULL) < current_file_status.st_mtime) {
295                                 return 0;
296                         }
297                 }
298         }
299
300         if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
301                 unlink(o->fn);
302                 return 0;
303         }
304
305         if (ast_mkdir(qdonedir, 0777)) {
306                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
307                 unlink(o->fn);
308                 return -1;
309         }
310
311         if (!(bname = strrchr(o->fn, '/'))) {
312                 bname = o->fn;
313         } else {
314                 bname++;
315         }
316
317         snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
318         /* a existing call file the archive dir is overwritten */
319         unlink(newfn);
320         if (rename(o->fn, newfn) != 0) {
321                 unlink(o->fn);
322                 return -1;
323         }
324
325         /* Only append to the file AFTER we move it out of the watched directory,
326          * otherwise the fclose() causes another event for inotify(7) */
327         if ((f = fopen(newfn, "a"))) {
328                 fprintf(f, "Status: %s\n", status);
329                 fclose(f);
330         }
331
332         return 0;
333 }
334
335 static void *attempt_thread(void *data)
336 {
337         struct outgoing *o = data;
338         int res, reason;
339         if (!ast_strlen_zero(o->app)) {
340                 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);
341                 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);
342                 o->vars = NULL;
343         } else {
344                 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);
345                 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);
346                 o->vars = NULL;
347         }
348         if (res) {
349                 ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
350                 if (o->retries >= o->maxretries + 1) {
351                         /* Max retries exceeded */
352                         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" : "");
353                         remove_from_queue(o, "Expired");
354                 } else {
355                         /* Notate that the call is still active */
356                         safe_append(o, time(NULL), "EndRetry");
357 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
358                         queue_file(o->fn, time(NULL) + o->retrytime);
359 #endif
360                 }
361         } else {
362                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
363                 remove_from_queue(o, "Completed");
364         }
365         free_outgoing(o);
366         return NULL;
367 }
368
369 static void launch_service(struct outgoing *o)
370 {
371         pthread_t t;
372         int ret;
373
374         if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
375                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
376                 free_outgoing(o);
377         }
378 }
379
380 /* Called from scan_thread or queue_file */
381 static int scan_service(const char *fn, time_t now)
382 {
383         struct outgoing *o = NULL;
384         FILE *f;
385         int res = 0;
386
387         if (!(o = ast_calloc(1, sizeof(*o)))) {
388                 ast_log(LOG_WARNING, "Out of memory ;(\n");
389                 return -1;
390         }
391
392         if (init_outgoing(o)) {
393                 /* No need to call free_outgoing here since we know the failure
394                  * was to allocate string fields and no variables have been allocated
395                  * yet.
396                  */
397                 ast_free(o);
398                 return -1;
399         }
400
401         /* Attempt to open the file */
402         if (!(f = fopen(fn, "r"))) {
403                 remove_from_queue(o, "Failed");
404                 free_outgoing(o);
405 #if !defined(HAVE_INOTIFY) && !defined(HAVE_KQUEUE)
406                 ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
407 #endif
408                 return -1;
409         }
410
411         /* Read in and verify the contents */
412         if (apply_outgoing(o, fn, f)) {
413                 remove_from_queue(o, "Failed");
414                 free_outgoing(o);
415                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
416                 fclose(f);
417                 return -1;
418         }
419
420 #if 0
421         printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
422 #endif
423         fclose(f);
424         if (o->retries <= o->maxretries) {
425                 now += o->retrytime;
426                 if (o->callingpid && (o->callingpid == ast_mainpid)) {
427                         safe_append(o, time(NULL), "DelayedRetry");
428                         ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
429                         free_outgoing(o);
430                 } else {
431                         /* Increment retries */
432                         o->retries++;
433                         /* If someone else was calling, they're presumably gone now
434                            so abort their retry and continue as we were... */
435                         if (o->callingpid)
436                                 safe_append(o, time(NULL), "AbortRetry");
437
438                         safe_append(o, now, "StartRetry");
439                         launch_service(o);
440                 }
441                 res = now;
442         } else {
443                 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" : "");
444                 remove_from_queue(o, "Expired");
445                 free_outgoing(o);
446         }
447
448         return res;
449 }
450
451 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
452 struct direntry {
453         AST_LIST_ENTRY(direntry) list;
454         time_t mtime;
455         char name[0];
456 };
457
458 static AST_LIST_HEAD_STATIC(dirlist, direntry);
459
460 #if defined(HAVE_INOTIFY)
461 /* Only one thread is accessing this list, so no lock is necessary */
462 static AST_LIST_HEAD_NOLOCK_STATIC(createlist, direntry);
463 #endif
464
465 static void queue_file(const char *filename, time_t when)
466 {
467         struct stat st;
468         struct direntry *cur, *new;
469         int res;
470         time_t now = time(NULL);
471
472         if (filename[0] != '/') {
473                 char *fn = alloca(strlen(qdir) + strlen(filename) + 2);
474                 sprintf(fn, "%s/%s", qdir, filename); /* SAFE */
475                 filename = fn;
476         }
477
478         if (when == 0) {
479                 if (stat(filename, &st)) {
480                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", filename, strerror(errno));
481                         return;
482                 }
483
484                 if (!S_ISREG(st.st_mode)) {
485                         return;
486                 }
487
488                 when = st.st_mtime;
489         }
490
491         /* Need to check the existing list in order to avoid duplicates. */
492         AST_LIST_LOCK(&dirlist);
493         AST_LIST_TRAVERSE(&dirlist, cur, list) {
494                 if (cur->mtime == when && !strcmp(filename, cur->name)) {
495                         AST_LIST_UNLOCK(&dirlist);
496                         return;
497                 }
498         }
499
500         if ((res = when) > now || (res = scan_service(filename, now)) > 0) {
501                 if (!(new = ast_calloc(1, sizeof(*new) + strlen(filename) + 1))) {
502                         AST_LIST_UNLOCK(&dirlist);
503                         return;
504                 }
505                 new->mtime = res;
506                 strcpy(new->name, filename);
507                 /* List is ordered by mtime */
508                 if (AST_LIST_EMPTY(&dirlist)) {
509                         AST_LIST_INSERT_HEAD(&dirlist, new, list);
510                 } else {
511                         int found = 0;
512                         AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
513                                 if (cur->mtime > new->mtime) {
514                                         AST_LIST_INSERT_BEFORE_CURRENT(new, list);
515                                         found = 1;
516                                         break;
517                                 }
518                         }
519                         AST_LIST_TRAVERSE_SAFE_END
520                         if (!found) {
521                                 AST_LIST_INSERT_TAIL(&dirlist, new, list);
522                         }
523                 }
524         }
525         AST_LIST_UNLOCK(&dirlist);
526 }
527
528 #ifdef HAVE_INOTIFY
529 static void queue_file_create(const char *filename)
530 {
531         struct direntry *cur;
532
533         AST_LIST_TRAVERSE(&createlist, cur, list) {
534                 if (!strcmp(cur->name, filename)) {
535                         return;
536                 }
537         }
538
539         if (!(cur = ast_calloc(1, sizeof(*cur) + strlen(filename) + 1))) {
540                 return;
541         }
542         strcpy(cur->name, filename);
543         AST_LIST_INSERT_TAIL(&createlist, cur, list);
544 }
545
546 static void queue_file_write(const char *filename)
547 {
548         struct direntry *cur;
549         /* Only queue entries where an IN_CREATE preceded the IN_CLOSE_WRITE */
550         AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
551                 if (!strcmp(cur->name, filename)) {
552                         AST_LIST_REMOVE_CURRENT(list);
553                         ast_free(cur);
554                         queue_file(filename, 0);
555                         break;
556                 }
557         }
558         AST_LIST_TRAVERSE_SAFE_END
559 }
560 #endif
561
562 static void *scan_thread(void *unused)
563 {
564         DIR *dir;
565         struct dirent *de;
566         time_t now;
567         struct timespec ts = { .tv_sec = 1 };
568 #ifdef HAVE_INOTIFY
569         ssize_t res;
570         int inotify_fd = inotify_init();
571         struct inotify_event *iev;
572         char buf[8192] __attribute__((aligned (sizeof(int))));
573         struct pollfd pfd = { .fd = inotify_fd, .events = POLLIN };
574 #else
575         struct timespec nowait = { 0, 1 };
576         int inotify_fd = kqueue();
577         struct kevent kev;
578 #endif
579         struct direntry *cur;
580
581         while (!ast_fully_booted) {
582                 nanosleep(&ts, NULL);
583         }
584
585         if (inotify_fd < 0) {
586                 ast_log(LOG_ERROR, "Unable to initialize "
587 #ifdef HAVE_INOTIFY
588                         "inotify(7)"
589 #else
590                         "kqueue(2)"
591 #endif
592                         "\n");
593                 return NULL;
594         }
595
596 #ifdef HAVE_INOTIFY
597         inotify_add_watch(inotify_fd, qdir, IN_CREATE | IN_CLOSE_WRITE | IN_MOVED_TO);
598 #endif
599
600         /* First, run through the directory and clear existing entries */
601         if (!(dir = opendir(qdir))) {
602                 ast_log(LOG_ERROR, "Unable to open directory %s: %s\n", qdir, strerror(errno));
603                 return NULL;
604         }
605
606 #ifndef HAVE_INOTIFY
607         EV_SET(&kev, dirfd(dir), EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE, 0, NULL);
608         if (kevent(inotify_fd, &kev, 1, NULL, 0, &nowait) < 0 && errno != 0) {
609                 ast_log(LOG_ERROR, "Unable to watch directory %s: %s\n", qdir, strerror(errno));
610         }
611 #endif
612         now = time(NULL);
613         while ((de = readdir(dir))) {
614                 queue_file(de->d_name, 0);
615         }
616
617 #ifdef HAVE_INOTIFY
618         /* Directory needs to remain open for kqueue(2) */
619         closedir(dir);
620 #endif
621
622         /* Wait for either a) next timestamp to occur, or b) a change to happen */
623         for (;/* ever */;) {
624                 time_t next = AST_LIST_EMPTY(&dirlist) ? INT_MAX : AST_LIST_FIRST(&dirlist)->mtime;
625
626                 time(&now);
627                 if (next > now) {
628 #ifdef HAVE_INOTIFY
629                         int stage = 0;
630                         /* Convert from seconds to milliseconds, unless there's nothing
631                          * in the queue already, in which case, we wait forever. */
632                         int waittime = next == INT_MAX ? -1 : (next - now) * 1000;
633                         /* When a file arrives, add it to the queue, in mtime order. */
634                         if ((res = poll(&pfd, 1, waittime)) > 0 && (stage = 1) &&
635                                 (res = read(inotify_fd, &buf, sizeof(buf))) >= sizeof(*iev)) {
636                                 ssize_t len = 0;
637                                 /* File(s) added to directory, add them to my list */
638                                 for (iev = (void *) buf; res >= sizeof(*iev); iev = (struct inotify_event *) (((char *) iev) + len)) {
639                                         if (iev->mask & IN_CREATE) {
640                                                 queue_file_create(iev->name);
641                                         } else if (iev->mask & IN_CLOSE_WRITE) {
642                                                 queue_file_write(iev->name);
643                                         } else if (iev->mask & IN_MOVED_TO) {
644                                                 queue_file(iev->name, 0);
645                                         } else {
646                                                 ast_log(LOG_ERROR, "Unexpected event %d for file '%s'\n", (int) iev->mask, iev->name);
647                                         }
648
649                                         len = sizeof(*iev) + iev->len;
650                                         res -= len;
651                                 }
652                         } else if (res < 0 && errno != EINTR && errno != EAGAIN) {
653                                 ast_debug(1, "Got an error back from %s(2): %s\n", stage ? "read" : "poll", strerror(errno));
654                         }
655 #else
656                         struct timespec ts2 = { next - now, 0 };
657                         if (kevent(inotify_fd, NULL, 0, &kev, 1, &ts2) <= 0) {
658                                 /* Interrupt or timeout, restart calculations */
659                                 continue;
660                         } else {
661                                 /* Directory changed, rescan */
662                                 rewinddir(dir);
663                                 while ((de = readdir(dir))) {
664                                         queue_file(de->d_name, 0);
665                                 }
666                         }
667 #endif
668                         time(&now);
669                 }
670
671                 /* Empty the list of all entries ready to be processed */
672                 AST_LIST_LOCK(&dirlist);
673                 while (!AST_LIST_EMPTY(&dirlist) && AST_LIST_FIRST(&dirlist)->mtime <= now) {
674                         cur = AST_LIST_REMOVE_HEAD(&dirlist, list);
675                         queue_file(cur->name, cur->mtime);
676                         ast_free(cur);
677                 }
678                 AST_LIST_UNLOCK(&dirlist);
679         }
680         return NULL;
681 }
682
683 #else
684 static void *scan_thread(void *unused)
685 {
686         struct stat st;
687         DIR *dir;
688         struct dirent *de;
689         char fn[256];
690         int res;
691         time_t last = 0, next = 0, now;
692         struct timespec ts = { .tv_sec = 1 };
693
694         while (!ast_fully_booted) {
695                 nanosleep(&ts, NULL);
696         }
697
698         for(;;) {
699                 /* Wait a sec */
700                 nanosleep(&ts, NULL);
701                 time(&now);
702
703                 if (stat(qdir, &st)) {
704                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
705                         continue;
706                 }
707
708                 /* Make sure it is time for us to execute our check */
709                 if ((st.st_mtime == last) && (next && (next > now)))
710                         continue;
711
712 #if 0
713                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
714                 printf("Ooh, something changed / timeout\n");
715 #endif
716                 next = 0;
717                 last = st.st_mtime;
718
719                 if (!(dir = opendir(qdir))) {
720                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
721                         continue;
722                 }
723
724                 while ((de = readdir(dir))) {
725                         snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
726                         if (stat(fn, &st)) {
727                                 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
728                                 continue;
729                         }
730                         if (!S_ISREG(st.st_mode))
731                                 continue;
732                         if (st.st_mtime <= now) {
733                                 res = scan_service(fn, now);
734                                 if (res > 0) {
735                                         /* Update next service time */
736                                         if (!next || (res < next)) {
737                                                 next = res;
738                                         }
739                                 } else if (res) {
740                                         ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
741                                 } else if (!next) {
742                                         /* Expired entry: must recheck on the next go-around */
743                                         next = st.st_mtime;
744                                 }
745                         } else {
746                                 /* Update "next" update if necessary */
747                                 if (!next || (st.st_mtime < next))
748                                         next = st.st_mtime;
749                         }
750                 }
751                 closedir(dir);
752         }
753         return NULL;
754 }
755 #endif
756
757 static int unload_module(void)
758 {
759         return -1;
760 }
761
762 static int load_module(void)
763 {
764         pthread_t thread;
765         int ret;
766         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
767         if (ast_mkdir(qdir, 0777)) {
768                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
769                 return AST_MODULE_LOAD_DECLINE;
770         }
771         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
772
773         if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
774                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
775                 return AST_MODULE_LOAD_FAILURE;
776         }
777
778         return AST_MODULE_LOAD_SUCCESS;
779 }
780
781 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");