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