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