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