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