This rather large commit changes the way modules are loaded.
[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         int 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, "%d", &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         if (!ast_strlen_zero(o->app)) {
258                 if (option_verbose > 2)
259                         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);
260                 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);
261         } else {
262                 if (option_verbose > 2)
263                         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);
264                 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);
265         }
266         if (res) {
267                 ast_log(LOG_NOTICE, "Call failed to go through, reason %d\n", reason);
268                 if (o->retries >= o->maxretries + 1) {
269                         /* Max retries exceeded */
270                         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" : "");
271                         unlink(o->fn);
272                 } else {
273                         /* Notate that the call is still active */
274                         safe_append(o, time(NULL), "EndRetry");
275                 }
276         } else {
277                 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
278                 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
279                 unlink(o->fn);
280         }
281         free_outgoing(o);
282         return NULL;
283 }
284
285 static void launch_service(struct outgoing *o)
286 {
287         pthread_t t;
288         pthread_attr_t attr;
289         int ret;
290         pthread_attr_init(&attr);
291         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
292         if ((ret = ast_pthread_create(&t,&attr,attempt_thread, o)) != 0) {
293                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
294                 free_outgoing(o);
295         }
296 }
297
298 static int scan_service(char *fn, time_t now, time_t atime)
299 {
300         struct outgoing *o;
301         FILE *f;
302         o = malloc(sizeof(struct outgoing));
303         if (o) {
304                 init_outgoing(o);
305                 f = fopen(fn, "r+");
306                 if (f) {
307                         if (!apply_outgoing(o, fn, f)) {
308 #if 0
309                                 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
310 #endif
311                                 fclose(f);
312                                 if (o->retries <= o->maxretries) {
313                                         now += o->retrytime;
314                                         if (o->callingpid && (o->callingpid == ast_mainpid)) {
315                                                 safe_append(o, time(NULL), "DelayedRetry");
316                                                 free_outgoing(o);
317                                                 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
318                                         } else {
319                                                 /* Increment retries */
320                                                 o->retries++;
321                                                 /* If someone else was calling, they're presumably gone now
322                                                    so abort their retry and continue as we were... */
323                                                 if (o->callingpid)
324                                                         safe_append(o, time(NULL), "AbortRetry");
325
326                                                 safe_append(o, now, "StartRetry");
327                                                 launch_service(o);
328                                         }
329                                         return now;
330                                 } else {
331                                         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" : "");
332                                         free_outgoing(o);
333                                         unlink(fn);
334                                         return 0;
335                                 }
336                         } else {
337                                 free_outgoing(o);
338                                 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
339                                 fclose(f);
340                                 unlink(fn);
341                         }
342                 } else {
343                         free_outgoing(o);
344                         ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
345                         unlink(fn);
346                 }
347         } else
348                 ast_log(LOG_WARNING, "Out of memory :(\n");
349         return -1;
350 }
351
352 static void *scan_thread(void *unused)
353 {
354         struct stat st;
355         DIR *dir;
356         struct dirent *de;
357         char fn[256];
358         int res;
359         time_t last = 0, next = 0, now;
360         for(;;) {
361                 /* Wait a sec */
362                 sleep(1);
363                 time(&now);
364                 if (!stat(qdir, &st)) {
365                         if ((st.st_mtime != last) || (next && (now > next))) {
366 #if 0
367                                 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
368                                 printf("Ooh, something changed / timeout\n");
369 #endif                          
370                                 next = 0;
371                                 last = st.st_mtime;
372                                 dir = opendir(qdir);
373                                 if (dir) {
374                                         while((de = readdir(dir))) {
375                                                 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
376                                                 if (!stat(fn, &st)) {
377                                                         if (S_ISREG(st.st_mode)) {
378                                                                 if (st.st_mtime <= now) {
379                                                                         res = scan_service(fn, now, st.st_atime);
380                                                                         if (res > 0) {
381                                                                                 /* Update next service time */
382                                                                                 if (!next || (res < next)) {
383                                                                                         next = res;
384                                                                                 }
385                                                                         } else if (res)
386                                                                                 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
387                                                                 } else {
388                                                                         /* Update "next" update if necessary */
389                                                                         if (!next || (st.st_mtime < next))
390                                                                                 next = st.st_mtime;
391                                                                 }
392                                                         }
393                                                 } else
394                                                         ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
395                                         }
396                                         closedir(dir);
397                                 } else
398                                         ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
399                         }
400                 } else
401                         ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
402         }
403         return NULL;
404 }
405
406 static int unload_module(void *mod)
407 {
408         return -1;
409 }
410
411 static int load_module(void *mod)
412 {
413         pthread_t thread;
414         pthread_attr_t attr;
415         int ret;
416         snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
417         if (mkdir(qdir, 0700) && (errno != EEXIST)) {
418                 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
419                 return 0;
420         }
421         pthread_attr_init(&attr);
422         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
423         if ((ret = ast_pthread_create(&thread,&attr,scan_thread, NULL)) != 0) {
424                 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
425                 return -1;
426         }
427         return 0;
428 }
429
430 static const char *description(void)
431 {
432         return "Outgoing Spool Support";
433 }
434
435 static const char *key(void)
436 {
437         return ASTERISK_GPL_KEY;
438 }
439
440 STD_MOD(MOD_1 | NO_USECOUNT | NO_UNLOAD, NULL, NULL, NULL);