Add another big set of doxygen documentation improvements from snuffy.
[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 /*! \file
20  *
21  * \brief Full-featured outgoing call spool support
22  * 
23  */
24
25 #include "asterisk.h"
26
27 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
28
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <time.h>
32 #include <utime.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <dirent.h>
36 #include <string.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <unistd.h>
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 enum {
57         /*! Always delete the call file after a call succeeds or the
58          * maximum number of retries is exceeded, even if the
59          * modification time of the call file is in the future.
60          */
61         SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
62         /* Don't unlink the call file after processing, move in qdonedir */
63         SPOOL_FLAG_ARCHIVE = (1 << 1)
64 };
65
66 static char qdir[255];
67 static char qdonedir[255];
68
69 struct outgoing {
70         char fn[256];
71         /*! Current number of retries */
72         int retries;
73         /*! Maximum number of retries permitted */
74         int maxretries;
75         /*! How long to wait between retries (in seconds) */
76         int retrytime;
77         /*! How long to wait for an answer */
78         int waittime;
79         /*! PID which is currently calling */
80         long callingpid;
81         
82         /*! What to connect to outgoing */
83         char tech[256];
84         char dest[256];
85         
86         /* If application */
87         char app[256];
88         char data[256];
89
90         /* If extension/context/priority */
91         char exten[AST_MAX_EXTENSION];
92         char context[AST_MAX_CONTEXT];
93         int priority;
94
95         /* CallerID Information */
96         char cid_num[256];
97         char cid_name[256];
98
99         /*! account code */
100         char account[AST_MAX_ACCOUNT_CODE];
101
102         /*! Variables and Functions */
103         struct ast_variable *vars;
104         
105         /*! Maximum length of call */
106         int maxlen;
107
108         /*! options */
109         struct ast_flags options;
110 };
111
112 static void init_outgoing(struct outgoing *o)
113 {
114         o->priority = 1;
115         o->retrytime = 300;
116         o->waittime = 45;
117         ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
118 }
119
120 static void free_outgoing(struct outgoing *o)
121 {
122         ast_free(o);
123 }
124
125 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
126 {
127         char buf[256];
128         char *c, *c2;
129         int lineno = 0;
130         struct ast_variable *var;
131
132         while(fgets(buf, sizeof(buf), f)) {
133                 lineno++;
134                 /* Trim comments */
135                 c = buf;
136                 while ((c = strchr(c, '#'))) {
137                         if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
138                                 *c = '\0';
139                         else
140                                 c++;
141                 }
142
143                 c = buf;
144                 while ((c = strchr(c, ';'))) {
145                         if ((c > buf) && (c[-1] == '\\')) {
146                                 memmove(c - 1, c, strlen(c) + 1);
147                                 c++;
148                         } else {
149                                 *c = '\0';
150                                 break;
151                         }
152                 }
153
154                 /* Trim trailing white space */
155                 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
156                         buf[strlen(buf) - 1] = '\0';
157                 if (!ast_strlen_zero(buf)) {
158                         c = strchr(buf, ':');
159                         if (c) {
160                                 *c = '\0';
161                                 c++;
162                                 while ((*c) && (*c < 33))
163                                         c++;
164 #if 0
165                                 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
166 #endif
167                                 if (!strcasecmp(buf, "channel")) {
168                                         ast_copy_string(o->tech, c, sizeof(o->tech));
169                                         if ((c2 = strchr(o->tech, '/'))) {
170                                                 *c2 = '\0';
171                                                 c2++;
172                                                 ast_copy_string(o->dest, c2, sizeof(o->dest));
173                                         } else {
174                                                 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
175                                                 o->tech[0] = '\0';
176                                         }
177                                 } else if (!strcasecmp(buf, "callerid")) {
178                                         ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
179                                 } else if (!strcasecmp(buf, "application")) {
180                                         ast_copy_string(o->app, c, sizeof(o->app));
181                                 } else if (!strcasecmp(buf, "data")) {
182                                         ast_copy_string(o->data, c, sizeof(o->data));
183                                 } else if (!strcasecmp(buf, "maxretries")) {
184                                         if (sscanf(c, "%d", &o->maxretries) != 1) {
185                                                 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
186                                                 o->maxretries = 0;
187                                         }
188                                 } else if (!strcasecmp(buf, "context")) {
189                                         ast_copy_string(o->context, c, sizeof(o->context));
190                                 } else if (!strcasecmp(buf, "extension")) {
191                                         ast_copy_string(o->exten, c, sizeof(o->exten));
192                                 } else if (!strcasecmp(buf, "priority")) {
193                                         if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
194                                                 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
195                                                 o->priority = 1;
196                                         }
197                                 } else if (!strcasecmp(buf, "retrytime")) {
198                                         if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
199                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
200                                                 o->retrytime = 300;
201                                         }
202                                 } else if (!strcasecmp(buf, "waittime")) {
203                                         if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
204                                                 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
205                                                 o->waittime = 45;
206                                         }
207                                 } else if (!strcasecmp(buf, "retry")) {
208                                         o->retries++;
209                                 } else if (!strcasecmp(buf, "startretry")) {
210                                         if (sscanf(c, "%ld", &o->callingpid) != 1) {
211                                                 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
212                                                 o->callingpid = 0;
213                                         }
214                                 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
215                                         o->callingpid = 0;
216                                         o->retries++;
217                                 } else if (!strcasecmp(buf, "delayedretry")) {
218                                 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
219                                         c2 = c;
220                                         strsep(&c2, "=");
221                                         if (c2) {
222                                                 var = ast_variable_new(c, c2);
223                                                 if (var) {
224                                                         var->next = o->vars;
225                                                         o->vars = var;
226                                                 }
227                                         } else
228                                                 ast_log(LOG_WARNING, "Malformed \"%s\" argument.  Should be \"%s: variable=value\"\n", buf, buf);
229                                 } else if (!strcasecmp(buf, "account")) {
230                                         ast_copy_string(o->account, c, sizeof(o->account));
231                                 } else if (!strcasecmp(buf, "alwaysdelete")) {
232                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
233                                 } else if (!strcasecmp(buf, "archive")) {
234                                         ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
235                                 } else {
236                                         ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
237                                 }
238                         } else
239                                 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
240                 }
241         }
242         ast_copy_string(o->fn, fn, sizeof(o->fn));
243         if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
244                 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
245                 return -1;
246         }
247         return 0;
248 }
249
250 static void safe_append(struct outgoing *o, time_t now, char *s)
251 {
252         int fd;
253         FILE *f;
254         struct utimbuf tbuf;
255
256         if ((fd = open(o->fn, O_WRONLY | O_APPEND)) < 0)
257                 return;
258
259         if ((f = fdopen(fd, "a"))) {
260                 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
261                 fclose(f);
262         } else
263                 close(fd);
264
265         /* Update the file time */
266         tbuf.actime = now;
267         tbuf.modtime = now + o->retrytime;
268         if (utime(o->fn, &tbuf))
269                 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
270 }
271
272 /*!
273  * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
274  *
275  * \param o the pointer to outgoing struct
276  * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
277  */
278 static int remove_from_queue(struct outgoing *o, const char *status)
279 {
280         int fd;
281         FILE *f;
282         char newfn[256];
283         const char *bname;
284
285         if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
286                 struct stat current_file_status;
287
288                 if (!stat(o->fn, &current_file_status)) {
289                         if (time(NULL) < current_file_status.st_mtime)
290                                 return 0;
291                 }
292         }
293
294         if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
295                 unlink(o->fn);
296                 return 0;
297         }
298
299         if (ast_mkdir(qdonedir, 0777)) {
300                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
301                 unlink(o->fn);
302                 return -1;
303         }
304
305         if ((fd = open(o->fn, O_WRONLY | O_APPEND))) {
306                 if ((f = fdopen(fd, "a"))) {
307                         fprintf(f, "Status: %s\n", status);
308                         fclose(f);
309                 } else
310                         close(fd);
311         }
312
313         if (!(bname = strrchr(o->fn, '/')))
314                 bname = o->fn;
315         else
316                 bname++;        
317         snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
318         /* a existing call file the archive dir is overwritten */
319         unlink(newfn);
320         if (rename(o->fn, newfn) != 0) {
321                 unlink(o->fn);
322                 return -1;
323         } else
324                 return 0;
325 }
326
327 static void *attempt_thread(void *data)
328 {
329         struct outgoing *o = data;
330         int res, reason;
331         if (!ast_strlen_zero(o->app)) {
332                 ast_verb(3, "Attempting call on %s/%s for application %s(%s) (Retry %d)\n", o->tech, o->dest, o->app, o->data, o->retries);
333                 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, o->account, NULL);
334         } else {
335                 ast_verb(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);
336                 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, o->account, NULL);
337         }
338         if (res) {
339                 ast_log(LOG_NOTICE, "Call failed to go through, reason %d\n", reason);
340                 if (o->retries >= o->maxretries + 1) {
341                         /* Max retries exceeded */
342                         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" : "");
343                         remove_from_queue(o, "Expired");
344                 } else {
345                         /* Notate that the call is still active */
346                         safe_append(o, time(NULL), "EndRetry");
347                 }
348         } else {
349                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
350                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
351                 remove_from_queue(o, "Completed");
352         }
353         free_outgoing(o);
354         return NULL;
355 }
356
357 static void launch_service(struct outgoing *o)
358 {
359         pthread_t t;
360         int ret;
361
362         if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
363                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
364                 free_outgoing(o);
365         }
366 }
367
368 static int scan_service(char *fn, time_t now, time_t atime)
369 {
370         struct outgoing *o = NULL;
371         FILE *f;
372         int res = 0;
373
374         if (!(o = ast_calloc(1, sizeof(*o)))) {
375                 ast_log(LOG_WARNING, "Out of memory ;(\n");
376                 return -1;
377         }
378         
379         init_outgoing(o);
380
381         /* Attempt to open the file */
382         if (!(f = fopen(fn, "r+"))) {
383                 remove_from_queue(o, "Failed");
384                 free_outgoing(o);
385                 ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
386                 return -1;
387         }
388
389         /* Read in and verify the contents */
390         if (apply_outgoing(o, fn, f)) {
391                 remove_from_queue(o, "Failed");
392                 free_outgoing(o);
393                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
394                 fclose(f);
395                 return -1;
396         }
397         
398 #if 0
399         printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
400 #endif
401         fclose(f);
402         if (o->retries <= o->maxretries) {
403                 now += o->retrytime;
404                 if (o->callingpid && (o->callingpid == ast_mainpid)) {
405                         safe_append(o, time(NULL), "DelayedRetry");
406                         ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
407                         free_outgoing(o);
408                 } else {
409                         /* Increment retries */
410                         o->retries++;
411                         /* If someone else was calling, they're presumably gone now
412                            so abort their retry and continue as we were... */
413                         if (o->callingpid)
414                                 safe_append(o, time(NULL), "AbortRetry");
415                         
416                         safe_append(o, now, "StartRetry");
417                         launch_service(o);
418                 }
419                 res = now;
420         } else {
421                 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" : "");
422                 remove_from_queue(o, "Expired");
423                 free_outgoing(o);
424         }
425
426         return res;
427 }
428
429 static void *scan_thread(void *unused)
430 {
431         struct stat st;
432         DIR *dir;
433         struct dirent *de;
434         char fn[256];
435         int res;
436         time_t last = 0, next = 0, now;
437
438         for(;;) {
439                 /* Wait a sec */
440                 sleep(1);
441                 time(&now);
442
443                 if (stat(qdir, &st)) {
444                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
445                         continue;
446                 }
447
448                 /* Make sure it is time for us to execute our check */
449                 if ((st.st_mtime == last) && (next && (next > now)))
450                         continue;
451                 
452 #if 0
453                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
454                 printf("Ooh, something changed / timeout\n");
455 #endif                          
456                 next = 0;
457                 last = st.st_mtime;
458
459                 if (!(dir = opendir(qdir))) {
460                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
461                         continue;
462                 }
463
464                 while ((de = readdir(dir))) {
465                         snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
466                         if (stat(fn, &st)) {
467                                 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
468                                 continue;
469                         }
470                         if (!S_ISREG(st.st_mode))
471                                 continue;
472                         if (st.st_mtime <= now) {
473                                 res = scan_service(fn, now, st.st_atime);
474                                 if (res > 0) {
475                                         /* Update next service time */
476                                         if (!next || (res < next)) {
477                                                 next = res;
478                                         }
479                                 } else if (res)
480                                         ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
481                         } else {
482                                 /* Update "next" update if necessary */
483                                 if (!next || (st.st_mtime < next))
484                                         next = st.st_mtime;
485                         }
486                 }
487                 closedir(dir);
488         }
489         return NULL;
490 }
491
492 static int unload_module(void)
493 {
494         return -1;
495 }
496
497 static int load_module(void)
498 {
499         pthread_t thread;
500         int ret;
501         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
502         if (ast_mkdir(qdir, 0777)) {
503                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
504                 return 0;
505         }
506         snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
507
508         if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
509                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
510                 return -1;
511         }
512
513         return 0;
514 }
515
516 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");