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