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