file.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, 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 Generic File Format Support.
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /*** MODULEINFO
  25. <support_level>core</support_level>
  26. ***/
  27. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <dirent.h>
  30. #include <sys/stat.h>
  31. #include <sys/wait.h>
  32. #include <math.h>
  33. #include "asterisk/_private.h" /* declare ast_file_init() */
  34. #include "asterisk/paths.h" /* use ast_config_AST_DATA_DIR */
  35. #include "asterisk/mod_format.h"
  36. #include "asterisk/cli.h"
  37. #include "asterisk/channel.h"
  38. #include "asterisk/sched.h"
  39. #include "asterisk/translate.h"
  40. #include "asterisk/utils.h"
  41. #include "asterisk/lock.h"
  42. #include "asterisk/app.h"
  43. #include "asterisk/pbx.h"
  44. #include "asterisk/linkedlists.h"
  45. #include "asterisk/module.h"
  46. #include "asterisk/astobj2.h"
  47. #include "asterisk/test.h"
  48. /*! \brief
  49. * The following variable controls the layout of localized sound files.
  50. * If 0, use the historical layout with prefix just before the filename
  51. * (i.e. digits/en/1.gsm , digits/it/1.gsm or default to digits/1.gsm),
  52. * if 1 put the prefix at the beginning of the filename
  53. * (i.e. en/digits/1.gsm, it/digits/1.gsm or default to digits/1.gsm).
  54. * The latter permits a language to be entirely in one directory.
  55. *
  56. * This is settable in asterisk.conf.
  57. */
  58. int ast_language_is_prefix = 1;
  59. static AST_RWLIST_HEAD_STATIC(formats, ast_format_def);
  60. int __ast_format_def_register(const struct ast_format_def *f, struct ast_module *mod)
  61. {
  62. struct ast_format_def *tmp;
  63. AST_RWLIST_WRLOCK(&formats);
  64. AST_RWLIST_TRAVERSE(&formats, tmp, list) {
  65. if (!strcasecmp(f->name, tmp->name)) {
  66. AST_RWLIST_UNLOCK(&formats);
  67. ast_log(LOG_WARNING, "Tried to register '%s' format, already registered\n", f->name);
  68. return -1;
  69. }
  70. }
  71. if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
  72. AST_RWLIST_UNLOCK(&formats);
  73. return -1;
  74. }
  75. *tmp = *f;
  76. tmp->module = mod;
  77. if (tmp->buf_size) {
  78. /*
  79. * Align buf_size properly, rounding up to the machine-specific
  80. * alignment for pointers.
  81. */
  82. struct _test_align { void *a, *b; } p;
  83. int align = (char *)&p.b - (char *)&p.a;
  84. tmp->buf_size = ((f->buf_size + align - 1) / align) * align;
  85. }
  86. memset(&tmp->list, 0, sizeof(tmp->list));
  87. AST_RWLIST_INSERT_HEAD(&formats, tmp, list);
  88. AST_RWLIST_UNLOCK(&formats);
  89. ast_verb(2, "Registered file format %s, extension(s) %s\n", f->name, f->exts);
  90. return 0;
  91. }
  92. int ast_format_def_unregister(const char *name)
  93. {
  94. struct ast_format_def *tmp;
  95. int res = -1;
  96. AST_RWLIST_WRLOCK(&formats);
  97. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&formats, tmp, list) {
  98. if (!strcasecmp(name, tmp->name)) {
  99. AST_RWLIST_REMOVE_CURRENT(list);
  100. ast_free(tmp);
  101. res = 0;
  102. }
  103. }
  104. AST_RWLIST_TRAVERSE_SAFE_END;
  105. AST_RWLIST_UNLOCK(&formats);
  106. if (!res)
  107. ast_verb(2, "Unregistered format %s\n", name);
  108. else
  109. ast_log(LOG_WARNING, "Tried to unregister format %s, already unregistered\n", name);
  110. return res;
  111. }
  112. int ast_stopstream(struct ast_channel *tmp)
  113. {
  114. ast_channel_lock(tmp);
  115. /* Stop a running stream if there is one */
  116. if (ast_channel_stream(tmp)) {
  117. ast_closestream(ast_channel_stream(tmp));
  118. ast_channel_stream_set(tmp, NULL);
  119. if (ast_channel_oldwriteformat(tmp)->id && ast_set_write_format(tmp, ast_channel_oldwriteformat(tmp)))
  120. ast_log(LOG_WARNING, "Unable to restore format back to %s\n", ast_getformatname(ast_channel_oldwriteformat(tmp)));
  121. }
  122. /* Stop the video stream too */
  123. if (ast_channel_vstream(tmp) != NULL) {
  124. ast_closestream(ast_channel_vstream(tmp));
  125. ast_channel_vstream_set(tmp, NULL);
  126. }
  127. ast_channel_unlock(tmp);
  128. return 0;
  129. }
  130. int ast_writestream(struct ast_filestream *fs, struct ast_frame *f)
  131. {
  132. int res = -1;
  133. if (f->frametype == AST_FRAME_VIDEO) {
  134. if (AST_FORMAT_GET_TYPE(fs->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
  135. /* This is the audio portion. Call the video one... */
  136. if (!fs->vfs && fs->filename) {
  137. const char *type = ast_getformatname(&f->subclass.format);
  138. fs->vfs = ast_writefile(fs->filename, type, NULL, fs->flags, 0, fs->mode);
  139. ast_debug(1, "Opened video output file\n");
  140. }
  141. if (fs->vfs)
  142. return ast_writestream(fs->vfs, f);
  143. /* else ignore */
  144. return 0;
  145. }
  146. } else if (f->frametype != AST_FRAME_VOICE) {
  147. ast_log(LOG_WARNING, "Tried to write non-voice frame\n");
  148. return -1;
  149. }
  150. if (ast_format_cmp(&f->subclass.format, &fs->fmt->format) != AST_FORMAT_CMP_NOT_EQUAL) {
  151. res = fs->fmt->write(fs, f);
  152. if (res < 0)
  153. ast_log(LOG_WARNING, "Natural write failed\n");
  154. else if (res > 0)
  155. ast_log(LOG_WARNING, "Huh??\n");
  156. } else {
  157. /* XXX If they try to send us a type of frame that isn't the normal frame, and isn't
  158. the one we've setup a translator for, we do the "wrong thing" XXX */
  159. if (fs->trans && (ast_format_cmp(&f->subclass.format, &fs->lastwriteformat) != AST_FORMAT_CMP_EQUAL)) {
  160. ast_translator_free_path(fs->trans);
  161. fs->trans = NULL;
  162. }
  163. if (!fs->trans)
  164. fs->trans = ast_translator_build_path(&fs->fmt->format, &f->subclass.format);
  165. if (!fs->trans)
  166. ast_log(LOG_WARNING, "Unable to translate to format %s, source format %s\n",
  167. fs->fmt->name, ast_getformatname(&f->subclass.format));
  168. else {
  169. struct ast_frame *trf;
  170. ast_format_copy(&fs->lastwriteformat, &f->subclass.format);
  171. /* Get the translated frame but don't consume the original in case they're using it on another stream */
  172. if ((trf = ast_translate(fs->trans, f, 0))) {
  173. struct ast_frame *cur;
  174. /* the translator may have returned multiple frames, so process them */
  175. for (cur = trf; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
  176. if ((res = fs->fmt->write(fs, trf))) {
  177. ast_log(LOG_WARNING, "Translated frame write failed\n");
  178. break;
  179. }
  180. }
  181. ast_frfree(trf);
  182. } else {
  183. res = 0;
  184. }
  185. }
  186. }
  187. return res;
  188. }
  189. static int copy(const char *infile, const char *outfile)
  190. {
  191. int ifd, ofd, len;
  192. char buf[4096]; /* XXX make it lerger. */
  193. if ((ifd = open(infile, O_RDONLY)) < 0) {
  194. ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile);
  195. return -1;
  196. }
  197. if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, AST_FILE_MODE)) < 0) {
  198. ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile);
  199. close(ifd);
  200. return -1;
  201. }
  202. while ( (len = read(ifd, buf, sizeof(buf)) ) ) {
  203. int res;
  204. if (len < 0) {
  205. ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
  206. break;
  207. }
  208. /* XXX handle partial writes */
  209. res = write(ofd, buf, len);
  210. if (res != len) {
  211. ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
  212. len = -1; /* error marker */
  213. break;
  214. }
  215. }
  216. close(ifd);
  217. close(ofd);
  218. if (len < 0) {
  219. unlink(outfile);
  220. return -1; /* error */
  221. }
  222. return 0; /* success */
  223. }
  224. /*!
  225. * \brief construct a filename. Absolute pathnames are preserved,
  226. * relative names are prefixed by the sounds/ directory.
  227. * The wav49 suffix is replaced by 'WAV'.
  228. * Returns a malloc'ed string to be freed by the caller.
  229. */
  230. static char *build_filename(const char *filename, const char *ext)
  231. {
  232. char *fn = NULL;
  233. if (!strcmp(ext, "wav49"))
  234. ext = "WAV";
  235. if (filename[0] == '/') {
  236. if (ast_asprintf(&fn, "%s.%s", filename, ext) < 0) {
  237. fn = NULL;
  238. }
  239. } else {
  240. if (ast_asprintf(&fn, "%s/sounds/%s.%s",
  241. ast_config_AST_DATA_DIR, filename, ext) < 0) {
  242. fn = NULL;
  243. }
  244. }
  245. return fn;
  246. }
  247. /* compare type against the list 'exts' */
  248. /* XXX need a better algorithm */
  249. static int exts_compare(const char *exts, const char *type)
  250. {
  251. char tmp[256];
  252. char *stringp = tmp, *ext;
  253. ast_copy_string(tmp, exts, sizeof(tmp));
  254. while ((ext = strsep(&stringp, "|"))) {
  255. if (!strcmp(ext, type))
  256. return 1;
  257. }
  258. return 0;
  259. }
  260. /*! \internal \brief Close the file stream by canceling any pending read / write callbacks */
  261. static void filestream_close(struct ast_filestream *f)
  262. {
  263. enum ast_format_type format_type = AST_FORMAT_GET_TYPE(f->fmt->format.id);
  264. if (!f->owner) {
  265. return;
  266. }
  267. /* Stop a running stream if there is one */
  268. switch (format_type)
  269. {
  270. case AST_FORMAT_TYPE_AUDIO:
  271. ast_channel_stream_set(f->owner, NULL);
  272. AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_streamid, ast_channel_streamid_set);
  273. ast_settimeout(f->owner, 0, NULL, NULL);
  274. break;
  275. case AST_FORMAT_TYPE_VIDEO:
  276. ast_channel_vstream_set(f->owner, NULL);
  277. AST_SCHED_DEL_ACCESSOR(ast_channel_sched(f->owner), f->owner, ast_channel_vstreamid, ast_channel_vstreamid_set);
  278. break;
  279. default:
  280. ast_log(AST_LOG_WARNING, "Unable to schedule deletion of filestream with unsupported type %s\n", f->fmt->name);
  281. break;
  282. }
  283. }
  284. static void filestream_destructor(void *arg)
  285. {
  286. struct ast_filestream *f = arg;
  287. int status;
  288. int pid = -1;
  289. /* Stop a running stream if there is one */
  290. filestream_close(f);
  291. /* destroy the translator on exit */
  292. if (f->trans)
  293. ast_translator_free_path(f->trans);
  294. if (f->fmt->close) {
  295. void (*closefn)(struct ast_filestream *) = f->fmt->close;
  296. closefn(f);
  297. }
  298. if (f->f) {
  299. fclose(f->f);
  300. }
  301. if (f->realfilename && f->filename) {
  302. pid = ast_safe_fork(0);
  303. if (!pid) {
  304. execl("/bin/mv", "mv", "-f", f->filename, f->realfilename, SENTINEL);
  305. _exit(1);
  306. }
  307. else if (pid > 0) {
  308. /* Block the parent until the move is complete.*/
  309. waitpid(pid, &status, 0);
  310. }
  311. }
  312. if (f->filename)
  313. free(f->filename);
  314. if (f->realfilename)
  315. free(f->realfilename);
  316. if (f->vfs)
  317. ast_closestream(f->vfs);
  318. if (f->write_buffer) {
  319. ast_free(f->write_buffer);
  320. }
  321. if (f->orig_chan_name)
  322. free((void *) f->orig_chan_name);
  323. ast_module_unref(f->fmt->module);
  324. }
  325. static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
  326. {
  327. struct ast_filestream *s;
  328. int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
  329. if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
  330. return NULL;
  331. ast_module_ref(fmt->module);
  332. s->fmt = fmt;
  333. s->f = bfile;
  334. if (fmt->desc_size)
  335. s->_private = ((char *)(s + 1)) + fmt->buf_size;
  336. if (fmt->buf_size)
  337. s->buf = (char *)(s + 1);
  338. s->fr.src = fmt->name;
  339. return s;
  340. }
  341. /*
  342. * Default implementations of open and rewrite.
  343. * Only use them if you don't have expensive stuff to do.
  344. */
  345. enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
  346. static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
  347. {
  348. struct ast_format_def *f = s->fmt;
  349. int ret = -1;
  350. int (*openfn)(struct ast_filestream *s);
  351. if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
  352. ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
  353. else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
  354. ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
  355. else {
  356. /* preliminary checks succeed. */
  357. ret = 0;
  358. }
  359. return ret;
  360. }
  361. static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
  362. {
  363. return fn_wrapper(s, comment, WRAP_REWRITE);
  364. }
  365. static int open_wrapper(struct ast_filestream *s)
  366. {
  367. return fn_wrapper(s, NULL, WRAP_OPEN);
  368. }
  369. enum file_action {
  370. ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
  371. ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
  372. ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
  373. ACTION_OPEN,
  374. ACTION_COPY /* copy file. return 0 on success, -1 on error */
  375. };
  376. /*!
  377. * \internal
  378. * \brief perform various actions on a file. Second argument
  379. * \note arg2 depends on the command:
  380. * unused for DELETE
  381. * optional ast_format_cap holding all the formats found for a file, for EXISTS.
  382. * destination file name (const char *) for COPY and RENAME
  383. * struct ast_channel * for OPEN
  384. * if fmt is NULL, OPEN will return the first matching entry,
  385. * whereas other functions will run on all matching entries.
  386. */
  387. static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
  388. {
  389. struct ast_format_def *f;
  390. int res = (action == ACTION_EXISTS) ? 0 : -1;
  391. AST_RWLIST_RDLOCK(&formats);
  392. /* Check for a specific format */
  393. AST_RWLIST_TRAVERSE(&formats, f, list) {
  394. char *stringp, *ext = NULL;
  395. if (fmt && !exts_compare(f->exts, fmt))
  396. continue;
  397. /* Look for a file matching the supported extensions.
  398. * The file must exist, and for OPEN, must match
  399. * one of the formats supported by the channel.
  400. */
  401. stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
  402. while ( (ext = strsep(&stringp, "|")) ) {
  403. struct stat st;
  404. char *fn = build_filename(filename, ext);
  405. if (fn == NULL)
  406. continue;
  407. if ( stat(fn, &st) ) { /* file not existent */
  408. ast_free(fn);
  409. continue;
  410. }
  411. /* for 'OPEN' we need to be sure that the format matches
  412. * what the channel can process
  413. */
  414. if (action == ACTION_OPEN) {
  415. struct ast_channel *chan = (struct ast_channel *)arg2;
  416. FILE *bfile;
  417. struct ast_filestream *s;
  418. if ((ast_format_cmp(ast_channel_writeformat(chan), &f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
  419. !(((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_AUDIO) && fmt) ||
  420. ((AST_FORMAT_GET_TYPE(f->format.id) == AST_FORMAT_TYPE_VIDEO) && fmt))) {
  421. ast_free(fn);
  422. continue; /* not a supported format */
  423. }
  424. if ( (bfile = fopen(fn, "r")) == NULL) {
  425. ast_free(fn);
  426. continue; /* cannot open file */
  427. }
  428. s = get_filestream(f, bfile);
  429. if (!s) {
  430. fclose(bfile);
  431. ast_free(fn); /* cannot allocate descriptor */
  432. continue;
  433. }
  434. if (open_wrapper(s)) {
  435. ast_free(fn);
  436. ast_closestream(s);
  437. continue; /* cannot run open on file */
  438. }
  439. if (st.st_size == 0) {
  440. ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
  441. }
  442. /* ok this is good for OPEN */
  443. res = 1; /* found */
  444. s->lasttimeout = -1;
  445. s->fmt = f;
  446. s->trans = NULL;
  447. s->filename = NULL;
  448. if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO) {
  449. if (ast_channel_stream(chan))
  450. ast_closestream(ast_channel_stream(chan));
  451. ast_channel_stream_set(chan, s);
  452. } else {
  453. if (ast_channel_vstream(chan))
  454. ast_closestream(ast_channel_vstream(chan));
  455. ast_channel_vstream_set(chan, s);
  456. }
  457. ast_free(fn);
  458. break;
  459. }
  460. switch (action) {
  461. case ACTION_OPEN:
  462. break; /* will never get here */
  463. case ACTION_EXISTS: /* return the matching format */
  464. /* if arg2 is present, it is a format capabilities structure.
  465. * Add this format to the set of formats this file can be played in */
  466. if (arg2) {
  467. ast_format_cap_add((struct ast_format_cap *) arg2, &f->format);
  468. }
  469. res = 1; /* file does exist and format it exists in is returned in arg2 */
  470. break;
  471. case ACTION_DELETE:
  472. if ( (res = unlink(fn)) )
  473. ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
  474. break;
  475. case ACTION_RENAME:
  476. case ACTION_COPY: {
  477. char *nfn = build_filename((const char *)arg2, ext);
  478. if (!nfn)
  479. ast_log(LOG_WARNING, "Out of memory\n");
  480. else {
  481. res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
  482. if (res)
  483. ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
  484. action == ACTION_COPY ? "copy" : "rename",
  485. fn, nfn, strerror(errno));
  486. ast_free(nfn);
  487. }
  488. }
  489. break;
  490. default:
  491. ast_log(LOG_WARNING, "Unknown helper %u\n", action);
  492. }
  493. ast_free(fn);
  494. }
  495. }
  496. AST_RWLIST_UNLOCK(&formats);
  497. return res;
  498. }
  499. static int is_absolute_path(const char *filename)
  500. {
  501. return filename[0] == '/';
  502. }
  503. /*!
  504. * \brief test if a file exists for a given format.
  505. * \note result_cap is OPTIONAL
  506. * \retval 1, true and result_cap represents format capabilities file exists in.
  507. * \retval 0, false
  508. */
  509. static int fileexists_test(const char *filename, const char *fmt, const char *lang,
  510. char *buf, int buflen, struct ast_format_cap *result_cap)
  511. {
  512. if (buf == NULL) {
  513. return 0;
  514. }
  515. if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
  516. if (lang) {
  517. snprintf(buf, buflen, "%s/%s", lang, filename);
  518. } else {
  519. snprintf(buf, buflen, "%s", filename);
  520. }
  521. } else { /* old layout */
  522. strcpy(buf, filename); /* first copy the full string */
  523. if (lang) {
  524. /* insert the language and suffix if needed */
  525. const char *c = strrchr(filename, '/');
  526. int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
  527. snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
  528. }
  529. }
  530. return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
  531. }
  532. /*!
  533. * \brief helper routine to locate a file with a given format
  534. * and language preference.
  535. *
  536. * \note Try preflang, preflang with stripped '_' suffices, or NULL.
  537. *
  538. * \note The last parameter(s) point to a buffer of sufficient size,
  539. * which on success is filled with the matching filename.
  540. *
  541. * \param filename, name of the file.
  542. * \param fmt, format to look for the file in. OPTIONAL
  543. * \param preflang, the perfered language
  544. * \param buf, returns the matching filename
  545. * \param buflen, size of the buf
  546. * \param result_cap, OPTIONAL format capabilities result structure
  547. * returns what formats the file was found in.
  548. *
  549. * \retval 1, true. file exists and result format is set
  550. * \retval 0, false. file does not exist.
  551. */
  552. static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
  553. char *buf, int buflen, struct ast_format_cap *result_cap)
  554. {
  555. char *lang;
  556. if (buf == NULL) {
  557. return 0;
  558. }
  559. /* We try languages in the following order:
  560. * preflang (may include dialect and style codes)
  561. * lang (preflang without dialect - if any)
  562. * <none>
  563. * default (unless the same as preflang or lang without dialect)
  564. */
  565. lang = ast_strdupa(preflang);
  566. /* Try preferred language, including removing any style or dialect codes */
  567. while (!ast_strlen_zero(lang)) {
  568. char *end;
  569. if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
  570. return 1;
  571. }
  572. if ((end = strrchr(lang, '_')) != NULL) {
  573. *end = '\0';
  574. continue;
  575. }
  576. break;
  577. }
  578. /* Try without any language */
  579. if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
  580. return 1;
  581. }
  582. /* Finally try the default language unless it was already tried before */
  583. if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
  584. if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
  585. return 1;
  586. }
  587. }
  588. return 0;
  589. }
  590. struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
  591. {
  592. return ast_openstream_full(chan, filename, preflang, 0);
  593. }
  594. struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
  595. {
  596. /*
  597. * Use fileexists_core() to find a file in a compatible
  598. * language and format, set up a suitable translator,
  599. * and open the stream.
  600. */
  601. struct ast_format_cap *file_fmt_cap;
  602. int res;
  603. int buflen;
  604. char *buf;
  605. if (!asis) {
  606. /* do this first, otherwise we detect the wrong writeformat */
  607. ast_stopstream(chan);
  608. if (ast_channel_generator(chan))
  609. ast_deactivate_generator(chan);
  610. }
  611. if (preflang == NULL)
  612. preflang = "";
  613. buflen = strlen(preflang) + strlen(filename) + 4;
  614. buf = ast_alloca(buflen);
  615. if (!(file_fmt_cap = ast_format_cap_alloc_nolock())) {
  616. return NULL;
  617. }
  618. if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
  619. !ast_format_cap_has_type(file_fmt_cap, AST_FORMAT_TYPE_AUDIO)) {
  620. ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
  621. file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
  622. return NULL;
  623. }
  624. /* Set the channel to a format we can work with and save off the previous format. */
  625. ast_format_copy(ast_channel_oldwriteformat(chan), ast_channel_writeformat(chan));
  626. /* Set the channel to the best format that exists for the file. */
  627. res = ast_set_write_format_from_cap(chan, file_fmt_cap);
  628. /* don't need this anymore now that the channel's write format is set. */
  629. file_fmt_cap = ast_format_cap_destroy(file_fmt_cap);
  630. if (res == -1) { /* No format available that works with this channel */
  631. return NULL;
  632. }
  633. res = filehelper(buf, chan, NULL, ACTION_OPEN);
  634. if (res >= 0)
  635. return ast_channel_stream(chan);
  636. return NULL;
  637. }
  638. struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
  639. {
  640. /* As above, but for video. But here we don't have translators
  641. * so we must enforce a format.
  642. */
  643. struct ast_format tmp_fmt;
  644. struct ast_format_cap *tmp_cap;
  645. char *buf;
  646. int buflen;
  647. const char *fmt;
  648. int fd;
  649. if (preflang == NULL)
  650. preflang = "";
  651. buflen = strlen(preflang) + strlen(filename) + 4;
  652. buf = ast_alloca(buflen);
  653. /* is the channel capable of video without translation ?*/
  654. if (!ast_format_cap_has_type(ast_channel_nativeformats(chan), AST_FORMAT_TYPE_VIDEO)) {
  655. return NULL;
  656. }
  657. if (!(tmp_cap = ast_format_cap_alloc_nolock())) {
  658. return NULL;
  659. }
  660. /* Video is supported, so see what video formats exist for this file */
  661. if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
  662. tmp_cap = ast_format_cap_destroy(tmp_cap);
  663. return NULL;
  664. }
  665. /* iterate over file formats and pick the first one compatible with the channel's native formats */
  666. ast_format_cap_iter_start(tmp_cap);
  667. while (!ast_format_cap_iter_next(tmp_cap, &tmp_fmt)) {
  668. fmt = ast_getformatname(&tmp_fmt);
  669. if ((AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_VIDEO) ||
  670. !ast_format_cap_iscompatible(ast_channel_nativeformats(chan), &tmp_fmt)) {
  671. continue;
  672. }
  673. fd = filehelper(buf, chan, fmt, ACTION_OPEN);
  674. if (fd >= 0) {
  675. ast_format_cap_iter_end(tmp_cap);
  676. tmp_cap = ast_format_cap_destroy(tmp_cap);
  677. return ast_channel_vstream(chan);
  678. }
  679. ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
  680. }
  681. ast_format_cap_iter_end(tmp_cap);
  682. tmp_cap = ast_format_cap_destroy(tmp_cap);
  683. return NULL;
  684. }
  685. static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
  686. {
  687. struct ast_frame *fr, *new_fr;
  688. if (!s || !s->fmt) {
  689. return NULL;
  690. }
  691. if (!(fr = s->fmt->read(s, whennext))) {
  692. return NULL;
  693. }
  694. if (!(new_fr = ast_frisolate(fr))) {
  695. ast_frfree(fr);
  696. return NULL;
  697. }
  698. if (new_fr != fr) {
  699. ast_frfree(fr);
  700. fr = new_fr;
  701. }
  702. return fr;
  703. }
  704. struct ast_frame *ast_readframe(struct ast_filestream *s)
  705. {
  706. int whennext = 0;
  707. return read_frame(s, &whennext);
  708. }
  709. enum fsread_res {
  710. FSREAD_FAILURE,
  711. FSREAD_SUCCESS_SCHED,
  712. FSREAD_SUCCESS_NOSCHED,
  713. };
  714. static int ast_fsread_audio(const void *data);
  715. static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
  716. {
  717. int whennext = 0;
  718. while (!whennext) {
  719. struct ast_frame *fr;
  720. if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
  721. goto return_failure;
  722. }
  723. fr = read_frame(s, &whennext);
  724. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  725. if (fr) {
  726. ast_log(LOG_WARNING, "Failed to write frame\n");
  727. ast_frfree(fr);
  728. }
  729. goto return_failure;
  730. }
  731. if (fr) {
  732. ast_frfree(fr);
  733. }
  734. }
  735. if (whennext != s->lasttimeout) {
  736. if (ast_channel_timingfd(s->owner) > -1) {
  737. float samp_rate = (float) ast_format_rate(&s->fmt->format);
  738. unsigned int rate;
  739. rate = (unsigned int) roundf(samp_rate / ((float) whennext));
  740. ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
  741. } else {
  742. ast_channel_streamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_audio, s));
  743. }
  744. s->lasttimeout = whennext;
  745. return FSREAD_SUCCESS_NOSCHED;
  746. }
  747. return FSREAD_SUCCESS_SCHED;
  748. return_failure:
  749. ast_channel_streamid_set(s->owner, -1);
  750. ast_settimeout(s->owner, 0, NULL, NULL);
  751. return FSREAD_FAILURE;
  752. }
  753. static int ast_fsread_audio(const void *data)
  754. {
  755. struct ast_filestream *fs = (struct ast_filestream *)data;
  756. enum fsread_res res;
  757. res = ast_readaudio_callback(fs);
  758. if (res == FSREAD_SUCCESS_SCHED)
  759. return 1;
  760. return 0;
  761. }
  762. static int ast_fsread_video(const void *data);
  763. static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
  764. {
  765. int whennext = 0;
  766. while (!whennext) {
  767. struct ast_frame *fr = read_frame(s, &whennext);
  768. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  769. if (fr) {
  770. ast_log(LOG_WARNING, "Failed to write frame\n");
  771. ast_frfree(fr);
  772. }
  773. ast_channel_vstreamid_set(s->owner, -1);
  774. return FSREAD_FAILURE;
  775. }
  776. if (fr) {
  777. ast_frfree(fr);
  778. }
  779. }
  780. if (whennext != s->lasttimeout) {
  781. ast_channel_vstreamid_set(s->owner, ast_sched_add(ast_channel_sched(s->owner), whennext / (ast_format_rate(&s->fmt->format) / 1000), ast_fsread_video, s));
  782. s->lasttimeout = whennext;
  783. return FSREAD_SUCCESS_NOSCHED;
  784. }
  785. return FSREAD_SUCCESS_SCHED;
  786. }
  787. static int ast_fsread_video(const void *data)
  788. {
  789. struct ast_filestream *fs = (struct ast_filestream *)data;
  790. enum fsread_res res;
  791. res = ast_readvideo_callback(fs);
  792. if (res == FSREAD_SUCCESS_SCHED)
  793. return 1;
  794. return 0;
  795. }
  796. int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
  797. {
  798. s->owner = chan;
  799. return 0;
  800. }
  801. int ast_playstream(struct ast_filestream *s)
  802. {
  803. enum fsread_res res;
  804. if (AST_FORMAT_GET_TYPE(s->fmt->format.id) == AST_FORMAT_TYPE_AUDIO)
  805. res = ast_readaudio_callback(s);
  806. else
  807. res = ast_readvideo_callback(s);
  808. return (res == FSREAD_FAILURE) ? -1 : 0;
  809. }
  810. int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
  811. {
  812. return fs->fmt->seek(fs, sample_offset, whence);
  813. }
  814. int ast_truncstream(struct ast_filestream *fs)
  815. {
  816. return fs->fmt->trunc(fs);
  817. }
  818. off_t ast_tellstream(struct ast_filestream *fs)
  819. {
  820. return fs->fmt->tell(fs);
  821. }
  822. int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
  823. {
  824. return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  825. }
  826. int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
  827. {
  828. return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  829. }
  830. int ast_closestream(struct ast_filestream *f)
  831. {
  832. /* This used to destroy the filestream, but it now just decrements a refcount.
  833. * We close the stream in order to quit queuing frames now, because we might
  834. * change the writeformat, which could result in a subsequent write error, if
  835. * the format is different. */
  836. filestream_close(f);
  837. ao2_ref(f, -1);
  838. return 0;
  839. }
  840. /*
  841. * Look the various language-specific places where a file could exist.
  842. */
  843. int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
  844. {
  845. char *buf;
  846. int buflen;
  847. if (preflang == NULL)
  848. preflang = "";
  849. buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
  850. buf = ast_alloca(buflen);
  851. return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
  852. }
  853. int ast_filedelete(const char *filename, const char *fmt)
  854. {
  855. return filehelper(filename, NULL, fmt, ACTION_DELETE);
  856. }
  857. int ast_filerename(const char *filename, const char *filename2, const char *fmt)
  858. {
  859. return filehelper(filename, filename2, fmt, ACTION_RENAME);
  860. }
  861. int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
  862. {
  863. return filehelper(filename, filename2, fmt, ACTION_COPY);
  864. }
  865. int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
  866. {
  867. struct ast_filestream *fs;
  868. struct ast_filestream *vfs=NULL;
  869. char fmt[256];
  870. off_t pos;
  871. int seekattempt;
  872. int res;
  873. fs = ast_openstream(chan, filename, preflang);
  874. if (!fs) {
  875. ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n", filename, ast_getformatname_multiple(fmt, sizeof(fmt), ast_channel_nativeformats(chan)), strerror(errno));
  876. return -1;
  877. }
  878. /* check to see if there is any data present (not a zero length file),
  879. * done this way because there is no where for ast_openstream_full to
  880. * return the file had no data. */
  881. pos = ftello(fs->f);
  882. seekattempt = fseeko(fs->f, -1, SEEK_END);
  883. if (seekattempt) {
  884. if (errno == EINVAL) {
  885. /* Zero-length file, as opposed to a pipe */
  886. return 0;
  887. } else {
  888. ast_seekstream(fs, 0, SEEK_SET);
  889. }
  890. } else {
  891. fseeko(fs->f, pos, SEEK_SET);
  892. }
  893. vfs = ast_openvstream(chan, filename, preflang);
  894. if (vfs) {
  895. ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_getformatname(&vfs->fmt->format));
  896. }
  897. if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
  898. fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
  899. if (ast_applystream(chan, fs))
  900. return -1;
  901. if (vfs && ast_applystream(chan, vfs))
  902. return -1;
  903. ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", filename, ast_channel_name(chan));
  904. res = ast_playstream(fs);
  905. if (!res && vfs)
  906. res = ast_playstream(vfs);
  907. ast_verb(3, "<%s> Playing '%s.%s' (language '%s')\n", ast_channel_name(chan), filename, ast_getformatname(ast_channel_writeformat(chan)), preflang ? preflang : "default");
  908. return res;
  909. }
  910. struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  911. {
  912. FILE *bfile;
  913. struct ast_format_def *f;
  914. struct ast_filestream *fs = NULL;
  915. char *fn;
  916. int format_found = 0;
  917. AST_RWLIST_RDLOCK(&formats);
  918. AST_RWLIST_TRAVERSE(&formats, f, list) {
  919. fs = NULL;
  920. if (!exts_compare(f->exts, type))
  921. continue;
  922. else
  923. format_found = 1;
  924. fn = build_filename(filename, type);
  925. if (!fn) {
  926. continue;
  927. }
  928. errno = 0;
  929. bfile = fopen(fn, "r");
  930. if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
  931. ast_log(LOG_WARNING, "Unable to open %s\n", fn);
  932. if (fs) {
  933. ast_closestream(fs);
  934. }
  935. fs = NULL;
  936. bfile = NULL;
  937. ast_free(fn);
  938. break;
  939. }
  940. /* found it */
  941. fs->trans = NULL;
  942. fs->fmt = f;
  943. fs->flags = flags;
  944. fs->mode = mode;
  945. fs->filename = ast_strdup(filename);
  946. fs->vfs = NULL;
  947. ast_free(fn);
  948. break;
  949. }
  950. AST_RWLIST_UNLOCK(&formats);
  951. if (!format_found)
  952. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  953. return fs;
  954. }
  955. struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  956. {
  957. int fd, myflags = 0;
  958. /* compiler claims this variable can be used before initialization... */
  959. FILE *bfile = NULL;
  960. struct ast_format_def *f;
  961. struct ast_filestream *fs = NULL;
  962. char *buf = NULL;
  963. size_t size = 0;
  964. int format_found = 0;
  965. AST_RWLIST_RDLOCK(&formats);
  966. /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
  967. /* We really can't use O_APPEND as it will break WAV header updates */
  968. if (flags & O_APPEND) {
  969. flags &= ~O_APPEND;
  970. } else {
  971. myflags = O_TRUNC;
  972. }
  973. myflags |= O_WRONLY | O_CREAT;
  974. /* XXX need to fix this - we should just do the fopen,
  975. * not open followed by fdopen()
  976. */
  977. AST_RWLIST_TRAVERSE(&formats, f, list) {
  978. char *fn, *orig_fn = NULL;
  979. if (fs)
  980. break;
  981. if (!exts_compare(f->exts, type))
  982. continue;
  983. else
  984. format_found = 1;
  985. fn = build_filename(filename, type);
  986. if (!fn) {
  987. continue;
  988. }
  989. fd = open(fn, flags | myflags, mode);
  990. if (fd > -1) {
  991. /* fdopen() the resulting file stream */
  992. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  993. if (!bfile) {
  994. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  995. close(fd);
  996. fd = -1;
  997. }
  998. }
  999. if (ast_opt_cache_record_files && (fd > -1)) {
  1000. char *c;
  1001. fclose(bfile); /* this also closes fd */
  1002. /*
  1003. We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
  1004. What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
  1005. */
  1006. orig_fn = ast_strdupa(fn);
  1007. for (c = fn; *c; c++)
  1008. if (*c == '/')
  1009. *c = '_';
  1010. size = strlen(fn) + strlen(record_cache_dir) + 2;
  1011. buf = ast_alloca(size);
  1012. strcpy(buf, record_cache_dir);
  1013. strcat(buf, "/");
  1014. strcat(buf, fn);
  1015. ast_free(fn);
  1016. fn = buf;
  1017. fd = open(fn, flags | myflags, mode);
  1018. if (fd > -1) {
  1019. /* fdopen() the resulting file stream */
  1020. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  1021. if (!bfile) {
  1022. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  1023. close(fd);
  1024. fd = -1;
  1025. }
  1026. }
  1027. }
  1028. if (fd > -1) {
  1029. errno = 0;
  1030. fs = get_filestream(f, bfile);
  1031. if (fs) {
  1032. if ((fs->write_buffer = ast_malloc(32768))) {
  1033. setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
  1034. }
  1035. }
  1036. if (!fs || rewrite_wrapper(fs, comment)) {
  1037. ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
  1038. close(fd);
  1039. if (orig_fn) {
  1040. unlink(fn);
  1041. unlink(orig_fn);
  1042. }
  1043. if (fs) {
  1044. ast_closestream(fs);
  1045. fs = NULL;
  1046. }
  1047. if (!buf) {
  1048. ast_free(fn);
  1049. }
  1050. continue;
  1051. }
  1052. fs->trans = NULL;
  1053. fs->fmt = f;
  1054. fs->flags = flags;
  1055. fs->mode = mode;
  1056. if (orig_fn) {
  1057. fs->realfilename = ast_strdup(orig_fn);
  1058. fs->filename = ast_strdup(fn);
  1059. } else {
  1060. fs->realfilename = NULL;
  1061. fs->filename = ast_strdup(filename);
  1062. }
  1063. fs->vfs = NULL;
  1064. /* If truncated, we'll be at the beginning; if not truncated, then append */
  1065. f->seek(fs, 0, SEEK_END);
  1066. } else if (errno != EEXIST) {
  1067. ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
  1068. if (orig_fn)
  1069. unlink(orig_fn);
  1070. }
  1071. /* if buf != NULL then fn is already free and pointing to it */
  1072. if (!buf)
  1073. ast_free(fn);
  1074. }
  1075. AST_RWLIST_UNLOCK(&formats);
  1076. if (!format_found)
  1077. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  1078. return fs;
  1079. }
  1080. /*!
  1081. * \brief the core of all waitstream() functions
  1082. */
  1083. static int waitstream_core(struct ast_channel *c,
  1084. const char *breakon,
  1085. const char *forward,
  1086. const char *reverse,
  1087. int skip_ms,
  1088. int audiofd,
  1089. int cmdfd,
  1090. const char *context,
  1091. ast_waitstream_fr_cb cb)
  1092. {
  1093. const char *orig_chan_name = NULL;
  1094. int err = 0;
  1095. if (!breakon)
  1096. breakon = "";
  1097. if (!forward)
  1098. forward = "";
  1099. if (!reverse)
  1100. reverse = "";
  1101. /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
  1102. ast_set_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1103. if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
  1104. orig_chan_name = ast_strdupa(ast_channel_name(c));
  1105. if (ast_channel_stream(c) && cb) {
  1106. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
  1107. cb(c, ms_len, AST_WAITSTREAM_CB_START);
  1108. }
  1109. while (ast_channel_stream(c)) {
  1110. int res;
  1111. int ms;
  1112. if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
  1113. ast_stopstream(c);
  1114. err = 1;
  1115. break;
  1116. }
  1117. ms = ast_sched_wait(ast_channel_sched(c));
  1118. if (ms < 0 && !ast_channel_timingfunc(c)) {
  1119. ast_stopstream(c);
  1120. break;
  1121. }
  1122. if (ms < 0)
  1123. ms = 1000;
  1124. if (cmdfd < 0) {
  1125. res = ast_waitfor(c, ms);
  1126. if (res < 0) {
  1127. ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
  1128. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1129. return res;
  1130. }
  1131. } else {
  1132. int outfd;
  1133. struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
  1134. if (!rchan && (outfd < 0) && (ms)) {
  1135. /* Continue */
  1136. if (errno == EINTR)
  1137. continue;
  1138. ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
  1139. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1140. return -1;
  1141. } else if (outfd > -1) { /* this requires cmdfd set */
  1142. /* The FD we were watching has something waiting */
  1143. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1144. return 1;
  1145. }
  1146. /* if rchan is set, it is 'c' */
  1147. res = rchan ? 1 : 0; /* map into 'res' values */
  1148. }
  1149. if (res > 0) {
  1150. struct ast_frame *fr = ast_read(c);
  1151. if (!fr) {
  1152. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1153. return -1;
  1154. }
  1155. switch (fr->frametype) {
  1156. case AST_FRAME_DTMF_END:
  1157. if (context) {
  1158. const char exten[2] = { fr->subclass.integer, '\0' };
  1159. if (ast_exists_extension(c, context, exten, 1,
  1160. S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
  1161. res = fr->subclass.integer;
  1162. ast_frfree(fr);
  1163. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1164. return res;
  1165. }
  1166. } else {
  1167. enum ast_waitstream_fr_cb_values cb_val = 0;
  1168. res = fr->subclass.integer;
  1169. if (strchr(forward, res)) {
  1170. int eoftest;
  1171. ast_stream_fastforward(ast_channel_stream(c), skip_ms);
  1172. eoftest = fgetc(ast_channel_stream(c)->f);
  1173. if (feof(ast_channel_stream(c)->f)) {
  1174. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1175. } else {
  1176. ungetc(eoftest, ast_channel_stream(c)->f);
  1177. }
  1178. cb_val = AST_WAITSTREAM_CB_FASTFORWARD;
  1179. } else if (strchr(reverse, res)) {
  1180. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1181. cb_val = AST_WAITSTREAM_CB_REWIND;
  1182. } else if (strchr(breakon, res)) {
  1183. ast_frfree(fr);
  1184. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1185. return res;
  1186. }
  1187. if (cb_val && cb) {
  1188. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_rate(&ast_channel_stream(c)->fmt->format) / 1000);
  1189. cb(c, ms_len, cb_val);
  1190. }
  1191. }
  1192. break;
  1193. case AST_FRAME_CONTROL:
  1194. switch (fr->subclass.integer) {
  1195. case AST_CONTROL_HANGUP:
  1196. case AST_CONTROL_BUSY:
  1197. case AST_CONTROL_CONGESTION:
  1198. ast_frfree(fr);
  1199. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1200. return -1;
  1201. case AST_CONTROL_RINGING:
  1202. case AST_CONTROL_ANSWER:
  1203. case AST_CONTROL_VIDUPDATE:
  1204. case AST_CONTROL_SRCUPDATE:
  1205. case AST_CONTROL_SRCCHANGE:
  1206. case AST_CONTROL_HOLD:
  1207. case AST_CONTROL_UNHOLD:
  1208. case AST_CONTROL_CONNECTED_LINE:
  1209. case AST_CONTROL_REDIRECTING:
  1210. case AST_CONTROL_AOC:
  1211. case AST_CONTROL_UPDATE_RTP_PEER:
  1212. case AST_CONTROL_PVT_CAUSE_CODE:
  1213. case -1:
  1214. /* Unimportant */
  1215. break;
  1216. default:
  1217. ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
  1218. }
  1219. break;
  1220. case AST_FRAME_VOICE:
  1221. /* Write audio if appropriate */
  1222. if (audiofd > -1) {
  1223. if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
  1224. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  1225. }
  1226. }
  1227. default:
  1228. /* Ignore all others */
  1229. break;
  1230. }
  1231. ast_frfree(fr);
  1232. }
  1233. ast_sched_runq(ast_channel_sched(c));
  1234. }
  1235. ast_clear_flag(ast_channel_flags(c), AST_FLAG_END_DTMF_ONLY);
  1236. return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
  1237. }
  1238. int ast_waitstream_fr_w_cb(struct ast_channel *c,
  1239. const char *breakon,
  1240. const char *forward,
  1241. const char *reverse,
  1242. int ms,
  1243. ast_waitstream_fr_cb cb)
  1244. {
  1245. return waitstream_core(c, breakon, forward, reverse, ms,
  1246. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
  1247. }
  1248. int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
  1249. {
  1250. return waitstream_core(c, breakon, forward, reverse, ms,
  1251. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
  1252. }
  1253. int ast_waitstream(struct ast_channel *c, const char *breakon)
  1254. {
  1255. return waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
  1256. }
  1257. int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
  1258. {
  1259. return waitstream_core(c, breakon, NULL, NULL, 0,
  1260. audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
  1261. }
  1262. int ast_waitstream_exten(struct ast_channel *c, const char *context)
  1263. {
  1264. /* Waitstream, with return in the case of a valid 1 digit extension */
  1265. /* in the current or specified context being pressed */
  1266. if (!context)
  1267. context = ast_channel_context(c);
  1268. return waitstream_core(c, NULL, NULL, NULL, 0,
  1269. -1, -1, context, NULL /* no callback */);
  1270. }
  1271. /*
  1272. * if the file name is non-empty, try to play it.
  1273. * Return 0 if success, -1 if error, digit if interrupted by a digit.
  1274. * If digits == "" then we can simply check for non-zero.
  1275. */
  1276. int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
  1277. {
  1278. int res = 0;
  1279. if (!ast_strlen_zero(file)) {
  1280. res = ast_streamfile(chan, file, ast_channel_language(chan));
  1281. if (!res) {
  1282. res = ast_waitstream(chan, digits);
  1283. }
  1284. }
  1285. return res;
  1286. }
  1287. char *ast_format_str_reduce(char *fmts)
  1288. {
  1289. struct ast_format_def *f;
  1290. struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
  1291. char *fmts_str[AST_MAX_FORMATS];
  1292. char *stringp, *type;
  1293. char *orig = fmts;
  1294. int i, j, x, first, found = 0;
  1295. int len = strlen(fmts) + 1;
  1296. int res;
  1297. if (AST_RWLIST_RDLOCK(&formats)) {
  1298. ast_log(LOG_WARNING, "Unable to lock format list\n");
  1299. return NULL;
  1300. }
  1301. stringp = ast_strdupa(fmts);
  1302. for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
  1303. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1304. if (exts_compare(f->exts, type)) {
  1305. found = 1;
  1306. break;
  1307. }
  1308. }
  1309. fmts_str[x] = type;
  1310. if (found) {
  1311. fmts_ptr[x] = f;
  1312. } else {
  1313. fmts_ptr[x] = NULL;
  1314. }
  1315. }
  1316. AST_RWLIST_UNLOCK(&formats);
  1317. first = 1;
  1318. for (i = 0; i < x; i++) {
  1319. /* ignore invalid entries */
  1320. if (!fmts_ptr[i]) {
  1321. ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
  1322. continue;
  1323. }
  1324. /* special handling for the first entry */
  1325. if (first) {
  1326. res = snprintf(fmts, len, "%s", fmts_str[i]);
  1327. fmts += res;
  1328. len -= res;
  1329. first = 0;
  1330. continue;
  1331. }
  1332. found = 0;
  1333. for (j = 0; j < i; j++) {
  1334. /* this is a duplicate */
  1335. if (fmts_ptr[j] == fmts_ptr[i]) {
  1336. found = 1;
  1337. break;
  1338. }
  1339. }
  1340. if (!found) {
  1341. res = snprintf(fmts, len, "|%s", fmts_str[i]);
  1342. fmts += res;
  1343. len -= res;
  1344. }
  1345. }
  1346. if (first) {
  1347. ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
  1348. return NULL;
  1349. }
  1350. return orig;
  1351. }
  1352. static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1353. {
  1354. #define FORMAT "%-10s %-10s %-20s\n"
  1355. #define FORMAT2 "%-10s %-10s %-20s\n"
  1356. struct ast_format_def *f;
  1357. int count_fmt = 0;
  1358. switch (cmd) {
  1359. case CLI_INIT:
  1360. e->command = "core show file formats";
  1361. e->usage =
  1362. "Usage: core show file formats\n"
  1363. " Displays currently registered file formats (if any).\n";
  1364. return NULL;
  1365. case CLI_GENERATE:
  1366. return NULL;
  1367. }
  1368. if (a->argc != 4)
  1369. return CLI_SHOWUSAGE;
  1370. ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
  1371. ast_cli(a->fd, FORMAT, "------", "----", "----------");
  1372. AST_RWLIST_RDLOCK(&formats);
  1373. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1374. ast_cli(a->fd, FORMAT2, ast_getformatname(&f->format), f->name, f->exts);
  1375. count_fmt++;
  1376. }
  1377. AST_RWLIST_UNLOCK(&formats);
  1378. ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
  1379. return CLI_SUCCESS;
  1380. #undef FORMAT
  1381. #undef FORMAT2
  1382. }
  1383. static struct ast_cli_entry cli_file[] = {
  1384. AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
  1385. };
  1386. static void file_shutdown(void)
  1387. {
  1388. ast_cli_unregister_multiple(cli_file, ARRAY_LEN(cli_file));
  1389. }
  1390. int ast_file_init(void)
  1391. {
  1392. ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
  1393. ast_register_cleanup(file_shutdown);
  1394. return 0;
  1395. }