pbx_spool.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. } else {
  345. 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);
  346. res = ast_pbx_outgoing_exten(o->tech, o->capabilities, o->dest,
  347. o->waittime * 1000, o->context, o->exten, o->priority, &reason,
  348. 2 /* wait to finish */, o->cid_num, o->cid_name, o->vars, o->account, NULL,
  349. ast_test_flag(&o->options, SPOOL_FLAG_EARLY_MEDIA), NULL);
  350. }
  351. if (res) {
  352. ast_log(LOG_NOTICE, "Call failed to go through, reason (%d) %s\n", reason, ast_channel_reason2str(reason));
  353. if (o->retries >= o->maxretries + 1) {
  354. /* Max retries exceeded */
  355. 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" : "");
  356. remove_from_queue(o, "Expired");
  357. } else {
  358. /* Notate that the call is still active */
  359. safe_append(o, time(NULL), "EndRetry");
  360. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  361. queue_file(o->fn, time(NULL) + o->retrytime);
  362. #endif
  363. }
  364. } else {
  365. ast_log(LOG_NOTICE, "Call completed to %s/%s\n", o->tech, o->dest);
  366. remove_from_queue(o, "Completed");
  367. }
  368. free_outgoing(o);
  369. return NULL;
  370. }
  371. static void launch_service(struct outgoing *o)
  372. {
  373. pthread_t t;
  374. int ret;
  375. if ((ret = ast_pthread_create_detached(&t, NULL, attempt_thread, o))) {
  376. ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
  377. free_outgoing(o);
  378. }
  379. }
  380. /* Called from scan_thread or queue_file */
  381. static int scan_service(const char *fn, time_t now)
  382. {
  383. struct outgoing *o;
  384. FILE *f;
  385. int res;
  386. o = new_outgoing(fn);
  387. if (!o) {
  388. return -1;
  389. }
  390. /* Attempt to open the file */
  391. f = fopen(o->fn, "r");
  392. if (!f) {
  393. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  394. /*!
  395. * \todo XXX There is some odd delayed duplicate servicing of
  396. * call files going on. We need to suppress the error message
  397. * if the file does not exist as a result.
  398. */
  399. if (errno != ENOENT)
  400. #endif
  401. {
  402. ast_log(LOG_WARNING, "Unable to open %s: '%s'(%d), deleting\n",
  403. o->fn, strerror(errno), (int) errno);
  404. }
  405. remove_from_queue(o, "Failed");
  406. free_outgoing(o);
  407. return -1;
  408. }
  409. /* Read in and verify the contents */
  410. res = apply_outgoing(o, f);
  411. fclose(f);
  412. if (res) {
  413. ast_log(LOG_WARNING, "Invalid file contents in %s, deleting\n", o->fn);
  414. remove_from_queue(o, "Failed");
  415. free_outgoing(o);
  416. return -1;
  417. }
  418. ast_debug(1, "Filename: %s, Retries: %d, max: %d\n", o->fn, o->retries, o->maxretries);
  419. if (o->retries <= o->maxretries) {
  420. now += o->retrytime;
  421. if (o->callingpid && (o->callingpid == ast_mainpid)) {
  422. safe_append(o, time(NULL), "DelayedRetry");
  423. ast_debug(1, "Delaying retry since we're currently running '%s'\n", o->fn);
  424. free_outgoing(o);
  425. } else {
  426. /* Increment retries */
  427. o->retries++;
  428. /* If someone else was calling, they're presumably gone now
  429. so abort their retry and continue as we were... */
  430. if (o->callingpid)
  431. safe_append(o, time(NULL), "AbortRetry");
  432. safe_append(o, now, "StartRetry");
  433. launch_service(o);
  434. }
  435. return now;
  436. }
  437. ast_log(LOG_NOTICE, "Queued call to %s/%s expired without completion after %d attempt%s\n",
  438. o->tech, o->dest, o->retries - 1, ((o->retries - 1) != 1) ? "s" : "");
  439. remove_from_queue(o, "Expired");
  440. free_outgoing(o);
  441. return 0;
  442. }
  443. #if defined(HAVE_INOTIFY) || defined(HAVE_KQUEUE)
  444. struct direntry {
  445. AST_LIST_ENTRY(direntry) list;
  446. time_t mtime;
  447. char name[0];
  448. };
  449. static AST_LIST_HEAD_STATIC(dirlist, direntry);
  450. #if defined(HAVE_INOTIFY)
  451. /* Only one thread is accessing this list, so no lock is necessary */
  452. static AST_LIST_HEAD_NOLOCK_STATIC(createlist, direntry);
  453. static AST_LIST_HEAD_NOLOCK_STATIC(openlist, direntry);
  454. #endif
  455. static void queue_file(const char *filename, time_t when)
  456. {
  457. struct stat st;
  458. struct direntry *cur, *new;
  459. int res;
  460. time_t now = time(NULL);
  461. if (!strchr(filename, '/')) {
  462. char *fn = ast_alloca(strlen(qdir) + strlen(filename) + 2);
  463. sprintf(fn, "%s/%s", qdir, filename); /* SAFE */
  464. filename = fn;
  465. }
  466. if (when == 0) {
  467. if (stat(filename, &st)) {
  468. ast_log(LOG_WARNING, "Unable to stat %s: %s\n", filename, strerror(errno));
  469. return;
  470. }
  471. if (!S_ISREG(st.st_mode)) {
  472. return;
  473. }
  474. when = st.st_mtime;
  475. }
  476. /* Need to check the existing list in order to avoid duplicates. */
  477. AST_LIST_LOCK(&dirlist);
  478. AST_LIST_TRAVERSE(&dirlist, cur, list) {
  479. if (cur->mtime == when && !strcmp(filename, cur->name)) {
  480. AST_LIST_UNLOCK(&dirlist);
  481. return;
  482. }
  483. }
  484. if ((res = when) > now || (res = scan_service(filename, now)) > 0) {
  485. if (!(new = ast_calloc(1, sizeof(*new) + strlen(filename) + 1))) {
  486. AST_LIST_UNLOCK(&dirlist);
  487. return;
  488. }
  489. new->mtime = res;
  490. strcpy(new->name, filename);
  491. /* List is ordered by mtime */
  492. if (AST_LIST_EMPTY(&dirlist)) {
  493. AST_LIST_INSERT_HEAD(&dirlist, new, list);
  494. } else {
  495. int found = 0;
  496. AST_LIST_TRAVERSE_SAFE_BEGIN(&dirlist, cur, list) {
  497. if (cur->mtime > new->mtime) {
  498. AST_LIST_INSERT_BEFORE_CURRENT(new, list);
  499. found = 1;
  500. break;
  501. }
  502. }
  503. AST_LIST_TRAVERSE_SAFE_END
  504. if (!found) {
  505. AST_LIST_INSERT_TAIL(&dirlist, new, list);
  506. }
  507. }
  508. }
  509. AST_LIST_UNLOCK(&dirlist);
  510. }
  511. #ifdef HAVE_INOTIFY
  512. static void queue_file_create(const char *filename)
  513. {
  514. struct direntry *cur;
  515. AST_LIST_TRAVERSE(&createlist, cur, list) {
  516. if (!strcmp(cur->name, filename)) {
  517. return;
  518. }
  519. }
  520. if (!(cur = ast_calloc(1, sizeof(*cur) + strlen(filename) + 1))) {
  521. return;
  522. }
  523. strcpy(cur->name, filename);
  524. /* We'll handle this file unless an IN_OPEN event occurs within 2 seconds */
  525. cur->mtime = time(NULL) + 2;
  526. AST_LIST_INSERT_TAIL(&createlist, cur, list);
  527. }
  528. static void queue_file_open(const char *filename)
  529. {
  530. struct direntry *cur;
  531. AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
  532. if (!strcmp(cur->name, filename)) {
  533. AST_LIST_REMOVE_CURRENT(list);
  534. AST_LIST_INSERT_TAIL(&openlist, cur, list);
  535. break;
  536. }
  537. }
  538. AST_LIST_TRAVERSE_SAFE_END
  539. }
  540. static void queue_created_files(void)
  541. {
  542. struct direntry *cur;
  543. time_t now = time(NULL);
  544. AST_LIST_TRAVERSE_SAFE_BEGIN(&createlist, cur, list) {
  545. if (cur->mtime > now) {
  546. break;
  547. }
  548. AST_LIST_REMOVE_CURRENT(list);
  549. queue_file(cur->name, 0);
  550. ast_free(cur);
  551. }
  552. AST_LIST_TRAVERSE_SAFE_END
  553. }
  554. static void queue_file_write(const char *filename)
  555. {
  556. struct direntry *cur;
  557. /* Only queue entries where an IN_CREATE preceded the IN_CLOSE_WRITE */
  558. AST_LIST_TRAVERSE_SAFE_BEGIN(&openlist, cur, list) {
  559. if (!strcmp(cur->name, filename)) {
  560. AST_LIST_REMOVE_CURRENT(list);
  561. ast_free(cur);
  562. queue_file(filename, 0);
  563. break;
  564. }
  565. }
  566. AST_LIST_TRAVERSE_SAFE_END
  567. }
  568. #endif
  569. static void *scan_thread(void *unused)
  570. {
  571. DIR *dir;
  572. struct dirent *de;
  573. time_t now;
  574. struct timespec ts = { .tv_sec = 1 };
  575. #ifdef HAVE_INOTIFY
  576. ssize_t res;
  577. int inotify_fd = inotify_init();
  578. struct inotify_event *iev;
  579. char buf[8192] __attribute__((aligned (sizeof(int))));
  580. struct pollfd pfd = { .fd = inotify_fd, .events = POLLIN };
  581. #else
  582. struct timespec nowait = { .tv_sec = 0, .tv_nsec = 1 };
  583. int inotify_fd = kqueue();
  584. struct kevent kev;
  585. struct kevent event;
  586. #endif
  587. struct direntry *cur;
  588. while (!ast_fully_booted) {
  589. nanosleep(&ts, NULL);
  590. }
  591. if (inotify_fd < 0) {
  592. ast_log(LOG_ERROR, "Unable to initialize "
  593. #ifdef HAVE_INOTIFY
  594. "inotify(7)"
  595. #else
  596. "kqueue(2)"
  597. #endif
  598. "\n");
  599. return NULL;
  600. }
  601. #ifdef HAVE_INOTIFY
  602. inotify_add_watch(inotify_fd, qdir, IN_CREATE | IN_OPEN | IN_CLOSE_WRITE | IN_MOVED_TO);
  603. #endif
  604. /* First, run through the directory and clear existing entries */
  605. if (!(dir = opendir(qdir))) {
  606. ast_log(LOG_ERROR, "Unable to open directory %s: %s\n", qdir, strerror(errno));
  607. return NULL;
  608. }
  609. #ifndef HAVE_INOTIFY
  610. EV_SET(&kev, dirfd(dir), EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE, 0, NULL);
  611. if (kevent(inotify_fd, &kev, 1, &event, 1, &nowait) < 0 && errno != 0) {
  612. ast_log(LOG_ERROR, "Unable to watch directory %s: %s\n", qdir, strerror(errno));
  613. }
  614. #endif
  615. now = time(NULL);
  616. while ((de = readdir(dir))) {
  617. queue_file(de->d_name, 0);
  618. }
  619. #ifdef HAVE_INOTIFY
  620. /* Directory needs to remain open for kqueue(2) */
  621. closedir(dir);
  622. #endif
  623. /* Wait for either a) next timestamp to occur, or b) a change to happen */
  624. for (;/* ever */;) {
  625. time_t next = AST_LIST_EMPTY(&dirlist) ? INT_MAX : AST_LIST_FIRST(&dirlist)->mtime;
  626. time(&now);
  627. if (next > now) {
  628. #ifdef HAVE_INOTIFY
  629. int stage = 0;
  630. /* Convert from seconds to milliseconds, unless there's nothing
  631. * in the queue already, in which case, we wait forever. */
  632. int waittime = next == INT_MAX ? -1 : (next - now) * 1000;
  633. if (!AST_LIST_EMPTY(&createlist)) {
  634. waittime = 1000;
  635. }
  636. /* When a file arrives, add it to the queue, in mtime order. */
  637. if ((res = poll(&pfd, 1, waittime)) > 0 && (stage = 1) &&
  638. (res = read(inotify_fd, &buf, sizeof(buf))) >= sizeof(*iev)) {
  639. ssize_t len = 0;
  640. /* File(s) added to directory, add them to my list */
  641. for (iev = (void *) buf; res >= sizeof(*iev); iev = (struct inotify_event *) (((char *) iev) + len)) {
  642. /* For an IN_MOVED_TO event, simply process the file. However, if
  643. * we get an IN_CREATE event it *might* be an open(O_CREAT) or it
  644. * might be a hardlink (like smsq does, since rename() might
  645. * overwrite an existing file). So we have to see if we get a
  646. * subsequent IN_OPEN event on the same file. If we do, keep it
  647. * on the openlist and wait for the corresponding IN_CLOSE_WRITE.
  648. * If we *don't* see an IN_OPEN event, then it was a hard link so
  649. * it can be processed immediately.
  650. *
  651. * Unfortunately, although open(O_CREAT) is an atomic file system
  652. * operation, the inotify subsystem doesn't give it to us in a
  653. * single event with both IN_CREATE|IN_OPEN set. It's two separate
  654. * events, and the kernel doesn't even give them to us at the same
  655. * time. We can read() from inotify_fd after the IN_CREATE event,
  656. * and get *nothing* from it. The IN_OPEN arrives only later! So
  657. * we have a very short timeout of 2 seconds. */
  658. if (iev->mask & IN_CREATE) {
  659. queue_file_create(iev->name);
  660. } else if (iev->mask & IN_OPEN) {
  661. queue_file_open(iev->name);
  662. } else if (iev->mask & IN_CLOSE_WRITE) {
  663. queue_file_write(iev->name);
  664. } else if (iev->mask & IN_MOVED_TO) {
  665. queue_file(iev->name, 0);
  666. } else {
  667. ast_log(LOG_ERROR, "Unexpected event %d for file '%s'\n", (int) iev->mask, iev->name);
  668. }
  669. len = sizeof(*iev) + iev->len;
  670. res -= len;
  671. }
  672. } else if (res < 0 && errno != EINTR && errno != EAGAIN) {
  673. ast_debug(1, "Got an error back from %s(2): %s\n", stage ? "read" : "poll", strerror(errno));
  674. }
  675. time(&now);
  676. }
  677. queue_created_files();
  678. #else
  679. int num_events;
  680. /* If queue empty then wait forever */
  681. if (next == INT_MAX) {
  682. num_events = kevent(inotify_fd, &kev, 1, &event, 1, NULL);
  683. } else {
  684. struct timespec ts2 = { .tv_sec = (unsigned long int)(next - now), .tv_nsec = 0 };
  685. num_events = kevent(inotify_fd, &kev, 1, &event, 1, &ts2);
  686. }
  687. if ((num_events < 0) || (event.flags == EV_ERROR)) {
  688. ast_debug(10, "KEvent error %s\n", strerror(errno));
  689. continue;
  690. } else if (num_events == 0) {
  691. /* Interrupt or timeout, restart calculations */
  692. continue;
  693. } else {
  694. /* Directory changed, rescan */
  695. rewinddir(dir);
  696. while ((de = readdir(dir))) {
  697. queue_file(de->d_name, 0);
  698. }
  699. }
  700. time(&now);
  701. }
  702. #endif
  703. /* Empty the list of all entries ready to be processed */
  704. AST_LIST_LOCK(&dirlist);
  705. while (!AST_LIST_EMPTY(&dirlist) && AST_LIST_FIRST(&dirlist)->mtime <= now) {
  706. cur = AST_LIST_REMOVE_HEAD(&dirlist, list);
  707. queue_file(cur->name, cur->mtime);
  708. ast_free(cur);
  709. }
  710. AST_LIST_UNLOCK(&dirlist);
  711. }
  712. return NULL;
  713. }
  714. #else
  715. static void *scan_thread(void *unused)
  716. {
  717. struct stat st;
  718. DIR *dir;
  719. struct dirent *de;
  720. char fn[256];
  721. int res;
  722. int force_poll = 1;
  723. time_t last = 0;
  724. time_t next = 0;
  725. time_t now;
  726. struct timespec ts = { .tv_sec = 1 };
  727. while (!ast_fully_booted) {
  728. nanosleep(&ts, NULL);
  729. }
  730. for (;;) {
  731. /* Wait a sec */
  732. nanosleep(&ts, NULL);
  733. time(&now);
  734. if (stat(qdir, &st)) {
  735. ast_log(LOG_WARNING, "Unable to stat %s\n", qdir);
  736. continue;
  737. }
  738. /* Make sure it is time for us to execute our check */
  739. if (!force_poll && st.st_mtime == last && (!next || now < next)) {
  740. /*
  741. * The directory timestamp did not change and any delayed
  742. * call-file is not ready to be executed.
  743. */
  744. continue;
  745. }
  746. #if 0
  747. printf("atime: %ld, mtime: %ld, ctime: %ld\n", st.st_atime, st.st_mtime, st.st_ctime);
  748. printf("Ooh, something changed / timeout\n");
  749. #endif
  750. if (!(dir = opendir(qdir))) {
  751. ast_log(LOG_WARNING, "Unable to open directory %s: %s\n", qdir, strerror(errno));
  752. continue;
  753. }
  754. /*
  755. * Since the dir timestamp is available at one second
  756. * resolution, we cannot know if it was updated within the same
  757. * second after we scanned it. Therefore, we will force another
  758. * scan if the dir was just modified.
  759. */
  760. force_poll = (st.st_mtime == now);
  761. next = 0;
  762. last = st.st_mtime;
  763. while ((de = readdir(dir))) {
  764. snprintf(fn, sizeof(fn), "%s/%s", qdir, de->d_name);
  765. if (stat(fn, &st)) {
  766. ast_log(LOG_WARNING, "Unable to stat %s: %s\n", fn, strerror(errno));
  767. continue;
  768. }
  769. if (!S_ISREG(st.st_mode)) {
  770. /* Not a regular file. */
  771. continue;
  772. }
  773. if (st.st_mtime <= now) {
  774. res = scan_service(fn, now);
  775. if (res > 0) {
  776. /* The call-file is delayed or to be retried later. */
  777. if (!next || res < next) {
  778. /* This delayed call file expires earlier. */
  779. next = res;
  780. }
  781. } else if (res) {
  782. ast_log(LOG_WARNING, "Failed to scan service '%s'\n", fn);
  783. } else if (!next) {
  784. /* Expired entry: must recheck on the next go-around */
  785. next = st.st_mtime;
  786. }
  787. } else {
  788. /* The file's timestamp is in the future. */
  789. if (!next || st.st_mtime < next) {
  790. /* This call-file's timestamp expires earlier. */
  791. next = st.st_mtime;
  792. }
  793. }
  794. }
  795. closedir(dir);
  796. }
  797. return NULL;
  798. }
  799. #endif
  800. static int unload_module(void)
  801. {
  802. return -1;
  803. }
  804. static int load_module(void)
  805. {
  806. pthread_t thread;
  807. int ret;
  808. snprintf(qdir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing");
  809. if (ast_mkdir(qdir, 0777)) {
  810. ast_log(LOG_WARNING, "Unable to create queue directory %s -- outgoing spool disabled\n", qdir);
  811. return AST_MODULE_LOAD_DECLINE;
  812. }
  813. snprintf(qdonedir, sizeof(qdir), "%s/%s", ast_config_AST_SPOOL_DIR, "outgoing_done");
  814. if ((ret = ast_pthread_create_detached_background(&thread, NULL, scan_thread, NULL))) {
  815. ast_log(LOG_WARNING, "Unable to create thread :( (returned error: %d)\n", ret);
  816. return AST_MODULE_LOAD_FAILURE;
  817. }
  818. return AST_MODULE_LOAD_SUCCESS;
  819. }
  820. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Outgoing Spool Support");