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