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