Convert pbx_spool to use string fields instead of statically-sized buffers.
[asterisk/asterisk.git] / pbx / pbx_spool.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, 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
34 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
35 #include "asterisk/lock.h"
36 #include "asterisk/file.h"
37 #include "asterisk/logger.h"
38 #include "asterisk/channel.h"
39 #include "asterisk/callerid.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/module.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/options.h"
44
45 /*
46  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
47  * The spool file contains a header 
48  */
49
50 enum {
51         /*! Always delete the call file after a call succeeds or the
52          * maximum number of retries is exceeded, even if the
53          * modification time of the call file is in the future.
54          */
55         SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
56         /* Don't unlink the call file after processing, move in qdonedir */
57         SPOOL_FLAG_ARCHIVE = (1 << 1)
58 };
59
60 static char qdir[255];
61 static char qdonedir[255];
62
63 struct outgoing {
64         int retries;                              /*!< Current number of retries */
65         int maxretries;                           /*!< Maximum number of retries permitted */
66         int retrytime;                            /*!< How long to wait between retries (in seconds) */
67         int waittime;                             /*!< How long to wait for an answer */
68         long callingpid;                          /*!< PID which is currently calling */
69         int format;                               /*!< Formats (codecs) for this call */
70         AST_DECLARE_STRING_FIELDS (
71                 AST_STRING_FIELD(fn);                 /*!< File name of call file */
72                 AST_STRING_FIELD(tech);               /*!< Which channel technology to use for outgoing call */
73                 AST_STRING_FIELD(dest);               /*!< Which device/line to use for outgoing call */
74                 AST_STRING_FIELD(app);                /*!< If application: Application name */
75                 AST_STRING_FIELD(data);               /*!< If application: Application data */
76                 AST_STRING_FIELD(exten);              /*!< If extension/context/priority: Extension in dialplan */
77                 AST_STRING_FIELD(context);            /*!< If extension/context/priority: Dialplan context */
78                 AST_STRING_FIELD(cid_num);            /*!< CallerID Information: Number/extension */
79                 AST_STRING_FIELD(cid_name);           /*!< CallerID Information: Name */
80                 AST_STRING_FIELD(account);            /*!< account code */
81         );
82         int priority;                             /*!< If extension/context/priority: Dialplan priority */
83         struct ast_variable *vars;                /*!< Variables and Functions */
84         int maxlen;                               /*!< Maximum length of call */
85         struct ast_flags options;                 /*!< options */
86 };
87
88 static int init_outgoing(struct outgoing *o)
89 {
90         o->priority = 1;
91         o->retrytime = 300;
92         o->waittime = 45;
93         o->format = AST_FORMAT_SLINEAR;
94         ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
95         if (ast_string_field_init(o, 128)) {
96                 return -1;
97         }
98         return 0;
99 }
100
101 static void free_outgoing(struct outgoing *o)
102 {
103         if (o->vars) {
104                 ast_variables_destroy(o->vars);
105         }
106         ast_string_field_free_memory(o);
107         ast_free(o);
108 }
109
110 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
111 {
112         char buf[256];
113         char *c, *c2;
114         int lineno = 0;
115         struct ast_variable *var, *last = o->vars;
116
117         while (last && last->next) {
118                 last = last->next;
119         }
120
121         while(fgets(buf, sizeof(buf), f)) {
122                 lineno++;
123                 /* Trim comments */
124                 c = buf;
125                 while ((c = strchr(c, '#'))) {
126                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
127                                 *c = '\0';
128                         else
129                                 c++;
130                 }
131
132                 c = buf;
133                 while ((c = strchr(c, ';'))) {
134                         if ((c > buf) && (c[-1] == '\\')) {
135                                 memmove(c - 1, c, strlen(c) + 1);
136                                 c++;
137                         } else {
138                                 *c = '\0';
139                                 break;
140                         }
141                 }
142
143                 /* Trim trailing white space */
144                 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
145                         buf[strlen(buf) - 1] = '\0';
146                 if (!ast_strlen_zero(buf)) {
147                         c = strchr(buf, ':');
148                         if (c) {
149                                 *c = '\0';
150                                 c++;
151                                 while ((*c) && (*c < 33))
152                                         c++;
153 #if 0
154                                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
155 #endif
156                                 if (!strcasecmp(buf, "channel")) {
157                                         if ((c2 = strchr(c, '/'))) {
158                                                 *c2 = '\0';
159                                                 c2++;
160                                                 ast_string_field_set(o, tech, c);
161                                                 ast_string_field_set(o, dest, c2);
162                                         } else {
163                                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
164                                         }
165                                 } else if (!strcasecmp(buf, "callerid")) {
166                                         char cid_name[80] = {0}, cid_num[80] = {0};
167                                         ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
168                                         ast_string_field_set(o, cid_num, cid_num);
169                                         ast_string_field_set(o, cid_name, cid_name);
170                                 } else if (!strcasecmp(buf, "application")) {
171                                         ast_string_field_set(o, app, c);
172                                 } else if (!strcasecmp(buf, "data")) {
173                                         ast_string_field_set(o, data, c);
174                                 } else if (!strcasecmp(buf, "maxretries")) {
175                                         if (sscanf(c, "%d", &o->maxretries) != 1) {
176                                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
177                                                 o->maxretries = 0;
178                                         }
179                                 } else if (!strcasecmp(buf, "codecs")) {
180                                         ast_parse_allow_disallow(NULL, &o->format, c, 1);
181                                 } else if (!strcasecmp(buf, "context")) {
182                                         ast_string_field_set(o, context, c);
183                                 } else if (!strcasecmp(buf, "extension")) {
184                                         ast_string_field_set(o, exten, c);
185                                 } else if (!strcasecmp(buf, "priority")) {
186                                         if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
187                                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
188                                                 o->priority = 1;
189                                         }
190                                 } else if (!strcasecmp(buf, "retrytime")) {
191                                         if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
192                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
193                                                 o->retrytime = 300;
194                                         }
195                                 } else if (!strcasecmp(buf, "waittime")) {
196                                         if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
197                                                 ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
198                                                 o->waittime = 45;
199                                         }
200                                 } else if (!strcasecmp(buf, "retry")) {
201                                         o->retries++;
202                                 } else if (!strcasecmp(buf, "startretry")) {
203                                         if (sscanf(c, "%ld", &o->callingpid) != 1) {
204                                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
205                                                 o->callingpid = 0;
206                                         }
207                                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
208                                         o->callingpid = 0;
209                                         o->retries++;
210                                 } else if (!strcasecmp(buf, "delayedretry")) {
211                                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
212                                         c2 = c;
213                                         strsep(&c2, "=");
214                                         if (c2) {
215                                                 var = ast_variable_new(c, c2, fn);
216                                                 if (var) {
217                                                         /* Always insert at the end, because some people want to treat the spool file as a script */
218                                                         if (last) {
219                                                                 last->next = var;
220                                                         } else {
221                                                                 o->vars = var;
222                                                         }
223                                                         last = var;
224                                                 }
225                                         } else
226                                                 ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
227                                 } else if (!strcasecmp(buf, "account")) {
228                                         ast_string_field_set(o, account, c);
229                                 } else if (!strcasecmp(buf, "alwaysdelete")) {
230                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
231                                 } else if (!strcasecmp(buf, "archive")) {
232                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
233                                 } else {
234                                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
235                                 }
236                         } else
237                                 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
238                 }
239         }
240         ast_string_field_set(o, fn, fn);
241         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
242                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
243                 return -1;
244         }
245         return 0;
246 }
247
248 static void safe_append(struct outgoing *o, time_t now, char *s)
249 {
250         int fd;
251         FILE *f;
252         struct utimbuf tbuf;
253
254         if ((fd = open(o->fn, O_WRONLY | O_APPEND)) < 0)
255                 return;
256
257         if ((f = fdopen(fd, "a"))) {
258                 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
259                 fclose(f);
260         } else
261                 close(fd);
262
263         /* Update the file time */
264         tbuf.actime = now;
265         tbuf.modtime = now + o->retrytime;
266         if (utime(o->fn, &tbuf))
267                 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
268 }
269
270 /*!
271  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
272  *
273  * \param o the pointer to outgoing struct
274  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
275  */
276 static int remove_from_queue(struct outgoing *o, const char *status)
277 {
278         int fd;
279         FILE *f;
280         char newfn[256];
281         const char *bname;
282
283         if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
284                 struct stat current_file_status;
285
286                 if (!stat(o->fn, &current_file_status)) {
287                         if (time(NULL) < current_file_status.st_mtime)
288                                 return 0;
289                 }
290         }
291
292         if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
293                 unlink(o->fn);
294                 return 0;
295         }
296
297         if (ast_mkdir(qdonedir, 0777)) {
298                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
299                 unlink(o->fn);
300                 return -1;
301         }
302
303         if ((fd = open(o->fn, O_WRONLY | O_APPEND))) {
304                 if ((f = fdopen(fd, "a"))) {
305                         fprintf(f, "Status: %s\n", status);
306                         fclose(f);
307                 } else
308                         close(fd);
309         }
310
311         if (!(bname = strrchr(o->fn, '/')))
312                 bname = o->fn;
313         else
314                 bname++;        
315         snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
316         /* a existing call file the archive dir is overwritten */
317         unlink(newfn);
318         if (rename(o->fn, newfn) != 0) {
319                 unlink(o->fn);
320                 return -1;
321         } else
322                 return 0;
323 }
324
325 static void *attempt_thread(void *data)
326 {
327         struct outgoing *o = data;
328         int res, reason;
329         if (!ast_strlen_zero(o->app)) {
330                 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);
331                 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);
332                 o->vars = NULL;
333         } else {
334                 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);
335                 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);
336                 o->vars = NULL;
337         }
338         if (res) {
339                 ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
340                 if (o->retries >= o->maxretries + 1) {
341                         /* Max retries exceeded */
342                         ast_log(LOG_EVENT, "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" : "");
343                         remove_from_queue(o, "Expired");
344                 } else {
345                         /* Notate that the call is still active */
346                         safe_append(o, time(NULL), "EndRetry");
347                 }
348         } else {
349                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
350                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
351                 remove_from_queue(o, "Completed");
352         }
353         free_outgoing(o);
354         return NULL;
355 }
356
357 static void launch_service(struct outgoing *o)
358 {
359         pthread_t t;
360         int ret;
361
362         if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
363                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
364                 free_outgoing(o);
365         }
366 }
367
368 static int scan_service(char *fn, time_t now, time_t atime)
369 {
370         struct outgoing *o = NULL;
371         FILE *f;
372         int res = 0;
373
374         if (!(o = ast_calloc(1, sizeof(*o)))) {
375                 ast_log(LOG_WARNING, "Out of memory ;(\n");
376                 return -1;
377         }
378         
379         if (init_outgoing(o)) {
380                 /* No need to call free_outgoing here since we know the failure
381                  * was to allocate string fields and no variables have been allocated
382                  * yet.
383                  */
384                 ast_free(o);
385                 return -1;
386         }
387
388         /* Attempt to open the file */
389         if (!(f = fopen(fn, "r+"))) {
390                 remove_from_queue(o, "Failed");
391                 free_outgoing(o);
392                 ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
393                 return -1;
394         }
395
396         /* Read in and verify the contents */
397         if (apply_outgoing(o, fn, f)) {
398                 remove_from_queue(o, "Failed");
399                 free_outgoing(o);
400                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
401                 fclose(f);
402                 return -1;
403         }
404         
405 #if 0
406         printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
407 #endif
408         fclose(f);
409         if (o->retries <= o->maxretries) {
410                 now += o->retrytime;
411                 if (o->callingpid && (o->callingpid == ast_mainpid)) {
412                         safe_append(o, time(NULL), "DelayedRetry");
413                         ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
414                         free_outgoing(o);
415                 } else {
416                         /* Increment retries */
417                         o->retries++;
418                         /* If someone else was calling, they're presumably gone now
419                            so abort their retry and continue as we were... */
420                         if (o->callingpid)
421                                 safe_append(o, time(NULL), "AbortRetry");
422                         
423                         safe_append(o, now, "StartRetry");
424                         launch_service(o);
425                 }
426                 res = now;
427         } else {
428                 ast_log(LOG_EVENT, "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" : "");
429                 remove_from_queue(o, "Expired");
430                 free_outgoing(o);
431         }
432
433         return res;
434 }
435
436 static void *scan_thread(void *unused)
437 {
438         struct stat st;
439         DIR *dir;
440         struct dirent *de;
441         char fn[256];
442         int res;
443         time_t last = 0, next = 0, now;
444         struct timespec ts = { .tv_sec = 1 };
445   
446         while (!ast_fully_booted) {
447                 nanosleep(&ts, NULL);
448         }
449
450         for(;;) {
451                 /* Wait a sec */
452                 nanosleep(&ts, NULL);
453                 time(&now);
454
455                 if (stat(qdir, &st)) {
456                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
457                         continue;
458                 }
459
460                 /* Make sure it is time for us to execute our check */
461                 if ((st.st_mtime == last) && (next && (next > now)))
462                         continue;
463                 
464 #if 0
465                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
466                 printf("Ooh, something changed / timeout\n");
467 #endif
468                 next = 0;
469                 last = st.st_mtime;
470
471                 if (!(dir = opendir(qdir))) {
472                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
473                         continue;
474                 }
475
476                 while ((de = readdir(dir))) {
477                         snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
478                         if (stat(fn, &st)) {
479                                 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
480                                 continue;
481                         }
482                         if (!S_ISREG(st.st_mode))
483                                 continue;
484                         if (st.st_mtime <= now) {
485                                 res = scan_service(fn, now, st.st_atime);
486                                 if (res > 0) {
487                                         /* Update next service time */
488                                         if (!next || (res < next)) {
489                                                 next = res;
490                                         }
491                                 } else if (res) {
492                                         ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
493                                 } else if (!next) {
494                                         /* Expired entry: must recheck on the next go-around */
495                                         next = st.st_mtime;
496                                 }
497                         } else {
498                                 /* Update "next" update if necessary */
499                                 if (!next || (st.st_mtime < next))
500                                         next = st.st_mtime;
501                         }
502                 }
503                 closedir(dir);
504         }
505         return NULL;
506 }
507
508 static int unload_module(void)
509 {
510         return -1;
511 }
512
513 static int load_module(void)
514 {
515         pthread_t thread;
516         int ret;
517         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
518         if (ast_mkdir(qdir, 0777)) {
519                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
520                 return AST_MODULE_LOAD_DECLINE;
521         }
522         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
523
524         if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
525                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
526                 return AST_MODULE_LOAD_FAILURE;
527         }
528
529         return AST_MODULE_LOAD_SUCCESS;
530 }
531
532 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");