0dad6060de6501a835bbc7d53072ff6a424a3768
[asterisk/asterisk.git] / pbx / pbx_spool.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2010, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Full-featured outgoing call spool support
22  * 
23  */
24
25 /*** MODULEINFO
26         <support_level>core</support_level>
27  ***/
28
29 #include "asterisk.h"
30
31 ASTERISK_REGISTER_FILE()
32
33 #include <sys/stat.h>
34 #include <time.h>
35 #include <utime.h>
36 #include <dirent.h>
37 #ifdef HAVE_INOTIFY
38 #include <sys/inotify.h>
39 #elif defined(HAVE_KQUEUE)
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/event.h>
43 #include <fcntl.h>
44 #endif
45
46 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
47 #include "asterisk/lock.h"
48 #include "asterisk/file.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/callerid.h"
52 #include "asterisk/pbx.h"
53 #include "asterisk/module.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/options.h"
56 #include "asterisk/format.h"
57 #include "asterisk/format_cache.h"
58
59 /*
60  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
61  * The spool file contains a header 
62  */
63
64 enum {
65         /*! Always delete the call file after a call succeeds or the
66          * maximum number of retries is exceeded, even if the
67          * modification time of the call file is in the future.
68          */
69         SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
70         /* Don't unlink the call file after processing, move in qdonedir */
71         SPOOL_FLAG_ARCHIVE = (1 << 1),
72         /* Connect the channel with the outgoing extension once early media is received */
73         SPOOL_FLAG_EARLY_MEDIA = (1 << 2),
74 };
75
76 static char qdir[255];
77 static char qdonedir[255];
78
79 struct outgoing {
80         int retries;                              /*!< Current number of retries */
81         int maxretries;                           /*!< Maximum number of retries permitted */
82         int retrytime;                            /*!< How long to wait between retries (in seconds) */
83         int waittime;                             /*!< How long to wait for an answer */
84         long callingpid;                          /*!< PID which is currently calling */
85         struct ast_format_cap *capabilities;                 /*!< Formats (codecs) for this call */
86         AST_DECLARE_STRING_FIELDS (
87                 AST_STRING_FIELD(fn);                 /*!< File name of call file */
88                 AST_STRING_FIELD(tech);               /*!< Which channel technology to use for outgoing call */
89                 AST_STRING_FIELD(dest);               /*!< Which device/line to use for outgoing call */
90                 AST_STRING_FIELD(app);                /*!< If application: Application name */
91                 AST_STRING_FIELD(data);               /*!< If application: Application data */
92                 AST_STRING_FIELD(exten);              /*!< If extension/context/priority: Extension in dialplan */
93                 AST_STRING_FIELD(context);            /*!< If extension/context/priority: Dialplan context */
94                 AST_STRING_FIELD(cid_num);            /*!< CallerID Information: Number/extension */
95                 AST_STRING_FIELD(cid_name);           /*!< CallerID Information: Name */
96                 AST_STRING_FIELD(account);            /*!< account code */
97         );
98         int priority;                             /*!< If extension/context/priority: Dialplan priority */
99         struct ast_variable *vars;                /*!< Variables and Functions */
100         int maxlen;                               /*!< Maximum length of call */
101         struct ast_flags options;                 /*!< options */
102 };
103
104 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
105 static void queue_file(const char *filename, time_t when);
106 #endif
107
108 static void free_outgoing(struct outgoing *o)
109 {
110         if (o->vars) {
111                 ast_variables_destroy(o->vars);
112         }
113         ao2_cleanup(o->capabilities);
114         ast_string_field_free_memory(o);
115         ast_free(o);
116 }
117
118 static struct outgoing *new_outgoing(const char *fn)
119 {
120         struct outgoing *o;
121
122         o = ast_calloc(1, sizeof(*o));
123         if (!o) {
124                 return NULL;
125         }
126
127         /* Initialize the new object. */
128         o->priority = 1;
129         o->retrytime = 300;
130         o->waittime = 45;
131         ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
132         if (ast_string_field_init(o, 128)) {
133                 /*
134                  * No need to call free_outgoing here since the failure was to
135                  * allocate string fields and no variables have been allocated
136                  * yet.
137                  */
138                 ast_free(o);
139                 return NULL;
140         }
141         ast_string_field_set(o, fn, fn);
142         if (ast_strlen_zero(o->fn)) {
143                 /* String field set failed.  Since this string is important we must fail. */
144                 free_outgoing(o);
145                 return NULL;
146         }
147
148         o->capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
149         if (!o->capabilities) {
150                 free_outgoing(o);
151                 return NULL;
152         }
153         ast_format_cap_append(o->capabilities, ast_format_slin, 0);
154
155         return o;
156 }
157
158 static int apply_outgoing(struct outgoing *o, FILE *f)
159 {
160         char buf[256];
161         char *c, *c2;
162         int lineno = 0;
163         struct ast_variable *var, *last = o->vars;
164
165         while (last && last->next) {
166                 last = last->next;
167         }
168
169         while(fgets(buf, sizeof(buf), f)) {
170                 lineno++;
171                 /* Trim comments */
172                 c = buf;
173                 while ((c = strchr(c, '#'))) {
174                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
175                                 *c = '\0';
176                         else
177                                 c++;
178                 }
179
180                 c = buf;
181                 while ((c = strchr(c, ';'))) {
182                         if ((c > buf) && (c[-1] == '\\')) {
183                                 memmove(c - 1, c, strlen(c) + 1);
184                                 c++;
185                         } else {
186                                 *c = '\0';
187                                 break;
188                         }
189                 }
190
191                 /* Trim trailing white space */
192                 ast_trim_blanks(buf);
193                 if (ast_strlen_zero(buf)) {
194                         continue;
195                 }
196                 c = strchr(buf, ':');
197                 if (!c) {
198                         ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, o->fn);
199                         continue;
200                 }
201                 *c = '\0';
202                 c = ast_skip_blanks(c + 1);
203 #if 0
204                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
205 #endif
206                 if (!strcasecmp(buf, "channel")) {
207                         if ((c2 = strchr(c, '/'))) {
208                                 *c2 = '\0';
209                                 c2++;
210                                 ast_string_field_set(o, tech, c);
211                                 ast_string_field_set(o, dest, c2);
212                         } else {
213                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, o->fn);
214                         }
215                 } else if (!strcasecmp(buf, "callerid")) {
216                         char cid_name[80] = {0}, cid_num[80] = {0};
217                         ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
218                         ast_string_field_set(o, cid_num, cid_num);
219                         ast_string_field_set(o, cid_name, cid_name);
220                 } else if (!strcasecmp(buf, "application")) {
221                         ast_string_field_set(o, app, c);
222                 } else if (!strcasecmp(buf, "data")) {
223                         ast_string_field_set(o, data, c);
224                 } else if (!strcasecmp(buf, "maxretries")) {
225                         if (sscanf(c, "%30d", &o->maxretries) != 1) {
226                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, o->fn);
227                                 o->maxretries = 0;
228                         }
229                 } else if (!strcasecmp(buf, "codecs")) {
230                         ast_format_cap_update_by_allow_disallow(o->capabilities, c, 1);
231                 } else if (!strcasecmp(buf, "context")) {
232                         ast_string_field_set(o, context, c);
233                 } else if (!strcasecmp(buf, "extension")) {
234                         ast_string_field_set(o, exten, c);
235                 } else if (!strcasecmp(buf, "priority")) {
236                         if ((sscanf(c, "%30d", &o->priority) != 1) || (o->priority < 1)) {
237                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, o->fn);
238                                 o->priority = 1;
239                         }
240                 } else if (!strcasecmp(buf, "retrytime")) {
241                         if ((sscanf(c, "%30d", &o->retrytime) != 1) || (o->retrytime < 1)) {
242                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, o->fn);
243                                 o->retrytime = 300;
244                         }
245                 } else if (!strcasecmp(buf, "waittime")) {
246                         if ((sscanf(c, "%30d", &o->waittime) != 1) || (o->waittime < 1)) {
247                                 ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, o->fn);
248                                 o->waittime = 45;
249                         }
250                 } else if (!strcasecmp(buf, "retry")) {
251                         o->retries++;
252                 } else if (!strcasecmp(buf, "startretry")) {
253                         if (sscanf(c, "%30ld", &o->callingpid) != 1) {
254                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
255                                 o->callingpid = 0;
256                         }
257                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
258                         o->callingpid = 0;
259                         o->retries++;
260                 } else if (!strcasecmp(buf, "delayedretry")) {
261                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
262                         c2 = c;
263                         strsep(&c2, "=");
264                         if (c2) {
265                                 var = ast_variable_new(c, c2, o->fn);
266                                 if (var) {
267                                         /* Always insert at the end, because some people want to treat the spool file as a script */
268                                         if (last) {
269                                                 last->next = var;
270                                         } else {
271                                                 o->vars = var;
272                                         }
273                                         last = var;
274                                 }
275                         } else
276                                 ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
277                 } else if (!strcasecmp(buf, "account")) {
278                         ast_string_field_set(o, account, c);
279                 } else if (!strcasecmp(buf, "alwaysdelete")) {
280                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
281                 } else if (!strcasecmp(buf, "archive")) {
282                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
283                 } else if (!strcasecmp(buf, "early_media")) {
284                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_EARLY_MEDIA);
285                 } else {
286                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, o->fn);
287                 }
288         }
289         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
290                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", o->fn);
291                 return -1;
292         }
293         return 0;
294 }
295
296 static void safe_append(struct outgoing *o, time_t now, char *s)
297 {
298         FILE *f;
299         struct utimbuf tbuf = { .actime = now, .modtime = now + o->retrytime };
300
301         ast_debug(1, "Outgoing %s/%s: %s\n", o->tech, o->dest, s);
302
303         if ((f = fopen(o->fn, "a"))) {
304                 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
305                 fclose(f);
306         }
307
308         /* Update the file time */
309         if (utime(o->fn, &tbuf)) {
310                 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
311         }
312 }
313
314 /*!
315  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
316  *
317  * \param o the pointer to outgoing struct
318  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
319  */
320 static int remove_from_queue(struct outgoing *o, const char *status)
321 {
322         FILE *f;
323         char newfn[256];
324         const char *bname;
325
326         if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
327                 struct stat current_file_status;
328
329                 if (!stat(o->fn, &current_file_status)) {
330                         if (time(NULL) < current_file_status.st_mtime) {
331                                 return 0;
332                         }
333                 }
334         }
335
336         if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
337                 unlink(o->fn);
338                 return 0;
339         }
340
341         if (ast_mkdir(qdonedir, 0777)) {
342                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
343                 unlink(o->fn);
344                 return -1;
345         }
346
347         if (!(bname = strrchr(o->fn, '/'))) {
348                 bname = o->fn;
349         } else {
350                 bname++;
351         }
352
353         snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
354         /* If there is already a call file with the name in the archive dir, it will be overwritten. */
355         unlink(newfn);
356         if (rename(o->fn, newfn) != 0) {
357                 unlink(o->fn);
358                 return -1;
359         }
360
361         /* Only append to the file AFTER we move it out of the watched directory,
362          * otherwise the fclose() causes another event for inotify(7) */
363         if ((f = fopen(newfn, "a"))) {
364                 fprintf(f, "Status: %s\n", status);
365                 fclose(f);
366         }
367
368         return 0;
369 }
370
371 static void *attempt_thread(void *data)
372 {
373         struct outgoing *o = data;
374         int res, reason;
375         if (!ast_strlen_zero(o->app)) {
376                 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);
377                 res = ast_pbx_outgoing_app(o->tech, o->capabilities, o->dest, o->waittime * 1000,
378                         o->app, o->data, &reason, 2 /* wait to finish */, o->cid_num, o->cid_name,
379                         o->vars, o->account, NULL, NULL);
380         } else {
381                 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);
382                 res = ast_pbx_outgoing_exten(o->tech, o->capabilities, o->dest,
383                         o->waittime * 1000, o->context, o->exten, o->priority, &reason,
384                         2 /* wait to finish */, o->cid_num, o->cid_name, o->vars, o->account, NULL,
385                         ast_test_flag(&o->options, SPOOL_FLAG_EARLY_MEDIA), NULL);
386         }
387         if (res) {
388                 ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
389                 if (o->retries >= o->maxretries + 1) {
390                         /* Max retries exceeded */
391                         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" : "");
392                         remove_from_queue(o, "Expired");
393                 } else {
394                         /* Notate that the call is still active */
395                         safe_append(o, time(NULL), "EndRetry");
396 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
397                         queue_file(o->fn, time(NULL) + o->retrytime);
398 #endif
399                 }
400         } else {
401                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
402                 remove_from_queue(o, "Completed");
403         }
404         free_outgoing(o);
405         return NULL;
406 }
407
408 static void launch_service(struct outgoing *o)
409 {
410         pthread_t t;
411         int ret;
412
413         if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
414                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
415                 free_outgoing(o);
416         }
417 }
418
419 /* Called from scan_thread or queue_file */
420 static int scan_service(const char *fn, time_t now)
421 {
422         struct outgoing *o;
423         FILE *f;
424         int res;
425
426         o = new_outgoing(fn);
427         if (!o) {
428                 return -1;
429         }
430
431         /* Attempt to open the file */
432         f = fopen(o->fn, "r");
433         if (!f) {
434 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
435                 /*!
436                  * \todo XXX There is some odd delayed duplicate servicing of
437                  * call files going on.  We need to suppress the error message
438                  * if the file does not exist as a result.
439                  */
440                 if (errno != ENOENT)
441 #endif
442                 {
443                         ast_log(LOG_WARNING, "Unable to open %s: '%s'(%d), deleting\n",
444                                 o->fn, strerror(errno), (int) errno);
445                 }
446                 remove_from_queue(o, "Failed");
447                 free_outgoing(o);
448                 return -1;
449         }
450
451         /* Read in and verify the contents */
452         res = apply_outgoing(o, f);
453         fclose(f);
454         if (res) {
455                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", o->fn);
456                 remove_from_queue(o, "Failed");
457                 free_outgoing(o);
458                 return -1;
459         }
460
461         ast_debug(1, "Filename: %s, Retries: %d, max: %d\n", o->fn, o->retries, o->maxretries);
462         if (o->retries <= o->maxretries) {
463                 now += o->retrytime;
464                 if (o->callingpid && (o->callingpid == ast_mainpid)) {
465                         safe_append(o, time(NULL), "DelayedRetry");
466                         ast_debug(1, "Delaying retry since we're currently running '%s'\n", o->fn);
467                         free_outgoing(o);
468                 } else {
469                         /* Increment retries */
470                         o->retries++;
471                         /* If someone else was calling, they're presumably gone now
472                            so abort their retry and continue as we were... */
473                         if (o->callingpid)
474                                 safe_append(o, time(NULL), "AbortRetry");
475
476                         safe_append(o, now, "StartRetry");
477                         launch_service(o);
478                 }
479                 return now;
480         }
481
482         ast_log(LOG_NOTICE, "Queued call to %s/%s expired without completion after %d attempt%s\n",
483                 o->tech, o->dest, o->retries - 1, ((o->retries - 1) != 1) ? "s" : "");
484         remove_from_queue(o, "Expired");
485         free_outgoing(o);
486         return 0;
487 }
488
489 #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
490 struct direntry {
491         AST_LIST_ENTRY(direntry) list;
492         time_t mtime;
493         char name[0];
494 };
495
496 static AST_LIST_HEAD_STATIC(dirlist, direntry);
497
498 #if defined(HAVE_INOTIFY)
499 /* Only one thread is accessing this list, so no lock is necessary */
500 static AST_LIST_HEAD_NOLOCK_STATIC(createlist, direntry);
501 static AST_LIST_HEAD_NOLOCK_STATIC(openlist, direntry);
502 #endif
503
504 static void queue_file(const char *filename, time_t when)
505 {
506         struct stat st;
507         struct direntry *cur, *new;
508         int res;
509         time_t now = time(NULL);
510
511         if (!strchr(filename, '/')) {
512                 char *fn = ast_alloca(strlen(qdir) + strlen(filename) + 2);
513                 sprintf(fn, "%s/%s", qdir, filename); /* SAFE */
514                 filename = fn;
515         }
516
517         if (when == 0) {
518                 if (stat(filename, &st)) {
519                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", filename, strerror(errno));
520                         return;
521                 }
522
523                 if (!S_ISREG(st.st_mode)) {
524                         return;
525                 }
526
527                 when = st.st_mtime;
528         }
529
530         /* Need to check the existing list in order to avoid duplicates. */
531         AST_LIST_LOCK(&dirlist);
532         AST_LIST_TRAVERSE(&dirlist, cur, list) {
533                 if (cur->mtime == when && !strcmp(filename, cur->name)) {
534                         AST_LIST_UNLOCK(&dirlist);
535                         return;
536                 }
537         }
538
539         if ((res = when) > now || (res = scan_service(filename, now)) > 0) {
540                 if (!(new = ast_calloc(1, sizeof(*new) + strlen(filename) + 1))) {
541                         AST_LIST_UNLOCK(&dirlist);
542                         return;
543                 }
544                 new->mtime = res;
545                 strcpy(new->name, filename);
546                 /* List is ordered by mtime */
547                 if (AST_LIST_EMPTY(&dirlist)) {
548                         AST_LIST_INSERT_HEAD(&dirlist, new, list);
549                 } else {
550                         int found = 0;
551                         AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
552                                 if (cur->mtime > new->mtime) {
553                                         AST_LIST_INSERT_BEFORE_CURRENT(new, list);
554                                         found = 1;
555                                         break;
556                                 }
557                         }
558                         AST_LIST_TRAVERSE_SAFE_END
559                         if (!found) {
560                                 AST_LIST_INSERT_TAIL(&dirlist, new, list);
561                         }
562                 }
563         }
564         AST_LIST_UNLOCK(&dirlist);
565 }
566
567 #ifdef HAVE_INOTIFY
568 static void queue_file_create(const char *filename)
569 {
570         struct direntry *cur;
571
572         AST_LIST_TRAVERSE(&createlist, cur, list) {
573                 if (!strcmp(cur->name, filename)) {
574                         return;
575                 }
576         }
577
578         if (!(cur = ast_calloc(1, sizeof(*cur) + strlen(filename) + 1))) {
579                 return;
580         }
581         strcpy(cur->name, filename);
582         /* We'll handle this file unless an IN_OPEN event occurs within 2 seconds */
583         cur->mtime = time(NULL) + 2;
584         AST_LIST_INSERT_TAIL(&createlist, cur, list);
585 }
586
587 static void queue_file_open(const char *filename)
588 {
589         struct direntry *cur;
590
591         AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
592                 if (!strcmp(cur->name, filename)) {
593                         AST_LIST_REMOVE_CURRENT(list);
594                         AST_LIST_INSERT_TAIL(&openlist, cur, list);
595                         break;
596                 }
597         }
598         AST_LIST_TRAVERSE_SAFE_END
599 }
600
601 static void queue_created_files(void)
602 {
603         struct direntry *cur;
604         time_t now = time(NULL);
605
606         AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
607                 if (cur->mtime > now) {
608                         break;
609                 }
610
611                 AST_LIST_REMOVE_CURRENT(list);
612                 queue_file(cur->name, 0);
613                 ast_free(cur);
614         }
615         AST_LIST_TRAVERSE_SAFE_END
616 }
617
618 static void queue_file_write(const char *filename)
619 {
620         struct direntry *cur;
621         /* Only queue entries where an IN_CREATE preceded the IN_CLOSE_WRITE */
622         AST_LIST_TRAVERSE_SAFE_BEGIN(&openlist, cur, list) {
623                 if (!strcmp(cur->name, filename)) {
624                         AST_LIST_REMOVE_CURRENT(list);
625                         ast_free(cur);
626                         queue_file(filename, 0);
627                         break;
628                 }
629         }
630         AST_LIST_TRAVERSE_SAFE_END
631 }
632 #endif
633
634 static void *scan_thread(void *unused)
635 {
636         DIR *dir;
637         struct dirent *de;
638         time_t now;
639         struct timespec ts = { .tv_sec = 1 };
640 #ifdef HAVE_INOTIFY
641         ssize_t res;
642         int inotify_fd = inotify_init();
643         struct inotify_event *iev;
644         char buf[8192] __attribute__((aligned (sizeof(int))));
645         struct pollfd pfd = { .fd = inotify_fd, .events = POLLIN };
646 #else
647         struct timespec nowait = { .tv_sec = 0, .tv_nsec = 1 };
648         int inotify_fd = kqueue();
649         struct kevent kev;
650         struct kevent event;
651 #endif
652         struct direntry *cur;
653
654         while (!ast_fully_booted) {
655                 nanosleep(&ts, NULL);
656         }
657
658         if (inotify_fd < 0) {
659                 ast_log(LOG_ERROR, "Unable to initialize "
660 #ifdef HAVE_INOTIFY
661                         "inotify(7)"
662 #else
663                         "kqueue(2)"
664 #endif
665                         "\n");
666                 return NULL;
667         }
668
669 #ifdef HAVE_INOTIFY
670         inotify_add_watch(inotify_fd, qdir, IN_CREATE | IN_OPEN | IN_CLOSE_WRITE | IN_MOVED_TO);
671 #endif
672
673         /* First, run through the directory and clear existing entries */
674         if (!(dir = opendir(qdir))) {
675                 ast_log(LOG_ERROR, "Unable to open directory %s: %s\n", qdir, strerror(errno));
676                 return NULL;
677         }
678
679 #ifndef HAVE_INOTIFY
680         EV_SET(&kev, dirfd(dir), EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE, 0, NULL);
681         if (kevent(inotify_fd, &kev, 1, &event, 1, &nowait) < 0 && errno != 0) {
682                 ast_log(LOG_ERROR, "Unable to watch directory %s: %s\n", qdir, strerror(errno));
683         }
684 #endif
685         now = time(NULL);
686         while ((de = readdir(dir))) {
687                 queue_file(de->d_name, 0);
688         }
689
690 #ifdef HAVE_INOTIFY
691         /* Directory needs to remain open for kqueue(2) */
692         closedir(dir);
693 #endif
694
695         /* Wait for either a) next timestamp to occur, or b) a change to happen */
696         for (;/* ever */;) {
697                 time_t next = AST_LIST_EMPTY(&dirlist) ? INT_MAX : AST_LIST_FIRST(&dirlist)->mtime;
698
699                 time(&now);
700                 if (next > now) {
701 #ifdef HAVE_INOTIFY
702                         int stage = 0;
703                         /* Convert from seconds to milliseconds, unless there's nothing
704                          * in the queue already, in which case, we wait forever. */
705                         int waittime = next == INT_MAX ? -1 : (next - now) * 1000;
706                         if (!AST_LIST_EMPTY(&createlist)) {
707                                 waittime = 1000;
708                         }
709                         /* When a file arrives, add it to the queue, in mtime order. */
710                         if ((res = poll(&pfd, 1, waittime)) > 0 && (stage = 1) &&
711                                 (res = read(inotify_fd, &buf, sizeof(buf))) >= sizeof(*iev)) {
712                                 ssize_t len = 0;
713                                 /* File(s) added to directory, add them to my list */
714                                 for (iev = (void *) buf; res >= sizeof(*iev); iev = (struct inotify_event *) (((char *) iev) + len)) {
715                                         /* For an IN_MOVED_TO event, simply process the file. However, if
716                                          * we get an IN_CREATE event it *might* be an open(O_CREAT) or it
717                                          * might be a hardlink (like smsq does, since rename() might
718                                          * overwrite an existing file). So we have to see if we get a
719                                          * subsequent IN_OPEN event on the same file. If we do, keep it
720                                          * on the openlist and wait for the corresponding IN_CLOSE_WRITE.
721                                          * If we *don't* see an IN_OPEN event, then it was a hard link so
722                                          * it can be processed immediately.
723                                          *
724                                          * Unfortunately, although open(O_CREAT) is an atomic file system
725                                          * operation, the inotify subsystem doesn't give it to us in a
726                                          * single event with both IN_CREATE|IN_OPEN set. It's two separate
727                                          * events, and the kernel doesn't even give them to us at the same
728                                          * time. We can read() from inotify_fd after the IN_CREATE event,
729                                          * and get *nothing* from it. The IN_OPEN arrives only later! So
730                                          * we have a very short timeout of 2 seconds. */
731                                         if (iev->mask & IN_CREATE) {
732                                                 queue_file_create(iev->name);
733                                         } else if (iev->mask & IN_OPEN) {
734                                                 queue_file_open(iev->name);
735                                         } else if (iev->mask & IN_CLOSE_WRITE) {
736                                                 queue_file_write(iev->name);
737                                         } else if (iev->mask & IN_MOVED_TO) {
738                                                 queue_file(iev->name, 0);
739                                         } else {
740                                                 ast_log(LOG_ERROR, "Unexpected event %d for file '%s'\n", (int) iev->mask, iev->name);
741                                         }
742
743                                         len = sizeof(*iev) + iev->len;
744                                         res -= len;
745                                 }
746                         } else if (res < 0 && errno != EINTR && errno != EAGAIN) {
747                                 ast_debug(1, "Got an error back from %s(2): %s\n", stage ? "read" : "poll", strerror(errno));
748                         }
749                         time(&now);
750                 }
751                 queue_created_files();
752 #else
753                         int num_events;
754                         /* If queue empty then wait forever */
755                         if (next == INT_MAX) {
756                                 num_events = kevent(inotify_fd, &kev, 1, &event, 1, NULL);
757                         } else {
758                                 struct timespec ts2 = { .tv_sec = (unsigned long int)(next - now), .tv_nsec = 0 };
759                                 num_events = kevent(inotify_fd, &kev, 1, &event, 1, &ts2);
760                         }
761                         if ((num_events < 0) || (event.flags == EV_ERROR)) {
762                                 ast_debug(10, "KEvent error %s\n", strerror(errno));
763                                 continue;
764                         } else if (num_events == 0) {
765                                 /* Interrupt or timeout, restart calculations */
766                                 continue;
767                         } else {
768                                 /* Directory changed, rescan */
769                                 rewinddir(dir);
770                                 while ((de = readdir(dir))) {
771                                         queue_file(de->d_name, 0);
772                                 }
773                         }
774                         time(&now);
775                 }
776 #endif
777
778                 /* Empty the list of all entries ready to be processed */
779                 AST_LIST_LOCK(&dirlist);
780                 while (!AST_LIST_EMPTY(&dirlist) && AST_LIST_FIRST(&dirlist)->mtime <= now) {
781                         cur = AST_LIST_REMOVE_HEAD(&dirlist, list);
782                         queue_file(cur->name, cur->mtime);
783                         ast_free(cur);
784                 }
785                 AST_LIST_UNLOCK(&dirlist);
786         }
787         return NULL;
788 }
789
790 #else
791 static void *scan_thread(void *unused)
792 {
793         struct stat st;
794         DIR *dir;
795         struct dirent *de;
796         char fn[256];
797         int res;
798         int force_poll = 1;
799         time_t last = 0;
800         time_t next = 0;
801         time_t now;
802         struct timespec ts = { .tv_sec = 1 };
803
804         while (!ast_fully_booted) {
805                 nanosleep(&ts, NULL);
806         }
807
808         for (;;) {
809                 /* Wait a sec */
810                 nanosleep(&ts, NULL);
811                 time(&now);
812
813                 if (stat(qdir, &st)) {
814                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
815                         continue;
816                 }
817
818                 /* Make sure it is time for us to execute our check */
819                 if (!force_poll && st.st_mtime == last && (!next || now < next)) {
820                         /*
821                          * The directory timestamp did not change and any delayed
822                          * call-file is not ready to be executed.
823                          */
824                         continue;
825                 }
826
827 #if 0
828                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
829                 printf("Ooh, something changed / timeout\n");
830 #endif
831
832                 if (!(dir = opendir(qdir))) {
833                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
834                         continue;
835                 }
836
837                 /*
838                  * Since the dir timestamp is available at one second
839                  * resolution, we cannot know if it was updated within the same
840                  * second after we scanned it.  Therefore, we will force another
841                  * scan if the dir was just modified.
842                  */
843                 force_poll = (st.st_mtime == now);
844
845                 next = 0;
846                 last = st.st_mtime;
847                 while ((de = readdir(dir))) {
848                         snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
849                         if (stat(fn, &st)) {
850                                 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
851                                 continue;
852                         }
853                         if (!S_ISREG(st.st_mode)) {
854                                 /* Not a regular file. */
855                                 continue;
856                         }
857                         if (st.st_mtime <= now) {
858                                 res = scan_service(fn, now);
859                                 if (res > 0) {
860                                         /* The call-file is delayed or to be retried later. */
861                                         if (!next || res < next) {
862                                                 /* This delayed call file expires earlier. */
863                                                 next = res;
864                                         }
865                                 } else if (res) {
866                                         ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
867                                 } else if (!next) {
868                                         /* Expired entry: must recheck on the next go-around */
869                                         next = st.st_mtime;
870                                 }
871                         } else {
872                                 /* The file's timestamp is in the future. */
873                                 if (!next || st.st_mtime < next) {
874                                         /* This call-file's timestamp expires earlier. */
875                                         next = st.st_mtime;
876                                 }
877                         }
878                 }
879                 closedir(dir);
880         }
881         return NULL;
882 }
883 #endif
884
885 static int unload_module(void)
886 {
887         return -1;
888 }
889
890 static int load_module(void)
891 {
892         pthread_t thread;
893         int ret;
894         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
895         if (ast_mkdir(qdir, 0777)) {
896                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
897                 return AST_MODULE_LOAD_DECLINE;
898         }
899         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
900
901         if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
902                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
903                 return AST_MODULE_LOAD_FAILURE;
904         }
905
906         return AST_MODULE_LOAD_SUCCESS;
907 }
908
909 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");