pbx_spool.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2010, 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. /*! \file
  19. *
  20. * \brief Full-featured outgoing call spool support
  21. *
  22. */
  23. /*** MODULEINFO
  24. <support_level>core</support_level>
  25. ***/
  26. #include "asterisk.h"
  27. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  28. #include <sys/stat.h>
  29. #include <time.h>
  30. #include <utime.h>
  31. #include <dirent.h>
  32. #ifdef HAVE_INOTIFY
  33. #include <sys/inotify.h>
  34. #elif defined(HAVE_KQUEUE)
  35. #include <sys/types.h>
  36. #include <sys/time.h>
  37. #include <sys/event.h>
  38. #include <fcntl.h>
  39. #endif
  40. #include "asterisk/paths.h" /* use ast_config_AST_SPOOL_DIR */
  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/utils.h"
  49. #include "asterisk/options.h"
  50. #include "asterisk/format.h"
  51. #include "asterisk/format_cache.h"
  52. /*
  53. * pbx_spool is similar in spirit to qcall, but with substantially enhanced functionality...
  54. * The spool file contains a header
  55. */
  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.
  60. */
  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),
  64. /* Connect the channel with the outgoing extension once early media is received */
  65. SPOOL_FLAG_EARLY_MEDIA = (1 << 2),
  66. };
  67. static char qdir[255];
  68. static char qdonedir[255];
  69. struct outgoing {
  70. int retries; /*!< Current number of retries */
  71. int maxretries; /*!< Maximum number of retries permitted */
  72. int retrytime; /*!< How long to wait between retries (in seconds) */
  73. int waittime; /*!< How long to wait for an answer */
  74. long callingpid; /*!< PID which is currently calling */
  75. struct ast_format_cap *capabilities; /*!< Formats (codecs) for this call */
  76. AST_DECLARE_STRING_FIELDS (
  77. AST_STRING_FIELD(fn); /*!< File name of call file */
  78. AST_STRING_FIELD(tech); /*!< Which channel technology to use for outgoing call */
  79. AST_STRING_FIELD(dest); /*!< Which device/line to use for outgoing call */
  80. AST_STRING_FIELD(app); /*!< If application: Application name */
  81. AST_STRING_FIELD(data); /*!< If application: Application data */
  82. AST_STRING_FIELD(exten); /*!< If extension/context/priority: Extension in dialplan */
  83. AST_STRING_FIELD(context); /*!< If extension/context/priority: Dialplan context */
  84. AST_STRING_FIELD(cid_num); /*!< CallerID Information: Number/extension */
  85. AST_STRING_FIELD(cid_name); /*!< CallerID Information: Name */
  86. AST_STRING_FIELD(account); /*!< account code */
  87. );
  88. int priority; /*!< If extension/context/priority: Dialplan priority */
  89. struct ast_variable *vars; /*!< Variables and Functions */
  90. int maxlen; /*!< Maximum length of call */
  91. struct ast_flags options; /*!< options */
  92. };
  93. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  94. struct direntry {
  95. AST_LIST_ENTRY(direntry) list;
  96. time_t mtime;
  97. char name[0];
  98. };
  99. static AST_LIST_HEAD_STATIC(dirlist, direntry);
  100. static void queue_file(const char *filename, time_t when);
  101. #endif
  102. static void free_outgoing(struct outgoing *o)
  103. {
  104. if (o->vars) {
  105. ast_variables_destroy(o->vars);
  106. }
  107. ao2_cleanup(o->capabilities);
  108. ast_string_field_free_memory(o);
  109. ast_free(o);
  110. }
  111. static struct outgoing *new_outgoing(const char *fn)
  112. {
  113. struct outgoing *o;
  114. o = ast_calloc(1, sizeof(*o));
  115. if (!o) {
  116. return NULL;
  117. }
  118. /* Initialize the new object. */
  119. o->priority = 1;
  120. o->retrytime = 300;
  121. o->waittime = 45;
  122. ast_set_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE);
  123. if (ast_string_field_init(o, 128)) {
  124. /*
  125. * No need to call free_outgoing here since the failure was to
  126. * allocate string fields and no variables have been allocated
  127. * yet.
  128. */
  129. ast_free(o);
  130. return NULL;
  131. }
  132. ast_string_field_set(o, fn, fn);
  133. if (ast_strlen_zero(o->fn)) {
  134. /* String field set failed. Since this string is important we must fail. */
  135. free_outgoing(o);
  136. return NULL;
  137. }
  138. o->capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
  139. if (!o->capabilities) {
  140. free_outgoing(o);
  141. return NULL;
  142. }
  143. ast_format_cap_append(o->capabilities, ast_format_slin, 0);
  144. return o;
  145. }
  146. static void parse_line(char *line, unsigned int lineno, struct outgoing *o)
  147. {
  148. char *c;
  149. /* Trim comments */
  150. c = line;
  151. while ((c = strchr(c, '#'))) {
  152. if ((c == line) || (*(c-1) == ' ') || (*(c-1) == '\t')) {
  153. *c = '\0';
  154. break;
  155. }
  156. c++;
  157. }
  158. c = line;
  159. while ((c = strchr(c, ';'))) {
  160. if ((c > line) && (c[-1] == '\\')) {
  161. memmove(c - 1, c, strlen(c) + 1);
  162. } else {
  163. *c = '\0';
  164. break;
  165. }
  166. }
  167. /* Trim trailing white space */
  168. ast_trim_blanks(line);
  169. if (ast_strlen_zero(line)) {
  170. return;
  171. }
  172. c = strchr(line, ':');
  173. if (!c) {
  174. ast_log(LOG_NOTICE, "Syntax error at line %d of %s\n", lineno, o->fn);
  175. return;
  176. }
  177. *c = '\0';
  178. c = ast_skip_blanks(c + 1);
  179. #if 0
  180. printf("'%s' is '%s' at line %d\n", line, c, lineno);
  181. #endif
  182. if (!strcasecmp(line, "channel")) {
  183. char *c2;
  184. if ((c2 = strchr(c, '/'))) {
  185. *c2 = '\0';
  186. c2++;
  187. ast_string_field_set(o, tech, c);
  188. ast_string_field_set(o, dest, c2);
  189. } else {
  190. ast_log(LOG_NOTICE, "Channel should be in form Tech/Dest at line %d of %s\n", lineno, o->fn);
  191. }
  192. } else if (!strcasecmp(line, "callerid")) {
  193. char cid_name[80] = {0}, cid_num[80] = {0};
  194. ast_callerid_split(c, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
  195. ast_string_field_set(o, cid_num, cid_num);
  196. ast_string_field_set(o, cid_name, cid_name);
  197. } else if (!strcasecmp(line, "application")) {
  198. ast_string_field_set(o, app, c);
  199. } else if (!strcasecmp(line, "data")) {
  200. ast_string_field_set(o, data, c);
  201. } else if (!strcasecmp(line, "maxretries")) {
  202. if (sscanf(c, "%30d", &o->maxretries) != 1) {
  203. ast_log(LOG_WARNING, "Invalid max retries at line %d of %s\n", lineno, o->fn);
  204. o->maxretries = 0;
  205. }
  206. } else if (!strcasecmp(line, "codecs")) {
  207. ast_format_cap_update_by_allow_disallow(o->capabilities, c, 1);
  208. } else if (!strcasecmp(line, "context")) {
  209. ast_string_field_set(o, context, c);
  210. } else if (!strcasecmp(line, "extension")) {
  211. ast_string_field_set(o, exten, c);
  212. } else if (!strcasecmp(line, "priority")) {
  213. if ((sscanf(c, "%30d", &o->priority) != 1) || (o->priority < 1)) {
  214. ast_log(LOG_WARNING, "Invalid priority at line %d of %s\n", lineno, o->fn);
  215. o->priority = 1;
  216. }
  217. } else if (!strcasecmp(line, "retrytime")) {
  218. if ((sscanf(c, "%30d", &o->retrytime) != 1) || (o->retrytime < 1)) {
  219. ast_log(LOG_WARNING, "Invalid retrytime at line %d of %s\n", lineno, o->fn);
  220. o->retrytime = 300;
  221. }
  222. } else if (!strcasecmp(line, "waittime")) {
  223. if ((sscanf(c, "%30d", &o->waittime) != 1) || (o->waittime < 1)) {
  224. ast_log(LOG_WARNING, "Invalid waittime at line %d of %s\n", lineno, o->fn);
  225. o->waittime = 45;
  226. }
  227. } else if (!strcasecmp(line, "retry")) {
  228. o->retries++;
  229. } else if (!strcasecmp(line, "startretry")) {
  230. if (sscanf(c, "%30ld", &o->callingpid) != 1) {
  231. ast_log(LOG_WARNING, "Unable to retrieve calling PID!\n");
  232. o->callingpid = 0;
  233. }
  234. } else if (!strcasecmp(line, "endretry") || !strcasecmp(line, "abortretry")) {
  235. o->callingpid = 0;
  236. o->retries++;
  237. } else if (!strcasecmp(line, "delayedretry")) {
  238. } else if (!strcasecmp(line, "setvar") || !strcasecmp(line, "set")) {
  239. char *c2 = c;
  240. strsep(&c2, "=");
  241. if (c2) {
  242. struct ast_variable *var = ast_variable_new(c, c2, o->fn);
  243. if (var) {
  244. /*
  245. * Always insert at the end, because some people
  246. * want to treat the spool file as a script
  247. */
  248. struct ast_variable **tail = &o->vars;
  249. while (*tail) {
  250. tail = &(*tail)->next;
  251. }
  252. *tail = var;
  253. }
  254. } else {
  255. ast_log(LOG_WARNING, "Malformed \"%s\" argument. Should be \"%s: variable=value\"\n", line, line);
  256. }
  257. } else if (!strcasecmp(line, "account")) {
  258. ast_string_field_set(o, account, c);
  259. } else if (!strcasecmp(line, "alwaysdelete")) {
  260. ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ALWAYS_DELETE);
  261. } else if (!strcasecmp(line, "archive")) {
  262. ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_ARCHIVE);
  263. } else if (!strcasecmp(line, "early_media")) {
  264. ast_set2_flag(&o->options, ast_true(c), SPOOL_FLAG_EARLY_MEDIA);
  265. } else {
  266. ast_log(LOG_WARNING, "Unknown keyword '%s' at line %d of %s\n", line, lineno, o->fn);
  267. }
  268. }
  269. #define LINE_BUFFER_SIZE 1024
  270. static int apply_outgoing(struct outgoing *o, FILE *f)
  271. {
  272. char buf[LINE_BUFFER_SIZE];
  273. unsigned int lineno = 0;
  274. while (fgets(buf, sizeof(buf), f)) {
  275. size_t len = strlen(buf);
  276. lineno++;
  277. if (buf[len - 1] == '\n' || feof(f)) {
  278. /* We have a line, parse it */
  279. parse_line(buf, lineno, o);
  280. continue;
  281. }
  282. /* Crazy long line, skip it */
  283. ast_log(LOG_WARNING, "Skipping extremely long line at line %d of %s\n", lineno, o->fn);
  284. /* Consume the rest of the problematic line */
  285. while (fgets(buf, sizeof(buf), f)) {
  286. len = strlen(buf);
  287. if (buf[len - 1] == '\n' || feof(f)) {
  288. break;
  289. }
  290. }
  291. }
  292. if (ast_strlen_zero(o->tech)
  293. || ast_strlen_zero(o->dest)
  294. || (ast_strlen_zero(o->app) && ast_strlen_zero(o->exten))) {
  295. ast_log(LOG_WARNING, "At least one of app or extension must be specified, "
  296. "along with tech and dest in file %s\n", o->fn);
  297. return -1;
  298. }
  299. return 0;
  300. }
  301. static void safe_append(struct outgoing *o, time_t now, char *s)
  302. {
  303. FILE *f;
  304. struct utimbuf tbuf = { .actime = now, .modtime = now + o->retrytime };
  305. ast_debug(1, "Outgoing %s/%s: %s\n", o->tech, o->dest, s);
  306. if ((f = fopen(o->fn, "a"))) {
  307. fprintf(f, "\n%s: %ld %d (%ld)\n", s, (long)ast_mainpid, o->retries, (long) now);
  308. fclose(f);
  309. }
  310. /* Update the file time */
  311. if (utime(o->fn, &tbuf)) {
  312. ast_log(LOG_WARNING, "Unable to set utime on %s: %s\n", o->fn, strerror(errno));
  313. }
  314. }
  315. /*!
  316. * \brief Remove a call file from the outgoing queue optionally moving it in the archive dir
  317. *
  318. * \param o the pointer to outgoing struct
  319. * \param status the exit status of the call. Can be "Completed", "Failed" or "Expired"
  320. */
  321. static int remove_from_queue(struct outgoing *o, const char *status)
  322. {
  323. FILE *f;
  324. char newfn[256];
  325. const char *bname;
  326. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  327. struct direntry *cur;
  328. #endif
  329. if (!ast_test_flag(&o->options, SPOOL_FLAG_ALWAYS_DELETE)) {
  330. struct stat current_file_status;
  331. if (!stat(o->fn, &current_file_status)) {
  332. if (time(NULL) < current_file_status.st_mtime) {
  333. return 0;
  334. }
  335. }
  336. }
  337. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  338. AST_LIST_LOCK(&dirlist);
  339. AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
  340. if (!strcmp(cur->name, o->fn)) {
  341. AST_LIST_REMOVE_CURRENT(list);
  342. ast_free(cur);
  343. break;
  344. }
  345. }
  346. AST_LIST_TRAVERSE_SAFE_END;
  347. AST_LIST_UNLOCK(&dirlist);
  348. #endif
  349. if (!ast_test_flag(&o->options, SPOOL_FLAG_ARCHIVE)) {
  350. unlink(o->fn);
  351. return 0;
  352. }
  353. if (ast_mkdir(qdonedir, 0777)) {
  354. ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool archiving disabled\n", qdonedir);
  355. unlink(o->fn);
  356. return -1;
  357. }
  358. if (!(bname = strrchr(o->fn, '/'))) {
  359. bname = o->fn;
  360. } else {
  361. bname++;
  362. }
  363. snprintf(newfn, sizeof(newfn), "%s/%s", qdonedir, bname);
  364. /* If there is already a call file with the name in the archive dir, it will be overwritten. */
  365. unlink(newfn);
  366. if (rename(o->fn, newfn) != 0) {
  367. unlink(o->fn);
  368. return -1;
  369. }
  370. /* Only append to the file AFTER we move it out of the watched directory,
  371. * otherwise the fclose() causes another event for inotify(7) */
  372. if ((f = fopen(newfn, "a"))) {
  373. fprintf(f, "Status: %s\n", status);
  374. fclose(f);
  375. }
  376. return 0;
  377. }
  378. static void *attempt_thread(void *data)
  379. {
  380. struct outgoing *o = data;
  381. int res, reason;
  382. if (!ast_strlen_zero(o->app)) {
  383. ast_verb(3, "Attempting call on %s/%s for application %s(%s) (Retry %d)\n", o->tech, o->dest, o->app, o->data, o->retries);
  384. res = ast_pbx_outgoing_app(o->tech, o->capabilities, o->dest,
  385. o->waittime * 1000, o->app, o->data, &reason,
  386. AST_OUTGOING_WAIT_COMPLETE, o->cid_num, o->cid_name,
  387. o->vars, o->account, NULL, NULL);
  388. } else {
  389. ast_verb(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);
  390. res = ast_pbx_outgoing_exten(o->tech, o->capabilities, o->dest,
  391. o->waittime * 1000, o->context, o->exten, o->priority, &reason,
  392. AST_OUTGOING_WAIT_COMPLETE, o->cid_num, o->cid_name,
  393. o->vars, o->account, NULL, ast_test_flag(&o->options, SPOOL_FLAG_EARLY_MEDIA),
  394. NULL);
  395. }
  396. if (res) {
  397. ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
  398. if (o->retries >= o->maxretries + 1) {
  399. /* Max retries exceeded */
  400. ast_log(LOG_NOTICE, "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" : "");
  401. remove_from_queue(o, "Expired");
  402. } else {
  403. /* Notate that the call is still active */
  404. safe_append(o, time(NULL), "EndRetry");
  405. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  406. queue_file(o->fn, time(NULL) + o->retrytime);
  407. #endif
  408. }
  409. } else {
  410. ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
  411. remove_from_queue(o, "Completed");
  412. }
  413. free_outgoing(o);
  414. return NULL;
  415. }
  416. static void launch_service(struct outgoing *o)
  417. {
  418. pthread_t t;
  419. int ret;
  420. if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
  421. ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
  422. free_outgoing(o);
  423. }
  424. }
  425. /* Called from scan_thread or queue_file */
  426. static int scan_service(const char *fn, time_t now)
  427. {
  428. struct outgoing *o;
  429. FILE *f;
  430. int res;
  431. o = new_outgoing(fn);
  432. if (!o) {
  433. return -1;
  434. }
  435. /* Attempt to open the file */
  436. f = fopen(o->fn, "r");
  437. if (!f) {
  438. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  439. /*!
  440. * \todo XXX There is some odd delayed duplicate servicing of
  441. * call files going on. We need to suppress the error message
  442. * if the file does not exist as a result.
  443. */
  444. if (errno != ENOENT)
  445. #endif
  446. {
  447. ast_log(LOG_WARNING, "Unable to open %s: '%s'(%d), deleting\n",
  448. o->fn, strerror(errno), (int) errno);
  449. }
  450. remove_from_queue(o, "Failed");
  451. free_outgoing(o);
  452. return -1;
  453. }
  454. /* Read in and verify the contents */
  455. res = apply_outgoing(o, f);
  456. fclose(f);
  457. if (res) {
  458. ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", o->fn);
  459. remove_from_queue(o, "Failed");
  460. free_outgoing(o);
  461. return -1;
  462. }
  463. ast_debug(1, "Filename: %s, Retries: %d, max: %d\n", o->fn, o->retries, o->maxretries);
  464. if (o->retries <= o->maxretries) {
  465. now += o->retrytime;
  466. if (o->callingpid && (o->callingpid == ast_mainpid)) {
  467. safe_append(o, time(NULL), "DelayedRetry");
  468. ast_debug(1, "Delaying retry since we're currently running '%s'\n", o->fn);
  469. free_outgoing(o);
  470. } else {
  471. /* Increment retries */
  472. o->retries++;
  473. /* If someone else was calling, they're presumably gone now
  474. so abort their retry and continue as we were... */
  475. if (o->callingpid)
  476. safe_append(o, time(NULL), "AbortRetry");
  477. safe_append(o, now, "StartRetry");
  478. launch_service(o);
  479. }
  480. return now;
  481. }
  482. ast_log(LOG_NOTICE, "Queued call to %s/%s expired without completion after %d attempt%s\n",
  483. o->tech, o->dest, o->retries - 1, ((o->retries - 1) != 1) ? "s" : "");
  484. remove_from_queue(o, "Expired");
  485. free_outgoing(o);
  486. return 0;
  487. }
  488. #if defined(HAVE_INOTIFY)
  489. /* Only one thread is accessing this list, so no lock is necessary */
  490. static AST_LIST_HEAD_NOLOCK_STATIC(createlist, direntry);
  491. static AST_LIST_HEAD_NOLOCK_STATIC(openlist, direntry);
  492. #endif
  493. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  494. static void queue_file(const char *filename, time_t when)
  495. {
  496. struct stat st;
  497. struct direntry *cur, *new;
  498. int res;
  499. time_t now = time(NULL);
  500. if (!strchr(filename, '/')) {
  501. char *fn = ast_alloca(strlen(qdir) + strlen(filename) + 2);
  502. sprintf(fn, "%s/%s", qdir, filename); /* SAFE */
  503. filename = fn;
  504. }
  505. if (when == 0) {
  506. if (stat(filename, &st)) {
  507. ast_log(LOG_WARNING, "Unable to stat %s: %s\n", filename, strerror(errno));
  508. return;
  509. }
  510. if (!S_ISREG(st.st_mode)) {
  511. return;
  512. }
  513. when = st.st_mtime;
  514. }
  515. /* Need to check the existing list in order to avoid duplicates. */
  516. AST_LIST_LOCK(&dirlist);
  517. AST_LIST_TRAVERSE(&dirlist, cur, list) {
  518. if (cur->mtime == when && !strcmp(filename, cur->name)) {
  519. AST_LIST_UNLOCK(&dirlist);
  520. return;
  521. }
  522. }
  523. if ((res = when) > now || (res = scan_service(filename, now)) > 0) {
  524. if (!(new = ast_calloc(1, sizeof(*new) + strlen(filename) + 1))) {
  525. AST_LIST_UNLOCK(&dirlist);
  526. return;
  527. }
  528. new->mtime = res;
  529. strcpy(new->name, filename);
  530. /* List is ordered by mtime */
  531. if (AST_LIST_EMPTY(&dirlist)) {
  532. AST_LIST_INSERT_HEAD(&dirlist, new, list);
  533. } else {
  534. int found = 0;
  535. AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
  536. if (cur->mtime > new->mtime) {
  537. AST_LIST_INSERT_BEFORE_CURRENT(new, list);
  538. found = 1;
  539. break;
  540. }
  541. }
  542. AST_LIST_TRAVERSE_SAFE_END
  543. if (!found) {
  544. AST_LIST_INSERT_TAIL(&dirlist, new, list);
  545. }
  546. }
  547. }
  548. AST_LIST_UNLOCK(&dirlist);
  549. }
  550. #ifdef HAVE_INOTIFY
  551. static void queue_file_create(const char *filename)
  552. {
  553. struct direntry *cur;
  554. AST_LIST_TRAVERSE(&createlist, cur, list) {
  555. if (!strcmp(cur->name, filename)) {
  556. return;
  557. }
  558. }
  559. if (!(cur = ast_calloc(1, sizeof(*cur) + strlen(filename) + 1))) {
  560. return;
  561. }
  562. strcpy(cur->name, filename);
  563. /* We'll handle this file unless an IN_OPEN event occurs within 2 seconds */
  564. cur->mtime = time(NULL) + 2;
  565. AST_LIST_INSERT_TAIL(&createlist, cur, list);
  566. }
  567. static void queue_file_open(const char *filename)
  568. {
  569. struct direntry *cur;
  570. AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
  571. if (!strcmp(cur->name, filename)) {
  572. AST_LIST_REMOVE_CURRENT(list);
  573. AST_LIST_INSERT_TAIL(&openlist, cur, list);
  574. break;
  575. }
  576. }
  577. AST_LIST_TRAVERSE_SAFE_END
  578. }
  579. static void queue_created_files(void)
  580. {
  581. struct direntry *cur;
  582. time_t now = time(NULL);
  583. AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
  584. if (cur->mtime > now) {
  585. break;
  586. }
  587. AST_LIST_REMOVE_CURRENT(list);
  588. queue_file(cur->name, 0);
  589. ast_free(cur);
  590. }
  591. AST_LIST_TRAVERSE_SAFE_END
  592. }
  593. static void queue_file_write(const char *filename)
  594. {
  595. struct direntry *cur;
  596. /* Only queue entries where an IN_CREATE preceded the IN_CLOSE_WRITE */
  597. AST_LIST_TRAVERSE_SAFE_BEGIN(&openlist, cur, list) {
  598. if (!strcmp(cur->name, filename)) {
  599. AST_LIST_REMOVE_CURRENT(list);
  600. ast_free(cur);
  601. queue_file(filename, 0);
  602. break;
  603. }
  604. }
  605. AST_LIST_TRAVERSE_SAFE_END
  606. }
  607. #endif
  608. static void *scan_thread(void *unused)
  609. {
  610. DIR *dir;
  611. struct dirent *de;
  612. time_t now;
  613. struct timespec ts = { .tv_sec = 1 };
  614. #ifdef HAVE_INOTIFY
  615. ssize_t res;
  616. int inotify_fd = inotify_init();
  617. struct inotify_event *iev;
  618. char buf[8192] __attribute__((aligned (sizeof(int))));
  619. struct pollfd pfd = { .fd = inotify_fd, .events = POLLIN };
  620. #else
  621. struct timespec nowait = { .tv_sec = 0, .tv_nsec = 1 };
  622. int inotify_fd = kqueue();
  623. struct kevent kev;
  624. struct kevent event;
  625. #endif
  626. struct direntry *cur;
  627. while (!ast_fully_booted) {
  628. nanosleep(&ts, NULL);
  629. }
  630. if (inotify_fd < 0) {
  631. ast_log(LOG_ERROR, "Unable to initialize "
  632. #ifdef HAVE_INOTIFY
  633. "inotify(7)"
  634. #else
  635. "kqueue(2)"
  636. #endif
  637. "\n");
  638. return NULL;
  639. }
  640. #ifdef HAVE_INOTIFY
  641. inotify_add_watch(inotify_fd, qdir, IN_CREATE | IN_OPEN | IN_CLOSE_WRITE | IN_MOVED_TO);
  642. #endif
  643. /* First, run through the directory and clear existing entries */
  644. if (!(dir = opendir(qdir))) {
  645. ast_log(LOG_ERROR, "Unable to open directory %s: %s\n", qdir, strerror(errno));
  646. return NULL;
  647. }
  648. #ifndef HAVE_INOTIFY
  649. EV_SET(&kev, dirfd(dir), EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE, 0, NULL);
  650. if (kevent(inotify_fd, &kev, 1, &event, 1, &nowait) < 0 && errno != 0) {
  651. ast_log(LOG_ERROR, "Unable to watch directory %s: %s\n", qdir, strerror(errno));
  652. }
  653. #endif
  654. now = time(NULL);
  655. while ((de = readdir(dir))) {
  656. queue_file(de->d_name, 0);
  657. }
  658. #ifdef HAVE_INOTIFY
  659. /* Directory needs to remain open for kqueue(2) */
  660. closedir(dir);
  661. #endif
  662. /* Wait for either a) next timestamp to occur, or b) a change to happen */
  663. for (;/* ever */;) {
  664. time_t next = AST_LIST_EMPTY(&dirlist) ? INT_MAX : AST_LIST_FIRST(&dirlist)->mtime;
  665. time(&now);
  666. if (next > now) {
  667. #ifdef HAVE_INOTIFY
  668. int stage = 0;
  669. /* Convert from seconds to milliseconds, unless there's nothing
  670. * in the queue already, in which case, we wait forever. */
  671. int waittime = next == INT_MAX ? -1 : (next - now) * 1000;
  672. if (!AST_LIST_EMPTY(&createlist)) {
  673. waittime = 1000;
  674. }
  675. /* When a file arrives, add it to the queue, in mtime order. */
  676. if ((res = poll(&pfd, 1, waittime)) > 0 && (stage = 1) &&
  677. (res = read(inotify_fd, &buf, sizeof(buf))) >= sizeof(*iev)) {
  678. ssize_t len = 0;
  679. /* File(s) added to directory, add them to my list */
  680. for (iev = (void *) buf; res >= sizeof(*iev); iev = (struct inotify_event *) (((char *) iev) + len)) {
  681. /* For an IN_MOVED_TO event, simply process the file. However, if
  682. * we get an IN_CREATE event it *might* be an open(O_CREAT) or it
  683. * might be a hardlink (like smsq does, since rename() might
  684. * overwrite an existing file). So we have to see if we get a
  685. * subsequent IN_OPEN event on the same file. If we do, keep it
  686. * on the openlist and wait for the corresponding IN_CLOSE_WRITE.
  687. * If we *don't* see an IN_OPEN event, then it was a hard link so
  688. * it can be processed immediately.
  689. *
  690. * Unfortunately, although open(O_CREAT) is an atomic file system
  691. * operation, the inotify subsystem doesn't give it to us in a
  692. * single event with both IN_CREATE|IN_OPEN set. It's two separate
  693. * events, and the kernel doesn't even give them to us at the same
  694. * time. We can read() from inotify_fd after the IN_CREATE event,
  695. * and get *nothing* from it. The IN_OPEN arrives only later! So
  696. * we have a very short timeout of 2 seconds. */
  697. if (iev->mask & IN_CREATE) {
  698. queue_file_create(iev->name);
  699. } else if (iev->mask & IN_OPEN) {
  700. queue_file_open(iev->name);
  701. } else if (iev->mask & IN_CLOSE_WRITE) {
  702. queue_file_write(iev->name);
  703. } else if (iev->mask & IN_MOVED_TO) {
  704. queue_file(iev->name, 0);
  705. } else {
  706. ast_log(LOG_ERROR, "Unexpected event %d for file '%s'\n", (int) iev->mask, iev->name);
  707. }
  708. len = sizeof(*iev) + iev->len;
  709. res -= len;
  710. }
  711. } else if (res < 0 && errno != EINTR && errno != EAGAIN) {
  712. ast_debug(1, "Got an error back from %s(2): %s\n", stage ? "read" : "poll", strerror(errno));
  713. }
  714. time(&now);
  715. }
  716. queue_created_files();
  717. #else
  718. int num_events;
  719. /* If queue empty then wait forever */
  720. if (next == INT_MAX) {
  721. num_events = kevent(inotify_fd, &kev, 1, &event, 1, NULL);
  722. } else {
  723. struct timespec ts2 = { .tv_sec = (unsigned long int)(next - now), .tv_nsec = 0 };
  724. num_events = kevent(inotify_fd, &kev, 1, &event, 1, &ts2);
  725. }
  726. if ((num_events < 0) || (event.flags == EV_ERROR)) {
  727. ast_debug(10, "KEvent error %s\n", strerror(errno));
  728. continue;
  729. } else if (num_events == 0) {
  730. /* Interrupt or timeout, restart calculations */
  731. continue;
  732. } else {
  733. /* Directory changed, rescan */
  734. rewinddir(dir);
  735. while ((de = readdir(dir))) {
  736. queue_file(de->d_name, 0);
  737. }
  738. }
  739. time(&now);
  740. }
  741. #endif
  742. /* Empty the list of all entries ready to be processed */
  743. AST_LIST_LOCK(&dirlist);
  744. while (!AST_LIST_EMPTY(&dirlist) && AST_LIST_FIRST(&dirlist)->mtime <= now) {
  745. cur = AST_LIST_REMOVE_HEAD(&dirlist, list);
  746. queue_file(cur->name, cur->mtime);
  747. ast_free(cur);
  748. }
  749. AST_LIST_UNLOCK(&dirlist);
  750. }
  751. return NULL;
  752. }
  753. #else
  754. static void *scan_thread(void *unused)
  755. {
  756. struct stat st;
  757. DIR *dir;
  758. struct dirent *de;
  759. char fn[256];
  760. int res;
  761. int force_poll = 1;
  762. time_t last = 0;
  763. time_t next = 0;
  764. time_t now;
  765. struct timespec ts = { .tv_sec = 1 };
  766. while (!ast_fully_booted) {
  767. nanosleep(&ts, NULL);
  768. }
  769. for (;;) {
  770. /* Wait a sec */
  771. nanosleep(&ts, NULL);
  772. time(&now);
  773. if (stat(qdir, &st)) {
  774. ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
  775. continue;
  776. }
  777. /* Make sure it is time for us to execute our check */
  778. if (!force_poll && st.st_mtime == last && (!next || now < next)) {
  779. /*
  780. * The directory timestamp did not change and any delayed
  781. * call-file is not ready to be executed.
  782. */
  783. continue;
  784. }
  785. #if 0
  786. printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
  787. printf("Ooh, something changed / timeout\n");
  788. #endif
  789. if (!(dir = opendir(qdir))) {
  790. ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
  791. continue;
  792. }
  793. /*
  794. * Since the dir timestamp is available at one second
  795. * resolution, we cannot know if it was updated within the same
  796. * second after we scanned it. Therefore, we will force another
  797. * scan if the dir was just modified.
  798. */
  799. force_poll = (st.st_mtime == now);
  800. next = 0;
  801. last = st.st_mtime;
  802. while ((de = readdir(dir))) {
  803. snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
  804. if (stat(fn, &st)) {
  805. ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
  806. continue;
  807. }
  808. if (!S_ISREG(st.st_mode)) {
  809. /* Not a regular file. */
  810. continue;
  811. }
  812. if (st.st_mtime <= now) {
  813. res = scan_service(fn, now);
  814. if (res > 0) {
  815. /* The call-file is delayed or to be retried later. */
  816. if (!next || res < next) {
  817. /* This delayed call file expires earlier. */
  818. next = res;
  819. }
  820. } else if (res) {
  821. ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
  822. } else if (!next) {
  823. /* Expired entry: must recheck on the next go-around */
  824. next = st.st_mtime;
  825. }
  826. } else {
  827. /* The file's timestamp is in the future. */
  828. if (!next || st.st_mtime < next) {
  829. /* This call-file's timestamp expires earlier. */
  830. next = st.st_mtime;
  831. }
  832. }
  833. }
  834. closedir(dir);
  835. }
  836. return NULL;
  837. }
  838. #endif
  839. static int unload_module(void)
  840. {
  841. return -1;
  842. }
  843. static int load_module(void)
  844. {
  845. pthread_t thread;
  846. int ret;
  847. snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
  848. if (ast_mkdir(qdir, 0777)) {
  849. ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
  850. return AST_MODULE_LOAD_DECLINE;
  851. }
  852. snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
  853. if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
  854. ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
  855. return AST_MODULE_LOAD_FAILURE;
  856. }
  857. return AST_MODULE_LOAD_SUCCESS;
  858. }
  859. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");