file.c 47 KB

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