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