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