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