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