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