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