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