pbx_spool.c 26 KB

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