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