Let's also include aclocal.m4
[asterisk-bristuff.git] / pbx / pbx_spool.c
blob53211917d67770ebcc84581ee13f2d2d2cb0a308
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
19 /*! \file
21 * \brief Full-featured outgoing call spool support
25 #include "asterisk.h"
27 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29 #include <sys/stat.h>
30 #include <errno.h>
31 #include <time.h>
32 #include <utime.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <dirent.h>
36 #include <string.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <unistd.h>
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"
52 * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
53 * The spool file contains a header
56 enum {
57 /*! Always delete the call file after a call succeeds or the
58 * maximum number of retries is exceeded, even if the
59 * modification time of the call file is in the future.
61 SPOOL_FLAG_ALWAYS_DELETE = (1 << 0),
62 /* Don't unlink the call file after processing, move in qdonedir */
63 SPOOL_FLAG_ARCHIVE = (1 << 1)
66 static char qdir[255];
67 static char qdonedir[255];
69 struct outgoing {
70 char fn[256];
71 /* Current number of retries */
72 int retries;
73 /* Maximum number of retries permitted */
74 int maxretries;
75 /* How long to wait between retries (in seconds) */
76 int retrytime;
77 /* How long to wait for an answer */
78 int waittime;
79 /* PID which is currently calling */
80 long callingpid;
81 /* Formats (codecs) for this call */
82 int format;
84 /* What to connect to outgoing */
85 char tech[256];
86 char dest[256];
88 /* If application */
89 char app[256];
90 char data[256];
92 /* If extension/context/priority */
93 char exten[256];
94 char context[256];
95 int priority;
97 /* CallerID Information */
98 char cid_num[256];
99 char cid_name[256];
101 /* account code */
102 char account[AST_MAX_ACCOUNT_CODE];
104 /* Variables and Functions */
105 struct ast_variable *vars;
107 /* Maximum length of call */
108 int maxlen;
110 /* options */
111 struct ast_flags options;
114 static void init_outgoing(struct outgoing *o)
116 memset(o, 0, sizeof(struct outgoing));
117 o->priority = 1;
118 o->retrytime = 300;
119 o->waittime = 45;
120 o->format = AST_FORMAT_SLINEAR;
121 ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
124 static void free_outgoing(struct outgoing *o)
126 free(o);
129 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
131 char buf[256];
132 char *c, *c2;
133 int lineno = 0;
134 struct ast_variable *var, *last = o->vars;
136 while (last && last->next) {
137 last = last->next;
140 while(fgets(buf, sizeof(buf), f)) {
141 lineno++;
142 /* Trim comments */
143 c = buf;
144 while ((c = strchr(c, '#'))) {
145 if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
146 *c = '\0';
147 else
148 c++;
151 c = buf;
152 while ((c = strchr(c, ';'))) {
153 if ((c > buf) && (c[-1] == '\\')) {
154 memmove(c - 1, c, strlen(c) + 1);
155 c++;
156 } else {
157 *c = '\0';
158 break;
162 /* Trim trailing white space */
163 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
164 buf[strlen(buf) - 1] = '\0';
165 if (!ast_strlen_zero(buf)) {
166 c = strchr(buf, ':');
167 if (c) {
168 *c = '\0';
169 c++;
170 while ((*c) && (*c < 33))
171 c++;
172 #if 0
173 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
174 #endif
175 if (!strcasecmp(buf, "channel")) {
176 ast_copy_string(o->tech, c, sizeof(o->tech));
177 if ((c2 = strchr(o->tech, '/'))) {
178 *c2 = '\0';
179 c2++;
180 ast_copy_string(o->dest, c2, sizeof(o->dest));
181 } else {
182 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
183 o->tech[0] = '\0';
185 } else if (!strcasecmp(buf, "callerid")) {
186 ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
187 } else if (!strcasecmp(buf, "application")) {
188 ast_copy_string(o->app, c, sizeof(o->app));
189 } else if (!strcasecmp(buf, "data")) {
190 ast_copy_string(o->data, c, sizeof(o->data));
191 } else if (!strcasecmp(buf, "maxretries")) {
192 if (sscanf(c, "%d", &o->maxretries) != 1) {
193 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
194 o->maxretries = 0;
196 } else if (!strcasecmp(buf, "codecs")) {
197 ast_parse_allow_disallow(NULL, &o->format, c, 1);
198 } else if (!strcasecmp(buf, "context")) {
199 ast_copy_string(o->context, c, sizeof(o->context));
200 } else if (!strcasecmp(buf, "extension")) {
201 ast_copy_string(o->exten, c, sizeof(o->exten));
202 } else if (!strcasecmp(buf, "priority")) {
203 if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
204 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
205 o->priority = 1;
207 } else if (!strcasecmp(buf, "retrytime")) {
208 if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
209 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
210 o->retrytime = 300;
212 } else if (!strcasecmp(buf, "waittime")) {
213 if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
214 ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
215 o->waittime = 45;
217 } else if (!strcasecmp(buf, "retry")) {
218 o->retries++;
219 } else if (!strcasecmp(buf, "startretry")) {
220 if (sscanf(c, "%ld", &o->callingpid) != 1) {
221 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
222 o->callingpid = 0;
224 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
225 o->callingpid = 0;
226 o->retries++;
227 } else if (!strcasecmp(buf, "delayedretry")) {
228 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
229 c2 = c;
230 strsep(&c2, "=");
231 if (c2) {
232 var = ast_variable_new(c, c2);
233 if (var) {
234 /* Always insert at the end, because some people want to treat the spool file as a script */
235 if (last) {
236 last->next = var;
237 } else {
238 o->vars = var;
240 last = var;
242 } else
243 ast_log(LOG_WARNING, "Malformed \"%s\" argument. Should be \"%s: variable=value\"\n", buf, buf);
244 } else if (!strcasecmp(buf, "account")) {
245 ast_copy_string(o->account, c, sizeof(o->account));
246 } else if (!strcasecmp(buf, "alwaysdelete")) {
247 ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
248 } else if (!strcasecmp(buf, "archive")) {
249 ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
250 } else {
251 ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
253 } else
254 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
257 ast_copy_string(o->fn, fn, sizeof(o->fn));
258 if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
259 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
260 return -1;
262 return 0;
265 static void safe_append(struct outgoing *o, time_t now, char *s)
267 int fd;
268 FILE *f;
269 struct utimbuf tbuf;
270 fd = open(o->fn, O_WRONLY|O_APPEND);
271 if (fd > -1) {
272 f = fdopen(fd, "a");
273 if (f) {
274 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
275 fclose(f);
276 } else
277 close(fd);
278 /* Update the file time */
279 tbuf.actime = now;
280 tbuf.modtime = now + o->retrytime;
281 if (utime(o->fn, &tbuf))
282 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
287 * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
289 * \param o the pointer to outgoing struct
290 * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
292 static int remove_from_queue(struct outgoing *o, const char *status)
294 int fd;
295 FILE *f;
296 char newfn[256];
297 const char *bname;
299 if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
300 struct stat current_file_status;
302 if (!stat(o->fn, &current_file_status))
303 if (time(NULL) < current_file_status.st_mtime)
304 return 0;
307 if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
308 unlink(o->fn);
309 return 0;
311 if (mkdir(qdonedir, 0700) && (errno != EEXIST)) {
312 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
313 unlink(o->fn);
314 return -1;
316 fd = open(o->fn, O_WRONLY|O_APPEND);
317 if (fd > -1) {
318 f = fdopen(fd, "a");
319 if (f) {
320 fprintf(f, "Status: %s\n", status);
321 fclose(f);
322 } else
323 close(fd);
326 bname = strrchr(o->fn,'/');
327 if (bname == NULL)
328 bname = o->fn;
329 else
330 bname++;
331 snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
332 /* a existing call file the archive dir is overwritten */
333 unlink(newfn);
334 if (rename(o->fn, newfn) != 0) {
335 unlink(o->fn);
336 return -1;
337 } else
338 return 0;
341 static void *attempt_thread(void *data)
343 struct outgoing *o = data;
344 int res, reason;
345 if (!ast_strlen_zero(o->app)) {
346 if (option_verbose > 2)
347 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);
348 res = ast_pbx_outgoing_app(o->tech, o->format, 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);
349 } else {
350 if (option_verbose > 2)
351 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);
352 res = ast_pbx_outgoing_exten(o->tech, o->format, 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);
354 if (res) {
355 ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
356 if (o->retries >= o->maxretries + 1) {
357 /* Max retries exceeded */
358 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" : "");
359 remove_from_queue(o, "Expired");
360 } else {
361 /* Notate that the call is still active */
362 safe_append(o, time(NULL), "EndRetry");
364 } else {
365 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
366 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
367 remove_from_queue(o, "Completed");
369 free_outgoing(o);
370 return NULL;
373 static void launch_service(struct outgoing *o)
375 pthread_t t;
376 pthread_attr_t attr;
377 int ret;
378 pthread_attr_init(&attr);
379 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
380 if ((ret = ast_pthread_create(&t,&attr,attempt_thread, o)) != 0) {
381 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
382 free_outgoing(o);
384 pthread_attr_destroy(&attr);
387 static int scan_service(char *fn, time_t now, time_t atime)
389 struct outgoing *o;
390 FILE *f;
391 o = malloc(sizeof(struct outgoing));
392 if (o) {
393 init_outgoing(o);
394 f = fopen(fn, "r+");
395 if (f) {
396 if (!apply_outgoing(o, fn, f)) {
397 #if 0
398 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
399 #endif
400 fclose(f);
401 if (o->retries <= o->maxretries) {
402 now += o->retrytime;
403 if (o->callingpid && (o->callingpid == ast_mainpid)) {
404 safe_append(o, time(NULL), "DelayedRetry");
405 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
406 free_outgoing(o);
407 } else {
408 /* Increment retries */
409 o->retries++;
410 /* If someone else was calling, they're presumably gone now
411 so abort their retry and continue as we were... */
412 if (o->callingpid)
413 safe_append(o, time(NULL), "AbortRetry");
415 safe_append(o, now, "StartRetry");
416 launch_service(o);
418 return now;
419 } else {
420 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" : "");
421 free_outgoing(o);
422 remove_from_queue(o, "Expired");
423 return 0;
425 } else {
426 free_outgoing(o);
427 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
428 fclose(f);
429 remove_from_queue(o, "Failed");
431 } else {
432 free_outgoing(o);
433 ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
434 remove_from_queue(o, "Failed");
436 } else
437 ast_log(LOG_WARNING, "Out of memory :(\n");
438 return -1;
441 static void *scan_thread(void *unused)
443 struct stat st;
444 DIR *dir;
445 struct dirent *de;
446 char fn[256];
447 int res;
448 time_t last = 0, next = 0, now;
449 for(;;) {
450 /* Wait a sec */
451 sleep(1);
452 time(&now);
453 if (!stat(qdir, &st)) {
454 if ((st.st_mtime != last) || (next && (now > next))) {
455 #if 0
456 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
457 printf("Ooh, something changed / timeout\n");
458 #endif
459 next = 0;
460 last = st.st_mtime;
461 dir = opendir(qdir);
462 if (dir) {
463 while((de = readdir(dir))) {
464 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
465 if (!stat(fn, &st)) {
466 if (S_ISREG(st.st_mode)) {
467 if (st.st_mtime <= now) {
468 res = scan_service(fn, now, st.st_atime);
469 if (res > 0) {
470 /* Update next service time */
471 if (!next || (res < next)) {
472 next = res;
474 } else if (res)
475 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
476 } else {
477 /* Update "next" update if necessary */
478 if (!next || (st.st_mtime < next))
479 next = st.st_mtime;
482 } else
483 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
485 closedir(dir);
486 } else
487 ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
489 } else
490 ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
492 return NULL;
495 static int unload_module(void)
497 return -1;
500 static int load_module(void)
502 pthread_t thread;
503 pthread_attr_t attr;
504 int ret;
505 snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
506 if (mkdir(qdir, 0700) && (errno != EEXIST)) {
507 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
508 return 0;
510 snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
511 pthread_attr_init(&attr);
512 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
513 if ((ret = ast_pthread_create_background(&thread,&attr,scan_thread, NULL)) != 0) {
514 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
515 return -1;
517 pthread_attr_destroy(&attr);
518 return 0;
521 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");