Merged revisions 61863 via svnmerge from
[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                                         ast_copy_string(o->tech, c, sizeof(o->tech));
170                                         if ((c2 = strchr(o->tech, '/'))) {
171                                                 *c2 = '\0';
172                                                 c2++;
173                                                 ast_copy_string(o->dest, c2, sizeof(o->dest));
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                                         ast_copy_string(o->app, c, sizeof(o->app));
182                                 } else if (!strcasecmp(buf, "data")) {
183                                         ast_copy_string(o->data, c, sizeof(o->data));
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                                         ast_copy_string(o->context, c, sizeof(o->context));
191                                 } else if (!strcasecmp(buf, "extension")) {
192                                         ast_copy_string(o->exten, c, sizeof(o->exten));
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         ast_copy_string(o->fn, fn, sizeof(o->fn));
244         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
245                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
246                 return -1;
247         }
248         return 0;
249 }
250
251 static void safe_append(struct outgoing *o, time_t now, char *s)
252 {
253         int fd;
254         FILE *f;
255         struct utimbuf tbuf;
256         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         pthread_attr_destroy(&attr);
371 }
372
373 static int scan_service(char *fn, time_t now, time_t atime)
374 {
375         struct outgoing *o;
376         FILE *f;
377         o = malloc(sizeof(struct outgoing));
378         if (o) {
379                 init_outgoing(o);
380                 f = fopen(fn, "r+");
381                 if (f) {
382                         if (!apply_outgoing(o, fn, f)) {
383 #if 0
384                                 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
385 #endif
386                                 fclose(f);
387                                 if (o->retries <= o->maxretries) {
388                                         now += o->retrytime;
389                                         if (o->callingpid && (o->callingpid == ast_mainpid)) {
390                                                 safe_append(o, time(NULL), "DelayedRetry");
391                                                 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
392                                                 free_outgoing(o);
393                                         } else {
394                                                 /* Increment retries */
395                                                 o->retries++;
396                                                 /* If someone else was calling, they're presumably gone now
397                                                    so abort their retry and continue as we were... */
398                                                 if (o->callingpid)
399                                                         safe_append(o, time(NULL), "AbortRetry");
400
401                                                 safe_append(o, now, "StartRetry");
402                                                 launch_service(o);
403                                         }
404                                         return now;
405                                 } else {
406                                         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" : "");
407                                         remove_from_queue(o, "Expired");
408                                         free_outgoing(o);
409                                         return 0;
410                                 }
411                         } else {
412                                 remove_from_queue(o, "Failed");
413                                 free_outgoing(o);
414                                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
415                                 fclose(f);
416                         }
417                 } else {
418                         remove_from_queue(o, "Failed");
419                         free_outgoing(o);
420                         ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
421                 }
422         } else
423                 ast_log(LOG_WARNING, "Out of memory :(\n");
424         return -1;
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         for(;;) {
436                 /* Wait a sec */
437                 sleep(1);
438                 time(&now);
439                 if (!stat(qdir, &st)) {
440                         if ((st.st_mtime != last) || (next && (now > next))) {
441 #if 0
442                                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
443                                 printf("Ooh, something changed / timeout\n");
444 #endif                          
445                                 next = 0;
446                                 last = st.st_mtime;
447                                 dir = opendir(qdir);
448                                 if (dir) {
449                                         while((de = readdir(dir))) {
450                                                 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
451                                                 if (!stat(fn, &st)) {
452                                                         if (S_ISREG(st.st_mode)) {
453                                                                 if (st.st_mtime <= now) {
454                                                                         res = scan_service(fn, now, st.st_atime);
455                                                                         if (res > 0) {
456                                                                                 /* Update next service time */
457                                                                                 if (!next || (res < next)) {
458                                                                                         next = res;
459                                                                                 }
460                                                                         } else if (res)
461                                                                                 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
462                                                                 } else {
463                                                                         /* Update "next" update if necessary */
464                                                                         if (!next || (st.st_mtime < next))
465                                                                                 next = st.st_mtime;
466                                                                 }
467                                                         }
468                                                 } else
469                                                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
470                                         }
471                                         closedir(dir);
472                                 } else
473                                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
474                         }
475                 } else
476                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
477         }
478         return NULL;
479 }
480
481 static int unload_module(void)
482 {
483         return -1;
484 }
485
486 static int load_module(void)
487 {
488         pthread_t thread;
489         pthread_attr_t attr;
490         int ret;
491         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
492         if (mkdir(qdir, 0700) && (errno != EEXIST)) {
493                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
494                 return 0;
495         }
496         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
497         pthread_attr_init(&attr);
498         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
499         if ((ret = ast_pthread_create_background(&thread,&attr,scan_thread, NULL)) != 0) {
500                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
501                 return -1;
502         }
503         pthread_attr_destroy(&attr);
504         return 0;
505 }
506
507 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");