remove the dlfcn compatibility stuff, because no platforms that Asterisk currently...
[asterisk-bristuff.git] / pbx / pbx_spool.c
blob9316971421d8df4d9e87d31bd94974cd1566c0dc
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;
82 /* What to connect to outgoing */
83 char tech[256];
84 char dest[256];
86 /* If application */
87 char app[256];
88 char data[256];
90 /* If extension/context/priority */
91 char exten[256];
92 char context[256];
93 int priority;
95 /* CallerID Information */
96 char cid_num[256];
97 char cid_name[256];
99 /* account code */
100 char account[AST_MAX_ACCOUNT_CODE];
102 /* Variables and Functions */
103 struct ast_variable *vars;
105 /* Maximum length of call */
106 int maxlen;
108 /* options */
109 struct ast_flags options;
112 static void init_outgoing(struct outgoing *o)
114 memset(o, 0, sizeof(struct outgoing));
115 o->priority = 1;
116 o->retrytime = 300;
117 o->waittime = 45;
118 ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
121 static void free_outgoing(struct outgoing *o)
123 free(o);
126 static int apply_outgoing(struct outgoing *o, char *fn, FILE *f)
128 char buf[256];
129 char *c, *c2;
130 int lineno = 0;
131 struct ast_variable *var, *last = o->vars;
133 while (last && last->next) {
134 last = last->next;
137 while(fgets(buf, sizeof(buf), f)) {
138 lineno++;
139 /* Trim comments */
140 c = buf;
141 while ((c = strchr(c, '#'))) {
142 if ((c == buf) || (*(c-1) == ' ') || (*(c-1) == '\t'))
143 *c = '\0';
144 else
145 c++;
148 c = buf;
149 while ((c = strchr(c, ';'))) {
150 if ((c > buf) && (c[-1] == '\\')) {
151 memmove(c - 1, c, strlen(c) + 1);
152 c++;
153 } else {
154 *c = '\0';
155 break;
159 /* Trim trailing white space */
160 while(!ast_strlen_zero(buf) && buf[strlen(buf) - 1] < 33)
161 buf[strlen(buf) - 1] = '\0';
162 if (!ast_strlen_zero(buf)) {
163 c = strchr(buf, ':');
164 if (c) {
165 *c = '\0';
166 c++;
167 while ((*c) && (*c < 33))
168 c++;
169 #if 0
170 printf("'%s' is '%s' at line %d\n", buf, c, lineno);
171 #endif
172 if (!strcasecmp(buf, "channel")) {
173 ast_copy_string(o->tech, c, sizeof(o->tech));
174 if ((c2 = strchr(o->tech, '/'))) {
175 *c2 = '\0';
176 c2++;
177 ast_copy_string(o->dest, c2, sizeof(o->dest));
178 } else {
179 ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, fn);
180 o->tech[0] = '\0';
182 } else if (!strcasecmp(buf, "callerid")) {
183 ast_callerid_split(c, o->cid_name, sizeof(o->cid_name), o->cid_num, sizeof(o->cid_num));
184 } else if (!strcasecmp(buf, "application")) {
185 ast_copy_string(o->app, c, sizeof(o->app));
186 } else if (!strcasecmp(buf, "data")) {
187 ast_copy_string(o->data, c, sizeof(o->data));
188 } else if (!strcasecmp(buf, "maxretries")) {
189 if (sscanf(c, "%d", &o->maxretries) != 1) {
190 ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, fn);
191 o->maxretries = 0;
193 } else if (!strcasecmp(buf, "context")) {
194 ast_copy_string(o->context, c, sizeof(o->context));
195 } else if (!strcasecmp(buf, "extension")) {
196 ast_copy_string(o->exten, c, sizeof(o->exten));
197 } else if (!strcasecmp(buf, "priority")) {
198 if ((sscanf(c, "%d", &o->priority) != 1) || (o->priority < 1)) {
199 ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, fn);
200 o->priority = 1;
202 } else if (!strcasecmp(buf, "retrytime")) {
203 if ((sscanf(c, "%d", &o->retrytime) != 1) || (o->retrytime < 1)) {
204 ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, fn);
205 o->retrytime = 300;
207 } else if (!strcasecmp(buf, "waittime")) {
208 if ((sscanf(c, "%d", &o->waittime) != 1) || (o->waittime < 1)) {
209 ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, fn);
210 o->waittime = 45;
212 } else if (!strcasecmp(buf, "retry")) {
213 o->retries++;
214 } else if (!strcasecmp(buf, "startretry")) {
215 if (sscanf(c, "%ld", &o->callingpid) != 1) {
216 ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
217 o->callingpid = 0;
219 } else if (!strcasecmp(buf, "endretry") || !strcasecmp(buf, "abortretry")) {
220 o->callingpid = 0;
221 o->retries++;
222 } else if (!strcasecmp(buf, "delayedretry")) {
223 } else if (!strcasecmp(buf, "setvar") || !strcasecmp(buf, "set")) {
224 c2 = c;
225 strsep(&c2, "=");
226 if (c2) {
227 var = ast_variable_new(c, c2);
228 if (var) {
229 /* Always insert at the end, because some people want to treat the spool file as a script */
230 if (last) {
231 last->next = var;
232 } else {
233 o->vars = var;
235 last = var;
237 } else
238 ast_log(LOG_WARNING, "Malformed \"%s\" argument. Should be \"%s: variable=value\"\n", buf, buf);
239 } else if (!strcasecmp(buf, "account")) {
240 ast_copy_string(o->account, c, sizeof(o->account));
241 } else if (!strcasecmp(buf, "alwaysdelete")) {
242 ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
243 } else if (!strcasecmp(buf, "archive")) {
244 ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
245 } else {
246 ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", buf, lineno, fn);
248 } else
249 ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, fn);
252 ast_copy_string(o->fn, fn, sizeof(o->fn));
253 if (ast_strlen_zero(o->tech) || ast_strlen_zero(o->dest) || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
254 ast_log(LOG_WARNING, "At least one of app or extension must be specified, along with tech and dest in file %s\n", fn);
255 return -1;
257 return 0;
260 static void safe_append(struct outgoing *o, time_t now, char *s)
262 int fd;
263 FILE *f;
264 struct utimbuf tbuf;
265 fd = open(o->fn, O_WRONLY|O_APPEND);
266 if (fd > -1) {
267 f = fdopen(fd, "a");
268 if (f) {
269 fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
270 fclose(f);
271 } else
272 close(fd);
273 /* Update the file time */
274 tbuf.actime = now;
275 tbuf.modtime = now + o->retrytime;
276 if (utime(o->fn, &tbuf))
277 ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
282 * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
284 * \param o the pointer to outgoing struct
285 * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
287 static int remove_from_queue(struct outgoing *o, const char *status)
289 int fd;
290 FILE *f;
291 char newfn[256];
292 const char *bname;
294 if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
295 struct stat current_file_status;
297 if (!stat(o->fn, &current_file_status))
298 if (time(NULL) < current_file_status.st_mtime)
299 return 0;
302 if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
303 unlink(o->fn);
304 return 0;
306 if (mkdir(qdonedir, 0700) && (errno != EEXIST)) {
307 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
308 unlink(o->fn);
309 return -1;
311 fd = open(o->fn, O_WRONLY|O_APPEND);
312 if (fd > -1) {
313 f = fdopen(fd, "a");
314 if (f) {
315 fprintf(f, "Status: %s\n", status);
316 fclose(f);
317 } else
318 close(fd);
321 bname = strrchr(o->fn,'/');
322 if (bname == NULL)
323 bname = o->fn;
324 else
325 bname++;
326 snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
327 /* a existing call file the archive dir is overwritten */
328 unlink(newfn);
329 if (rename(o->fn, newfn) != 0) {
330 unlink(o->fn);
331 return -1;
332 } else
333 return 0;
336 static void *attempt_thread(void *data)
338 struct outgoing *o = data;
339 int res, reason;
340 if (!ast_strlen_zero(o->app)) {
341 if (option_verbose > 2)
342 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);
343 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);
344 } else {
345 if (option_verbose > 2)
346 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);
347 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);
349 if (res) {
350 ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
351 if (o->retries >= o->maxretries + 1) {
352 /* Max retries exceeded */
353 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" : "");
354 remove_from_queue(o, "Expired");
355 } else {
356 /* Notate that the call is still active */
357 safe_append(o, time(NULL), "EndRetry");
359 } else {
360 ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
361 ast_log(LOG_EVENT, "Queued call to %s/%s completed\n", o->tech, o->dest);
362 remove_from_queue(o, "Completed");
364 free_outgoing(o);
365 return NULL;
368 static void launch_service(struct outgoing *o)
370 pthread_t t;
371 pthread_attr_t attr;
372 int ret;
373 pthread_attr_init(&attr);
374 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
375 if ((ret = ast_pthread_create(&t,&attr,attempt_thread, o)) != 0) {
376 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
377 free_outgoing(o);
379 pthread_attr_destroy(&attr);
382 static int scan_service(char *fn, time_t now, time_t atime)
384 struct outgoing *o;
385 FILE *f;
386 o = malloc(sizeof(struct outgoing));
387 if (o) {
388 init_outgoing(o);
389 f = fopen(fn, "r+");
390 if (f) {
391 if (!apply_outgoing(o, fn, f)) {
392 #if 0
393 printf("Filename: %s, Retries: %d, max: %d\n", fn, o->retries, o->maxretries);
394 #endif
395 fclose(f);
396 if (o->retries <= o->maxretries) {
397 now += o->retrytime;
398 if (o->callingpid && (o->callingpid == ast_mainpid)) {
399 safe_append(o, time(NULL), "DelayedRetry");
400 ast_log(LOG_DEBUG, "Delaying retry since we're currently running '%s'\n", o->fn);
401 free_outgoing(o);
402 } else {
403 /* Increment retries */
404 o->retries++;
405 /* If someone else was calling, they're presumably gone now
406 so abort their retry and continue as we were... */
407 if (o->callingpid)
408 safe_append(o, time(NULL), "AbortRetry");
410 safe_append(o, now, "StartRetry");
411 launch_service(o);
413 return now;
414 } else {
415 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" : "");
416 free_outgoing(o);
417 remove_from_queue(o, "Expired");
418 return 0;
420 } else {
421 free_outgoing(o);
422 ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", fn);
423 fclose(f);
424 remove_from_queue(o, "Failed");
426 } else {
427 free_outgoing(o);
428 ast_log(LOG_WARNING, "Unable to open %s: %s, deleting\n", fn, strerror(errno));
429 remove_from_queue(o, "Failed");
431 } else
432 ast_log(LOG_WARNING, "Out of memory :(\n");
433 return -1;
436 static void *scan_thread(void *unused)
438 struct stat st;
439 DIR *dir;
440 struct dirent *de;
441 char fn[256];
442 int res;
443 time_t last = 0, next = 0, now;
444 for(;;) {
445 /* Wait a sec */
446 sleep(1);
447 time(&now);
448 if (!stat(qdir, &st)) {
449 if ((st.st_mtime != last) || (next && (now > next))) {
450 #if 0
451 printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
452 printf("Ooh, something changed / timeout\n");
453 #endif
454 next = 0;
455 last = st.st_mtime;
456 dir = opendir(qdir);
457 if (dir) {
458 while((de = readdir(dir))) {
459 snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
460 if (!stat(fn, &st)) {
461 if (S_ISREG(st.st_mode)) {
462 if (st.st_mtime <= now) {
463 res = scan_service(fn, now, st.st_atime);
464 if (res > 0) {
465 /* Update next service time */
466 if (!next || (res < next)) {
467 next = res;
469 } else if (res)
470 ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
471 } else {
472 /* Update "next" update if necessary */
473 if (!next || (st.st_mtime < next))
474 next = st.st_mtime;
477 } else
478 ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
480 closedir(dir);
481 } else
482 ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
484 } else
485 ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
487 return NULL;
490 static int unload_module(void)
492 return -1;
495 static int load_module(void)
497 pthread_t thread;
498 pthread_attr_t attr;
499 int ret;
500 snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
501 if (mkdir(qdir, 0700) && (errno != EEXIST)) {
502 ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
503 return 0;
505 snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
506 pthread_attr_init(&attr);
507 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
508 if ((ret = ast_pthread_create_background(&thread,&attr,scan_thread, NULL)) != 0) {
509 ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
510 return -1;
512 pthread_attr_destroy(&attr);
513 return 0;
516 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");