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