allow semicolons to be escaped in call files (issue #5407)
[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 /*
20  *
21  * Full-featured outgoing call spool support
22  * 
23  */
24
25 #include <sys/stat.h>
26 #include <errno.h>
27 #include <time.h>
28 #include <utime.h>
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <dirent.h>
32 #include <string.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <unistd.h>
36
37 #include "asterisk.h"
38
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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 static char *tdesc = "Outgoing Spool Support";
57 static char qdir[255];
58
59 struct outgoing {
60         char fn[256];
61         /* Current number of retries */
62         int retries;
63         /* Maximum number of retries permitted */
64         int maxretries;
65         /* How long to wait between retries (in seconds) */
66         int retrytime;
67         /* How long to wait for an answer */
68         int waittime;
69         /* PID which is currently calling */
70         int callingpid;
71         
72         /* What to connect to outgoing */
73         char tech[256];
74         char dest[256];
75         
76         /* If application */
77         char app[256];
78         char data[256];
79
80         /* If extension/context/priority */
81         char exten[256];
82         char context[256];
83         int priority;
84
85         /* CallerID Information */
86         char cid_num[256];
87         char cid_name[256];
88
89         /* Variables and Functions */
90         struct ast_variable *vars;
91         
92         /* Maximum length of call */
93         int maxlen;
94 };
95
96 static void init_outgoing(struct outgoing *o)
97 {
98         memset(o, 0, sizeof(struct outgoing));
99         o->priority = 1;
100         o->retrytime = 300;
101         o->waittime = 45;
102 }
103
104 static void free_outgoing(struct outgoing *o)
105 {
106         struct ast_variable *last;
107         while(o->vars) {
108                 last = o->vars;
109                 o->vars = o->vars->next;
110                 free(last);
111         }
112         free(o);
113 }
114
115 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
116 {
117         char buf[256];
118         char *c, *c2;
119         int lineno = 0;
120         struct ast_variable *var;
121
122         while(fgets(buf, sizeof(buf), f)) {
123                 lineno++;
124                 /* Trim comments */
125                 c = buf;
126                 while ((c = strchr(c, '#'))) {
127                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
128                                 *c = '\0';
129                         else
130                                 c++;
131                 }
132
133                 c = buf;
134                 while ((c = strchr(c, ';'))) {
135                         if ((c > buf) && (c[-1] == '\\')) {
136                                 memmove(c - 1, c, strlen(c) + 1);
137                                 c++;
138                         } else {
139                                 *c = '\0';
140                                 break;
141                         }
142                 }
143
144                 /* Trim trailing white space */
145                 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
146                         buf[strlen(buf) - 1] = '\0';
147                 if (!ast_strlen_zero(buf)) {
148                         c = strchr(buf, ':');
149                         if (c) {
150                                 *c = '\0';
151                                 c++;
152                                 while ((*c) && (*c < 33))
153                                         c++;
154 #if 0
155                                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
156 #endif
157                                 if (!strcasecmp(buf, "channel")) {
158                                         strncpy(o->tech, c, sizeof(o->tech) - 1);
159                                         if ((c2 = strchr(o->tech, '/'))) {
160                                                 *c2 = '\0';
161                                                 c2++;
162                                                 strncpy(o->dest, c2, sizeof(o->dest) - 1);
163                                         } else {
164                                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
165                                                 o->tech[0] = '\0';
166                                         }
167                                 } else if (!strcasecmp(buf, "callerid")) {
168                                         ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
169                                 } else if (!strcasecmp(buf, "application")) {
170                                         strncpy(o->app, c, sizeof(o->app) - 1);
171                                 } else if (!strcasecmp(buf, "data")) {
172                                         strncpy(o->data, c, sizeof(o->data) - 1);
173                                 } else if (!strcasecmp(buf, "maxretries")) {
174                                         if (sscanf(c, "%d", &o->maxretries) != 1) {
175                                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
176                                                 o->maxretries = 0;
177                                         }
178                                 } else if (!strcasecmp(buf, "context")) {
179                                         strncpy(o->context, c, sizeof(o->context) - 1);
180                                 } else if (!strcasecmp(buf, "extension")) {
181                                         strncpy(o->exten, c, sizeof(o->exten) - 1);
182                                 } else if (!strcasecmp(buf, "priority")) {
183                                         if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
184                                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
185                                                 o->priority = 1;
186                                         }
187                                 } else if (!strcasecmp(buf, "retrytime")) {
188                                         if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
189                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
190                                                 o->retrytime = 300;
191                                         }
192                                 } else if (!strcasecmp(buf, "waittime")) {
193                                         if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
194                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
195                                                 o->waittime = 45;
196                                         }
197                                 } else if (!strcasecmp(buf, "retry")) {
198                                         o->retries++;
199                                 } else if (!strcasecmp(buf, "startretry")) {
200                                         if (sscanf(c, "%d", &o->callingpid) != 1) {
201                                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
202                                                 o->callingpid = 0;
203                                         }
204                                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
205                                         o->callingpid = 0;
206                                         o->retries++;
207                                 } else if (!strcasecmp(buf, "delayedretry")) {
208                                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
209                                         c2 = c;
210                                         strsep(&c2, "=");
211                                         var = ast_variable_new(c, c2);
212                                         if (var) {
213                                                 var->next = o->vars;
214                                                 o->vars = var;
215                                         }
216                                 } else if (!strcasecmp(buf, "account")) {
217                                         var = ast_variable_new("CDR(accountcode|r)", c);
218                                         if (var) {      
219                                                 var->next = o->vars;
220                                                 o->vars = var;
221                                         }
222                                 } else {
223                                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
224                                 }
225                         } else
226                                 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
227                 }
228         }
229         strncpy(o->fn, fn, sizeof(o->fn) - 1);
230         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
231                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
232                 return -1;
233         }
234         return 0;
235 }
236
237 static void safe_append(struct outgoing *o, time_t now, char *s)
238 {
239         int fd;
240         FILE *f;
241         struct utimbuf tbuf;
242         fd = open(o->fn, O_WRONLY|O_APPEND);
243         if (fd > -1) {
244                 f = fdopen(fd, "a");
245                 if (f) {
246                         fprintf(f, "%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
247                         fclose(f);
248                 } else
249                         close(fd);
250                 /* Update the file time */
251                 tbuf.actime = now;
252                 tbuf.modtime = now + o->retrytime;
253                 if (utime(o->fn, &tbuf))
254                         ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
255         }
256 }
257
258 static void *attempt_thread(void *data)
259 {
260         struct outgoing *o = data;
261         int res, reason;
262         if (!ast_strlen_zero(o->app)) {
263                 if (option_verbose > 2)
264                         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);
265                 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, NULL);
266         } else {
267                 if (option_verbose > 2)
268                         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);
269                 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, NULL);
270         }
271         if (res) {
272                 ast_log(LOG_NOTICE, "Call failed to go through, reason %d\n", reason);
273                 if (o->retries >= o->maxretries + 1) {
274                         /* Max retries exceeded */
275                         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" : "");
276                         unlink(o->fn);
277                 } else {
278                         /* Notate that the call is still active */
279                         safe_append(o, time(NULL), "EndRetry");
280                 }
281         } else {
282                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
283                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
284                 unlink(o->fn);
285         }
286         free_outgoing(o);
287         return NULL;
288 }
289
290 static void launch_service(struct outgoing *o)
291 {
292         pthread_t t;
293         pthread_attr_t attr;
294         pthread_attr_init(&attr);
295         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
296         if (ast_pthread_create(&t,&attr,attempt_thread, o) == -1) {
297                 ast_log(LOG_WARNING, "Unable to create thread :(\n");
298                 free_outgoing(o);
299         }
300 }
301
302 static int scan_service(char *fn, time_t now, time_t atime)
303 {
304         struct outgoing *o;
305         FILE *f;
306         o = malloc(sizeof(struct outgoing));
307         if (o) {
308                 init_outgoing(o);
309                 f = fopen(fn, "r+");
310                 if (f) {
311                         if (!apply_outgoing(o, fn, f)) {
312 #if 0
313                                 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
314 #endif
315                                 fclose(f);
316                                 if (o->retries <= o->maxretries) {
317                                         if (o->callingpid && (o->callingpid == ast_mainpid)) {
318                                                 safe_append(o, time(NULL), "DelayedRetry");
319                                                 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
320                                         } else {
321                                                 /* Increment retries */
322                                                 o->retries++;
323                                                 /* If someone else was calling, they're presumably gone now
324                                                    so abort their retry and continue as we were... */
325                                                 if (o->callingpid)
326                                                         safe_append(o, time(NULL), "AbortRetry");
327
328                                                 safe_append(o, now, "StartRetry");
329                                                 launch_service(o);
330                                         }
331                                         now += o->retrytime;
332                                         return now;
333                                 } else {
334                                         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" : "");
335                                         free_outgoing(o);
336                                         unlink(fn);
337                                         return 0;
338                                 }
339                         } else {
340                                 free_outgoing(o);
341                                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
342                                 fclose(f);
343                                 unlink(fn);
344                         }
345                 } else {
346                         free_outgoing(o);
347                         ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
348                         unlink(fn);
349                 }
350         } else
351                 ast_log(LOG_WARNING, "Out of memory :(\n");
352         return -1;
353 }
354
355 static void *scan_thread(void *unused)
356 {
357         struct stat st;
358         DIR *dir;
359         struct dirent *de;
360         char fn[256];
361         int res;
362         time_t last = 0, next = 0, now;
363         for(;;) {
364                 /* Wait a sec */
365                 sleep(1);
366                 time(&now);
367                 if (!stat(qdir, &st)) {
368                         if ((st.st_mtime != last) || (next && (now > next))) {
369 #if 0
370                                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
371                                 printf("Ooh, something changed / timeout\n");
372 #endif                          
373                                 next = 0;
374                                 last = st.st_mtime;
375                                 dir = opendir(qdir);
376                                 if (dir) {
377                                         while((de = readdir(dir))) {
378                                                 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
379                                                 if (!stat(fn, &st)) {
380                                                         if (S_ISREG(st.st_mode)) {
381                                                                 if (st.st_mtime <= now) {
382                                                                         res = scan_service(fn, now, st.st_atime);
383                                                                         if (res > 0) {
384                                                                                 /* Update next service time */
385                                                                                 if (!next || (res < next)) {
386                                                                                         next = res;
387                                                                                 }
388                                                                         } else if (res)
389                                                                                 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
390                                                                 } else {
391                                                                         /* Update "next" update if necessary */
392                                                                         if (!next || (st.st_mtime < next))
393                                                                                 next = st.st_mtime;
394                                                                 }
395                                                         }
396                                                 } else
397                                                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
398                                         }
399                                         closedir(dir);
400                                 } else
401                                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
402                         }
403                 } else
404                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
405         }
406         return NULL;
407 }
408
409 int unload_module(void)
410 {
411         return -1;
412 }
413
414 int load_module(void)
415 {
416         pthread_t thread;
417         pthread_attr_t attr;
418         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
419         if (mkdir(qdir, 0700) && (errno != EEXIST)) {
420                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
421                 return 0;
422         }
423         pthread_attr_init(&attr);
424         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
425         if (ast_pthread_create(&thread,&attr,scan_thread, NULL) == -1) {
426                 ast_log(LOG_WARNING, "Unable to create thread :(\n");
427                 return -1;
428         }
429         return 0;
430 }
431
432 char *description(void)
433 {
434         return tdesc;
435 }
436
437 int usecount(void)
438 {
439         return 1;
440 }
441
442 char *key()
443 {
444         return ASTERISK_GPL_KEY;
445 }