fix some indentation
[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         /* Channel variables */
79         char variable[10*256];
80         /* Account code */
81         char account[256];
82         
83         /* Maximum length of call */
84         int maxlen;
85         
86 };
87
88 static void init_outgoing(struct outgoing *o)
89 {
90         memset(o, 0, sizeof(struct outgoing));
91         o->priority = 1;
92         o->retrytime = 300;
93         o->waittime = 45;
94 }
95
96 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
97 {
98         char buf[256];
99         char *c, *c2;
100         int lineno = 0;
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")) { /* JDG variable support */
180                                         strncat(o->variable, c, sizeof(o->variable) - strlen(o->variable) - 1);
181                                         strncat(o->variable, "|", sizeof(o->variable) - strlen(o->variable) - 1);
182
183                                 } else if (!strcasecmp(buf, "account")) {
184                                         strncpy(o->account, c, sizeof(o->account) - 1);
185                                 } else {
186                                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
187                                 }
188                         } else
189                                 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
190                 }
191         }
192         strncpy(o->fn, fn, sizeof(o->fn) - 1);
193         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
194                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
195                 return -1;
196         }
197         return 0;
198 }
199
200 static void safe_append(struct outgoing *o, time_t now, char *s)
201 {
202         int fd;
203         FILE *f;
204         struct utimbuf tbuf;
205         fd = open(o->fn, O_WRONLY|O_APPEND);
206         if (fd > -1) {
207                 f = fdopen(fd, "a");
208                 if (f) {
209                         fprintf(f, "%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
210                         fclose(f);
211                 } else
212                         close(fd);
213                 /* Update the file time */
214                 tbuf.actime = now;
215                 tbuf.modtime = now + o->retrytime;
216                 if (utime(o->fn, &tbuf))
217                         ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
218         }
219 }
220
221 static void *attempt_thread(void *data)
222 {
223         struct outgoing *o = data;
224         int res, reason;
225         if (!ast_strlen_zero(o->app)) {
226                 if (option_verbose > 2)
227                         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);
228                 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, NULL);
229         } else {
230                 if (option_verbose > 2)
231                         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);
232                 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, NULL);
233         }
234         if (res) {
235                 ast_log(LOG_NOTICE, "Call failed to go through, reason %d\n", reason);
236                 if (o->retries >= o->maxretries + 1) {
237                         /* Max retries exceeded */
238                         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" : "");
239                         unlink(o->fn);
240                 } else {
241                         /* Notate that the call is still active */
242                         safe_append(o, time(NULL), "EndRetry");
243                 }
244         } else {
245                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
246                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
247                 unlink(o->fn);
248         }
249         free(o);
250         return NULL;
251 }
252
253 static void launch_service(struct outgoing *o)
254 {
255         pthread_t t;
256         pthread_attr_t attr;
257         pthread_attr_init(&attr);
258         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
259         if (ast_pthread_create(&t,&attr,attempt_thread, o) == -1) {
260                 ast_log(LOG_WARNING, "Unable to create thread :(\n");
261                 free(o);
262         }
263 }
264
265 static int scan_service(char *fn, time_t now, time_t atime)
266 {
267         struct outgoing *o;
268         FILE *f;
269         o = malloc(sizeof(struct outgoing));
270         if (o) {
271                 init_outgoing(o);
272                 f = fopen(fn, "r+");
273                 if (f) {
274                         if (!apply_outgoing(o, fn, f)) {
275 #if 0
276                                 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
277 #endif
278                                 fclose(f);
279                                 if (o->retries <= o->maxretries) {
280                                         if (o->callingpid && (o->callingpid == ast_mainpid)) {
281                                                 safe_append(o, time(NULL), "DelayedRetry");
282                                                 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
283                                         } else {
284                                                 /* Increment retries */
285                                                 o->retries++;
286                                                 /* If someone else was calling, they're presumably gone now
287                                                    so abort their retry and continue as we were... */
288                                                 if (o->callingpid)
289                                                         safe_append(o, time(NULL), "AbortRetry");
290
291                                                 safe_append(o, now, "StartRetry");
292                                                 launch_service(o);
293                                         }
294                                         now += o->retrytime;
295                                         return now;
296                                 } else {
297                                         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" : "");
298                                         free(o);
299                                         unlink(fn);
300                                         return 0;
301                                 }
302                         } else {
303                                 free(o);
304                                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
305                                 fclose(f);
306                                 unlink(fn);
307                         }
308                 } else {
309                         free(o);
310                         ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
311                         unlink(fn);
312                 }
313         } else
314                 ast_log(LOG_WARNING, "Out of memory :(\n");
315         return -1;
316 }
317
318 static void *scan_thread(void *unused)
319 {
320         struct stat st;
321         DIR *dir;
322         struct dirent *de;
323         char fn[256];
324         int res;
325         time_t last = 0, next = 0, now;
326         for(;;) {
327                 /* Wait a sec */
328                 sleep(1);
329                 time(&now);
330                 if (!stat(qdir, &st)) {
331                         if ((st.st_mtime != last) || (next && (now > next))) {
332 #if 0
333                                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
334                                 printf("Ooh, something changed / timeout\n");
335 #endif                          
336                                 next = 0;
337                                 last = st.st_mtime;
338                                 dir = opendir(qdir);
339                                 if (dir) {
340                                         while((de = readdir(dir))) {
341                                                 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
342                                                 if (!stat(fn, &st)) {
343                                                         if (S_ISREG(st.st_mode)) {
344                                                                 if (st.st_mtime <= now) {
345                                                                         res = scan_service(fn, now, st.st_atime);
346                                                                         if (res > 0) {
347                                                                                 /* Update next service time */
348                                                                                 if (!next || (res < next)) {
349                                                                                         next = res;
350                                                                                 }
351                                                                         } else if (res)
352                                                                                 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
353                                                                 } else {
354                                                                         /* Update "next" update if necessary */
355                                                                         if (!next || (st.st_mtime < next))
356                                                                                 next = st.st_mtime;
357                                                                 }
358                                                         }
359                                                 } else
360                                                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
361                                         }
362                                         closedir(dir);
363                                 } else
364                                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
365                         }
366                 } else
367                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
368         }
369         return NULL;
370 }
371
372 int unload_module(void)
373 {
374         return -1;
375 }
376
377 int load_module(void)
378 {
379         pthread_t thread;
380         pthread_attr_t attr;
381         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
382         if (mkdir(qdir, 0700) && (errno != EEXIST)) {
383                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
384                 return 0;
385         }
386         pthread_attr_init(&attr);
387         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
388         if (ast_pthread_create(&thread,&attr,scan_thread, NULL) == -1) {
389                 ast_log(LOG_WARNING, "Unable to create thread :(\n");
390                 return -1;
391         }
392         return 0;
393 }
394
395 char *description(void)
396 {
397         return tdesc;
398 }
399
400 int usecount(void)
401 {
402         return 1;
403 }
404
405 char *key()
406 {
407         return ASTERISK_GPL_KEY;
408 }