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