ec008280bd6070b8de84eaa1b730c08d46508971
[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 <errno.h>
31 #include <time.h>
32 #include <utime.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <dirent.h>
36 #include <string.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <unistd.h>
40
41 #include "asterisk/lock.h"
42 #include "asterisk/file.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/callerid.h"
46 #include "asterisk/pbx.h"
47 #include "asterisk/module.h"
48 #include "asterisk/options.h"
49 #include "asterisk/utils.h"
50
51 /*
52  * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
53  * The spool file contains a header 
54  */
55
56 enum {
57         /*! Always delete the call file after a call succeeds or the
58          * maximum number of retries is exceeded, even if the
59          * modification time of the call file is in the future.
60          */
61         SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
62         /* Don't unlink the call file after processing, move in qdonedir */
63         SPOOL_FLAG_ARCHIVE = (1 << 1)
64 };
65
66 static char qdir[255];
67 static char qdonedir[255];
68
69 struct outgoing {
70         char fn[256];
71         /* Current number of retries */
72         int retries;
73         /* Maximum number of retries permitted */
74         int maxretries;
75         /* How long to wait between retries (in seconds) */
76         int retrytime;
77         /* How long to wait for an answer */
78         int waittime;
79         /* PID which is currently calling */
80         long callingpid;
81         
82         /* What to connect to outgoing */
83         char tech[256];
84         char dest[256];
85         
86         /* If application */
87         char app[256];
88         char data[256];
89
90         /* If extension/context/priority */
91         char exten[256];
92         char context[256];
93         int priority;
94
95         /* CallerID Information */
96         char cid_num[256];
97         char cid_name[256];
98
99         /* account code */
100         char account[AST_MAX_ACCOUNT_CODE];
101
102         /* Variables and Functions */
103         struct ast_variable *vars;
104         
105         /* Maximum length of call */
106         int maxlen;
107
108         /* options */
109         struct ast_flags options;
110 };
111
112 static void init_outgoing(struct outgoing *o)
113 {
114         memset(o, 0, sizeof(struct outgoing));
115         o->priority = 1;
116         o->retrytime = 300;
117         o->waittime = 45;
118         ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
119 }
120
121 static void free_outgoing(struct outgoing *o)
122 {
123         free(o);
124 }
125
126 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
127 {
128         char buf[256];
129         char *c, *c2;
130         int lineno = 0;
131         struct ast_variable *var;
132
133         while(fgets(buf, sizeof(buf), f)) {
134                 lineno++;
135                 /* Trim comments */
136                 c = buf;
137                 while ((c = strchr(c, '#'))) {
138                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
139                                 *c = '\0';
140                         else
141                                 c++;
142                 }
143
144                 c = buf;
145                 while ((c = strchr(c, ';'))) {
146                         if ((c > buf) && (c[-1] == '\\')) {
147                                 memmove(c - 1, c, strlen(c) + 1);
148                                 c++;
149                         } else {
150                                 *c = '\0';
151                                 break;
152                         }
153                 }
154
155                 /* Trim trailing white space */
156                 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
157                         buf[strlen(buf) - 1] = '\0';
158                 if (!ast_strlen_zero(buf)) {
159                         c = strchr(buf, ':');
160                         if (c) {
161                                 *c = '\0';
162                                 c++;
163                                 while ((*c) && (*c < 33))
164                                         c++;
165 #if 0
166                                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
167 #endif
168                                 if (!strcasecmp(buf, "channel")) {
169                                         strncpy(o->tech, c, sizeof(o->tech) - 1);
170                                         if ((c2 = strchr(o->tech, '/'))) {
171                                                 *c2 = '\0';
172                                                 c2++;
173                                                 strncpy(o->dest, c2, sizeof(o->dest) - 1);
174                                         } else {
175                                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
176                                                 o->tech[0] = '\0';
177                                         }
178                                 } else if (!strcasecmp(buf, "callerid")) {
179                                         ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
180                                 } else if (!strcasecmp(buf, "application")) {
181                                         strncpy(o->app, c, sizeof(o->app) - 1);
182                                 } else if (!strcasecmp(buf, "data")) {
183                                         strncpy(o->data, c, sizeof(o->data) - 1);
184                                 } else if (!strcasecmp(buf, "maxretries")) {
185                                         if (sscanf(c, "%d", &o->maxretries) != 1) {
186                                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
187                                                 o->maxretries = 0;
188                                         }
189                                 } else if (!strcasecmp(buf, "context")) {
190                                         strncpy(o->context, c, sizeof(o->context) - 1);
191                                 } else if (!strcasecmp(buf, "extension")) {
192                                         strncpy(o->exten, c, sizeof(o->exten) - 1);
193                                 } else if (!strcasecmp(buf, "priority")) {
194                                         if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
195                                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
196                                                 o->priority = 1;
197                                         }
198                                 } else if (!strcasecmp(buf, "retrytime")) {
199                                         if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
200                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
201                                                 o->retrytime = 300;
202                                         }
203                                 } else if (!strcasecmp(buf, "waittime")) {
204                                         if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
205                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
206                                                 o->waittime = 45;
207                                         }
208                                 } else if (!strcasecmp(buf, "retry")) {
209                                         o->retries++;
210                                 } else if (!strcasecmp(buf, "startretry")) {
211                                         if (sscanf(c, "%ld", &o->callingpid) != 1) {
212                                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
213                                                 o->callingpid = 0;
214                                         }
215                                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
216                                         o->callingpid = 0;
217                                         o->retries++;
218                                 } else if (!strcasecmp(buf, "delayedretry")) {
219                                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
220                                         c2 = c;
221                                         strsep(&c2, "=");
222                                         if (c2) {
223                                                 var = ast_variable_new(c, c2);
224                                                 if (var) {
225                                                         var->next = o->vars;
226                                                         o->vars = 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_copy_string(o->account, c, sizeof(o->account));
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         strncpy(o->fn, fn, sizeof(o->fn) - 1);
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         fd = open(o->fn, O_WRONLY|O_APPEND);
257         if (fd > -1) {
258                 f = fdopen(fd, "a");
259                 if (f) {
260                         fprintf(f, "%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
261                         fclose(f);
262                 } else
263                         close(fd);
264                 /* Update the file time */
265                 tbuf.actime = now;
266                 tbuf.modtime = now + o->retrytime;
267                 if (utime(o->fn, &tbuf))
268                         ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
269         }
270 }
271
272 /*!
273  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
274  *
275  * \param o the pointer to outgoing struct
276  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
277  */
278 static int remove_from_queue(struct outgoing *o, const char *status)
279 {
280         int fd;
281         FILE *f;
282         char newfn[256];
283         const char *bname;
284
285         if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
286                 struct stat current_file_status;
287
288                 if (!stat(o->fn, &current_file_status))
289                         if (time(NULL) < current_file_status.st_mtime)
290                                 return 0;
291         }
292
293         if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
294                 unlink(o->fn);
295                 return 0;
296         }
297         if (mkdir(qdonedir, 0700) && (errno != EEXIST)) {
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         fd = open(o->fn, O_WRONLY|O_APPEND);
303         if (fd > -1) {
304                 f = fdopen(fd, "a");
305                 if (f) {
306                         fprintf(f, "Status: %s\n", status);
307                         fclose(f);
308                 } else
309                         close(fd);
310         }
311
312         bname = strrchr(o->fn,'/');
313         if (bname == NULL) 
314                 bname = o->fn;
315         else 
316                 bname++;        
317         snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
318         /* a existing call file the archive dir is overwritten */
319         unlink(newfn);
320         if (rename(o->fn, newfn) != 0) {
321                 unlink(o->fn);
322                 return -1;
323         } else
324                 return 0;
325 }
326
327 static void *attempt_thread(void *data)
328 {
329         struct outgoing *o = data;
330         int res, reason;
331         if (!ast_strlen_zero(o->app)) {
332                 if (option_verbose > 2)
333                         ast_verbose(VERBOSE_PREFIX_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, AST_FORMAT_SLINEAR, 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         } else {
336                 if (option_verbose > 2)
337                         ast_verbose(VERBOSE_PREFIX_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, AST_FORMAT_SLINEAR, 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         }
340         if (res) {
341                 ast_log(LOG_NOTICE, "Call failed to go through, reason %d\n", reason);
342                 if (o->retries >= o->maxretries + 1) {
343                         /* Max retries exceeded */
344                         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" : "");
345                         remove_from_queue(o, "Expired");
346                 } else {
347                         /* Notate that the call is still active */
348                         safe_append(o, time(NULL), "EndRetry");
349                 }
350         } else {
351                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
352                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\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         pthread_attr_t attr;
363         int ret;
364         pthread_attr_init(&attr);
365         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
366         if ((ret = ast_pthread_create(&t,&attr,attempt_thread, o)) != 0) {
367                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
368                 free_outgoing(o);
369         }
370 }
371
372 static int scan_service(char *fn, time_t now, time_t atime)
373 {
374         struct outgoing *o;
375         FILE *f;
376         o = malloc(sizeof(struct outgoing));
377         if (o) {
378                 init_outgoing(o);
379                 f = fopen(fn, "r+");
380                 if (f) {
381                         if (!apply_outgoing(o, fn, f)) {
382 #if 0
383                                 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
384 #endif
385                                 fclose(f);
386                                 if (o->retries <= o->maxretries) {
387                                         now += o->retrytime;
388                                         if (o->callingpid && (o->callingpid == ast_mainpid)) {
389                                                 safe_append(o, time(NULL), "DelayedRetry");
390                                                 free_outgoing(o);
391                                                 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
392                                         } else {
393                                                 /* Increment retries */
394                                                 o->retries++;
395                                                 /* If someone else was calling, they're presumably gone now
396                                                    so abort their retry and continue as we were... */
397                                                 if (o->callingpid)
398                                                         safe_append(o, time(NULL), "AbortRetry");
399
400                                                 safe_append(o, now, "StartRetry");
401                                                 launch_service(o);
402                                         }
403                                         return now;
404                                 } else {
405                                         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" : "");
406                                         free_outgoing(o);
407                                         remove_from_queue(o, "Expired");
408                                         return 0;
409                                 }
410                         } else {
411                                 free_outgoing(o);
412                                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
413                                 fclose(f);
414                                 remove_from_queue(o, "Failed");
415                         }
416                 } else {
417                         free_outgoing(o);
418                         ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
419                         remove_from_queue(o, "Failed");
420                 }
421         } else
422                 ast_log(LOG_WARNING, "Out of memory :(\n");
423         return -1;
424 }
425
426 static void *scan_thread(void *unused)
427 {
428         struct stat st;
429         DIR *dir;
430         struct dirent *de;
431         char fn[256];
432         int res;
433         time_t last = 0, next = 0, now;
434         for(;;) {
435                 /* Wait a sec */
436                 sleep(1);
437                 time(&now);
438                 if (!stat(qdir, &st)) {
439                         if ((st.st_mtime != last) || (next && (now > next))) {
440 #if 0
441                                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
442                                 printf("Ooh, something changed / timeout\n");
443 #endif                          
444                                 next = 0;
445                                 last = st.st_mtime;
446                                 dir = opendir(qdir);
447                                 if (dir) {
448                                         while((de = readdir(dir))) {
449                                                 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
450                                                 if (!stat(fn, &st)) {
451                                                         if (S_ISREG(st.st_mode)) {
452                                                                 if (st.st_mtime <= now) {
453                                                                         res = scan_service(fn, now, st.st_atime);
454                                                                         if (res > 0) {
455                                                                                 /* Update next service time */
456                                                                                 if (!next || (res < next)) {
457                                                                                         next = res;
458                                                                                 }
459                                                                         } else if (res)
460                                                                                 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
461                                                                 } else {
462                                                                         /* Update "next" update if necessary */
463                                                                         if (!next || (st.st_mtime < next))
464                                                                                 next = st.st_mtime;
465                                                                 }
466                                                         }
467                                                 } else
468                                                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
469                                         }
470                                         closedir(dir);
471                                 } else
472                                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
473                         }
474                 } else
475                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
476         }
477         return NULL;
478 }
479
480 static int unload_module(void)
481 {
482         return -1;
483 }
484
485 static int load_module(void)
486 {
487         pthread_t thread;
488         pthread_attr_t attr;
489         int ret;
490         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
491         if (mkdir(qdir, 0700) && (errno != EEXIST)) {
492                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
493                 return 0;
494         }
495         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
496         pthread_attr_init(&attr);
497         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
498         if ((ret = ast_pthread_create_background(&thread,&attr,scan_thread, NULL)) != 0) {
499                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
500                 return -1;
501         }
502         return 0;
503 }
504
505 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");