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