file.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  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. if (f->filename)
  364. free(f->filename);
  365. if (f->realfilename)
  366. free(f->realfilename);
  367. if (f->vfs)
  368. ast_closestream(f->vfs);
  369. if (f->write_buffer) {
  370. ast_free(f->write_buffer);
  371. }
  372. if (f->orig_chan_name)
  373. free((void *) f->orig_chan_name);
  374. ao2_cleanup(f->lastwriteformat);
  375. ao2_cleanup(f->fr.subclass.format);
  376. ast_module_unref(f->fmt->module);
  377. }
  378. static struct ast_filestream *get_filestream(struct ast_format_def *fmt, FILE *bfile)
  379. {
  380. struct ast_filestream *s;
  381. int l = sizeof(*s) + fmt->buf_size + fmt->desc_size; /* total allocation size */
  382. if ( (s = ao2_alloc(l, filestream_destructor)) == NULL)
  383. return NULL;
  384. ast_module_ref(fmt->module);
  385. s->fmt = fmt;
  386. s->f = bfile;
  387. if (fmt->desc_size)
  388. s->_private = ((char *)(s + 1)) + fmt->buf_size;
  389. if (fmt->buf_size)
  390. s->buf = (char *)(s + 1);
  391. s->fr.src = fmt->name;
  392. if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_AUDIO) {
  393. s->fr.frametype = AST_FRAME_VOICE;
  394. } else if (ast_format_get_type(fmt->format) == AST_MEDIA_TYPE_VIDEO) {
  395. s->fr.frametype = AST_FRAME_VIDEO;
  396. }
  397. s->fr.mallocd = 0;
  398. s->fr.subclass.format = ao2_bump(fmt->format);
  399. return s;
  400. }
  401. /*
  402. * Default implementations of open and rewrite.
  403. * Only use them if you don't have expensive stuff to do.
  404. */
  405. enum wrap_fn { WRAP_OPEN, WRAP_REWRITE };
  406. static int fn_wrapper(struct ast_filestream *s, const char *comment, enum wrap_fn mode)
  407. {
  408. struct ast_format_def *f = s->fmt;
  409. int ret = -1;
  410. int (*openfn)(struct ast_filestream *s);
  411. if (mode == WRAP_OPEN && (openfn = f->open) && openfn(s))
  412. ast_log(LOG_WARNING, "Unable to open format %s\n", f->name);
  413. else if (mode == WRAP_REWRITE && f->rewrite && f->rewrite(s, comment))
  414. ast_log(LOG_WARNING, "Unable to rewrite format %s\n", f->name);
  415. else {
  416. /* preliminary checks succeed. */
  417. ret = 0;
  418. }
  419. return ret;
  420. }
  421. static int rewrite_wrapper(struct ast_filestream *s, const char *comment)
  422. {
  423. return fn_wrapper(s, comment, WRAP_REWRITE);
  424. }
  425. static int open_wrapper(struct ast_filestream *s)
  426. {
  427. return fn_wrapper(s, NULL, WRAP_OPEN);
  428. }
  429. enum file_action {
  430. ACTION_EXISTS = 1, /* return matching format if file exists, 0 otherwise */
  431. ACTION_DELETE, /* delete file, return 0 on success, -1 on error */
  432. ACTION_RENAME, /* rename file. return 0 on success, -1 on error */
  433. ACTION_OPEN,
  434. ACTION_COPY /* copy file. return 0 on success, -1 on error */
  435. };
  436. /*!
  437. * \internal
  438. * \brief perform various actions on a file. Second argument
  439. * \note arg2 depends on the command:
  440. * unused for DELETE
  441. * optional ast_format_cap holding all the formats found for a file, for EXISTS.
  442. * destination file name (const char *) for COPY and RENAME
  443. * struct ast_channel * for OPEN
  444. * if fmt is NULL, OPEN will return the first matching entry,
  445. * whereas other functions will run on all matching entries.
  446. */
  447. static int filehelper(const char *filename, const void *arg2, const char *fmt, const enum file_action action)
  448. {
  449. struct ast_format_def *f;
  450. int res = (action == ACTION_EXISTS) ? 0 : -1;
  451. AST_RWLIST_RDLOCK(&formats);
  452. /* Check for a specific format */
  453. AST_RWLIST_TRAVERSE(&formats, f, list) {
  454. char *stringp, *ext = NULL;
  455. if (fmt && !exts_compare(f->exts, fmt))
  456. continue;
  457. /* Look for a file matching the supported extensions.
  458. * The file must exist, and for OPEN, must match
  459. * one of the formats supported by the channel.
  460. */
  461. stringp = ast_strdupa(f->exts); /* this is in the stack so does not need to be freed */
  462. while ( (ext = strsep(&stringp, "|")) ) {
  463. struct stat st;
  464. char *fn = build_filename(filename, ext);
  465. if (fn == NULL)
  466. continue;
  467. if ( stat(fn, &st) ) { /* file not existent */
  468. ast_free(fn);
  469. continue;
  470. }
  471. /* for 'OPEN' we need to be sure that the format matches
  472. * what the channel can process
  473. */
  474. if (action == ACTION_OPEN) {
  475. struct ast_channel *chan = (struct ast_channel *)arg2;
  476. FILE *bfile;
  477. struct ast_filestream *s;
  478. if ((ast_format_cmp(ast_channel_writeformat(chan), f->format) == AST_FORMAT_CMP_NOT_EQUAL) &&
  479. !(((ast_format_get_type(f->format) == AST_MEDIA_TYPE_AUDIO) && fmt) ||
  480. ((ast_format_get_type(f->format) == AST_MEDIA_TYPE_VIDEO) && fmt))) {
  481. ast_free(fn);
  482. continue; /* not a supported format */
  483. }
  484. if ( (bfile = fopen(fn, "r")) == NULL) {
  485. ast_free(fn);
  486. continue; /* cannot open file */
  487. }
  488. s = get_filestream(f, bfile);
  489. if (!s) {
  490. fclose(bfile);
  491. ast_free(fn); /* cannot allocate descriptor */
  492. continue;
  493. }
  494. if (open_wrapper(s)) {
  495. ast_free(fn);
  496. ast_closestream(s);
  497. continue; /* cannot run open on file */
  498. }
  499. if (st.st_size == 0) {
  500. ast_log(LOG_WARNING, "File %s detected to have zero size.\n", fn);
  501. }
  502. /* ok this is good for OPEN */
  503. res = 1; /* found */
  504. s->lasttimeout = -1;
  505. s->fmt = f;
  506. s->trans = NULL;
  507. s->filename = NULL;
  508. if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO) {
  509. if (ast_channel_stream(chan))
  510. ast_closestream(ast_channel_stream(chan));
  511. ast_channel_stream_set(chan, s);
  512. } else {
  513. if (ast_channel_vstream(chan))
  514. ast_closestream(ast_channel_vstream(chan));
  515. ast_channel_vstream_set(chan, s);
  516. }
  517. ast_free(fn);
  518. break;
  519. }
  520. switch (action) {
  521. case ACTION_OPEN:
  522. break; /* will never get here */
  523. case ACTION_EXISTS: /* return the matching format */
  524. /* if arg2 is present, it is a format capabilities structure.
  525. * Add this format to the set of formats this file can be played in */
  526. if (arg2) {
  527. ast_format_cap_append((struct ast_format_cap *) arg2, f->format, 0);
  528. }
  529. res = 1; /* file does exist and format it exists in is returned in arg2 */
  530. break;
  531. case ACTION_DELETE:
  532. if ( (res = unlink(fn)) )
  533. ast_log(LOG_WARNING, "unlink(%s) failed: %s\n", fn, strerror(errno));
  534. break;
  535. case ACTION_RENAME:
  536. case ACTION_COPY: {
  537. char *nfn = build_filename((const char *)arg2, ext);
  538. if (!nfn)
  539. ast_log(LOG_WARNING, "Out of memory\n");
  540. else {
  541. res = action == ACTION_COPY ? copy(fn, nfn) : rename(fn, nfn);
  542. if (res)
  543. ast_log(LOG_WARNING, "%s(%s,%s) failed: %s\n",
  544. action == ACTION_COPY ? "copy" : "rename",
  545. fn, nfn, strerror(errno));
  546. ast_free(nfn);
  547. }
  548. }
  549. break;
  550. default:
  551. ast_log(LOG_WARNING, "Unknown helper %u\n", action);
  552. }
  553. ast_free(fn);
  554. }
  555. }
  556. AST_RWLIST_UNLOCK(&formats);
  557. return res;
  558. }
  559. static int is_absolute_path(const char *filename)
  560. {
  561. return filename[0] == '/';
  562. }
  563. /*!
  564. * \brief test if a file exists for a given format.
  565. * \note result_cap is OPTIONAL
  566. * \retval 1, true and result_cap represents format capabilities file exists in.
  567. * \retval 0, false
  568. */
  569. static int fileexists_test(const char *filename, const char *fmt, const char *lang,
  570. char *buf, int buflen, struct ast_format_cap *result_cap)
  571. {
  572. if (buf == NULL) {
  573. return 0;
  574. }
  575. if (ast_language_is_prefix && !is_absolute_path(filename)) { /* new layout */
  576. if (lang) {
  577. snprintf(buf, buflen, "%s/%s", lang, filename);
  578. } else {
  579. snprintf(buf, buflen, "%s", filename);
  580. }
  581. } else { /* old layout */
  582. strcpy(buf, filename); /* first copy the full string */
  583. if (lang) {
  584. /* insert the language and suffix if needed */
  585. const char *c = strrchr(filename, '/');
  586. int offset = c ? c - filename + 1 : 0; /* points right after the last '/' */
  587. snprintf(buf + offset, buflen - offset, "%s/%s", lang, filename + offset);
  588. }
  589. }
  590. return filehelper(buf, result_cap, fmt, ACTION_EXISTS);
  591. }
  592. /*!
  593. * \brief helper routine to locate a file with a given format
  594. * and language preference.
  595. *
  596. * \note Try preflang, preflang with stripped '_' suffices, or NULL.
  597. *
  598. * \note The last parameter(s) point to a buffer of sufficient size,
  599. * which on success is filled with the matching filename.
  600. *
  601. * \param filename Name of the file.
  602. * \param fmt Format to look for the file in. OPTIONAL
  603. * \param preflang The perfered language
  604. * \param buf Returns the matching filename
  605. * \param buflen Size of the buf
  606. * \param result_cap OPTIONAL format capabilities result structure
  607. * returns what formats the file was found in.
  608. *
  609. * \retval 1, true. file exists and result format is set
  610. * \retval 0, false. file does not exist.
  611. */
  612. static int fileexists_core(const char *filename, const char *fmt, const char *preflang,
  613. char *buf, int buflen, struct ast_format_cap *result_cap)
  614. {
  615. char *lang;
  616. if (buf == NULL) {
  617. return 0;
  618. }
  619. /* We try languages in the following order:
  620. * preflang (may include dialect and style codes)
  621. * lang (preflang without dialect - if any)
  622. * <none>
  623. * default (unless the same as preflang or lang without dialect)
  624. */
  625. lang = ast_strdupa(preflang);
  626. /* Try preferred language, including removing any style or dialect codes */
  627. while (!ast_strlen_zero(lang)) {
  628. char *end;
  629. if (fileexists_test(filename, fmt, lang, buf, buflen, result_cap)) {
  630. return 1;
  631. }
  632. if ((end = strrchr(lang, '_')) != NULL) {
  633. *end = '\0';
  634. continue;
  635. }
  636. break;
  637. }
  638. /* Try without any language */
  639. if (fileexists_test(filename, fmt, NULL, buf, buflen, result_cap)) {
  640. return 1;
  641. }
  642. /* Finally try the default language unless it was already tried before */
  643. if ((ast_strlen_zero(preflang) || strcmp(preflang, DEFAULT_LANGUAGE)) && (ast_strlen_zero(lang) || strcmp(lang, DEFAULT_LANGUAGE))) {
  644. if ((fileexists_test(filename, fmt, DEFAULT_LANGUAGE, buf, buflen, result_cap)) > 0) {
  645. return 1;
  646. }
  647. }
  648. return 0;
  649. }
  650. struct ast_filestream *ast_openstream(struct ast_channel *chan, const char *filename, const char *preflang)
  651. {
  652. return ast_openstream_full(chan, filename, preflang, 0);
  653. }
  654. struct ast_filestream *ast_openstream_full(struct ast_channel *chan, const char *filename, const char *preflang, int asis)
  655. {
  656. /*
  657. * Use fileexists_core() to find a file in a compatible
  658. * language and format, set up a suitable translator,
  659. * and open the stream.
  660. */
  661. struct ast_format_cap *file_fmt_cap;
  662. int res;
  663. int buflen;
  664. char *buf;
  665. if (!asis) {
  666. /* do this first, otherwise we detect the wrong writeformat */
  667. ast_stopstream(chan);
  668. if (ast_channel_generator(chan))
  669. ast_deactivate_generator(chan);
  670. }
  671. if (preflang == NULL)
  672. preflang = "";
  673. buflen = strlen(preflang) + strlen(filename) + 4;
  674. buf = ast_alloca(buflen);
  675. if (!(file_fmt_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  676. return NULL;
  677. }
  678. if (!fileexists_core(filename, NULL, preflang, buf, buflen, file_fmt_cap) ||
  679. !ast_format_cap_has_type(file_fmt_cap, AST_MEDIA_TYPE_AUDIO)) {
  680. ast_log(LOG_WARNING, "File %s does not exist in any format\n", filename);
  681. ao2_ref(file_fmt_cap, -1);
  682. return NULL;
  683. }
  684. /* Set the channel to a format we can work with and save off the previous format. */
  685. ast_channel_lock(chan);
  686. ast_channel_set_oldwriteformat(chan, ast_channel_writeformat(chan));
  687. /* Set the channel to the best format that exists for the file. */
  688. res = ast_set_write_format_from_cap(chan, file_fmt_cap);
  689. ast_channel_unlock(chan);
  690. /* don't need this anymore now that the channel's write format is set. */
  691. ao2_ref(file_fmt_cap, -1);
  692. if (res == -1) { /* No format available that works with this channel */
  693. return NULL;
  694. }
  695. res = filehelper(buf, chan, NULL, ACTION_OPEN);
  696. if (res >= 0)
  697. return ast_channel_stream(chan);
  698. return NULL;
  699. }
  700. struct ast_filestream *ast_openvstream(struct ast_channel *chan, const char *filename, const char *preflang)
  701. {
  702. /* As above, but for video. But here we don't have translators
  703. * so we must enforce a format.
  704. */
  705. struct ast_format_cap *nativeformats, *tmp_cap;
  706. char *buf;
  707. int buflen;
  708. int i, fd;
  709. if (preflang == NULL) {
  710. preflang = "";
  711. }
  712. buflen = strlen(preflang) + strlen(filename) + 4;
  713. buf = ast_alloca(buflen);
  714. ast_channel_lock(chan);
  715. nativeformats = ao2_bump(ast_channel_nativeformats(chan));
  716. ast_channel_unlock(chan);
  717. /* is the channel capable of video without translation ?*/
  718. if (!ast_format_cap_has_type(nativeformats, AST_MEDIA_TYPE_VIDEO)) {
  719. ao2_cleanup(nativeformats);
  720. return NULL;
  721. }
  722. if (!(tmp_cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
  723. ao2_cleanup(nativeformats);
  724. return NULL;
  725. }
  726. /* Video is supported, so see what video formats exist for this file */
  727. if (!fileexists_core(filename, NULL, preflang, buf, buflen, tmp_cap)) {
  728. ao2_ref(tmp_cap, -1);
  729. ao2_cleanup(nativeformats);
  730. return NULL;
  731. }
  732. /* iterate over file formats and pick the first one compatible with the channel's native formats */
  733. for (i = 0; i < ast_format_cap_count(tmp_cap); ++i) {
  734. struct ast_format *format = ast_format_cap_get_format(tmp_cap, i);
  735. if ((ast_format_get_type(format) != AST_MEDIA_TYPE_VIDEO) ||
  736. !ast_format_cap_iscompatible(nativeformats, tmp_cap)) {
  737. ao2_ref(format, -1);
  738. continue;
  739. }
  740. fd = filehelper(buf, chan, ast_format_get_name(format), ACTION_OPEN);
  741. if (fd >= 0) {
  742. ao2_ref(format, -1);
  743. ao2_ref(tmp_cap, -1);
  744. ao2_cleanup(nativeformats);
  745. return ast_channel_vstream(chan);
  746. }
  747. ast_log(LOG_WARNING, "File %s has video but couldn't be opened\n", filename);
  748. ao2_ref(format, -1);
  749. }
  750. ao2_ref(tmp_cap, -1);
  751. ao2_cleanup(nativeformats);
  752. return NULL;
  753. }
  754. static struct ast_frame *read_frame(struct ast_filestream *s, int *whennext)
  755. {
  756. struct ast_frame *fr, *new_fr;
  757. if (!s || !s->fmt) {
  758. return NULL;
  759. }
  760. if (!(fr = s->fmt->read(s, whennext))) {
  761. return NULL;
  762. }
  763. if (!(new_fr = ast_frisolate(fr))) {
  764. ast_frfree(fr);
  765. return NULL;
  766. }
  767. if (new_fr != fr) {
  768. ast_frfree(fr);
  769. fr = new_fr;
  770. }
  771. return fr;
  772. }
  773. struct ast_frame *ast_readframe(struct ast_filestream *s)
  774. {
  775. int whennext = 0;
  776. return read_frame(s, &whennext);
  777. }
  778. enum fsread_res {
  779. FSREAD_FAILURE,
  780. FSREAD_SUCCESS_SCHED,
  781. FSREAD_SUCCESS_NOSCHED,
  782. };
  783. static int ast_fsread_audio(const void *data);
  784. static enum fsread_res ast_readaudio_callback(struct ast_filestream *s)
  785. {
  786. int whennext = 0;
  787. while (!whennext) {
  788. struct ast_frame *fr;
  789. if (s->orig_chan_name && strcasecmp(ast_channel_name(s->owner), s->orig_chan_name)) {
  790. goto return_failure;
  791. }
  792. fr = read_frame(s, &whennext);
  793. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  794. if (fr) {
  795. ast_debug(2, "Failed to write frame\n");
  796. ast_frfree(fr);
  797. }
  798. goto return_failure;
  799. }
  800. if (fr) {
  801. ast_frfree(fr);
  802. }
  803. }
  804. if (whennext != s->lasttimeout) {
  805. if (ast_channel_timingfd(s->owner) > -1) {
  806. float samp_rate = (float) ast_format_get_sample_rate(s->fmt->format);
  807. unsigned int rate;
  808. rate = (unsigned int) roundf(samp_rate / ((float) whennext));
  809. ast_settimeout_full(s->owner, rate, ast_fsread_audio, s, 1);
  810. } else {
  811. 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));
  812. }
  813. s->lasttimeout = whennext;
  814. return FSREAD_SUCCESS_NOSCHED;
  815. }
  816. return FSREAD_SUCCESS_SCHED;
  817. return_failure:
  818. ast_channel_streamid_set(s->owner, -1);
  819. ast_settimeout(s->owner, 0, NULL, NULL);
  820. return FSREAD_FAILURE;
  821. }
  822. static int ast_fsread_audio(const void *data)
  823. {
  824. struct ast_filestream *fs = (struct ast_filestream *)data;
  825. enum fsread_res res;
  826. res = ast_readaudio_callback(fs);
  827. if (res == FSREAD_SUCCESS_SCHED)
  828. return 1;
  829. return 0;
  830. }
  831. static int ast_fsread_video(const void *data);
  832. static enum fsread_res ast_readvideo_callback(struct ast_filestream *s)
  833. {
  834. int whennext = 0;
  835. while (!whennext) {
  836. struct ast_frame *fr = read_frame(s, &whennext);
  837. if (!fr /* stream complete */ || ast_write(s->owner, fr) /* error writing */) {
  838. if (fr) {
  839. ast_debug(2, "Failed to write frame\n");
  840. ast_frfree(fr);
  841. }
  842. ast_channel_vstreamid_set(s->owner, -1);
  843. return FSREAD_FAILURE;
  844. }
  845. if (fr) {
  846. ast_frfree(fr);
  847. }
  848. }
  849. if (whennext != s->lasttimeout) {
  850. 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));
  851. s->lasttimeout = whennext;
  852. return FSREAD_SUCCESS_NOSCHED;
  853. }
  854. return FSREAD_SUCCESS_SCHED;
  855. }
  856. static int ast_fsread_video(const void *data)
  857. {
  858. struct ast_filestream *fs = (struct ast_filestream *)data;
  859. enum fsread_res res;
  860. res = ast_readvideo_callback(fs);
  861. if (res == FSREAD_SUCCESS_SCHED)
  862. return 1;
  863. return 0;
  864. }
  865. int ast_applystream(struct ast_channel *chan, struct ast_filestream *s)
  866. {
  867. s->owner = chan;
  868. return 0;
  869. }
  870. int ast_playstream(struct ast_filestream *s)
  871. {
  872. enum fsread_res res;
  873. if (ast_format_get_type(s->fmt->format) == AST_MEDIA_TYPE_AUDIO)
  874. res = ast_readaudio_callback(s);
  875. else
  876. res = ast_readvideo_callback(s);
  877. return (res == FSREAD_FAILURE) ? -1 : 0;
  878. }
  879. int ast_seekstream(struct ast_filestream *fs, off_t sample_offset, int whence)
  880. {
  881. return fs->fmt->seek(fs, sample_offset, whence);
  882. }
  883. int ast_truncstream(struct ast_filestream *fs)
  884. {
  885. return fs->fmt->trunc(fs);
  886. }
  887. off_t ast_tellstream(struct ast_filestream *fs)
  888. {
  889. return fs->fmt->tell(fs);
  890. }
  891. int ast_ratestream(struct ast_filestream *fs)
  892. {
  893. return ast_format_get_sample_rate(fs->fmt->format);
  894. }
  895. int ast_stream_fastforward(struct ast_filestream *fs, off_t ms)
  896. {
  897. return ast_seekstream(fs, ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  898. }
  899. int ast_stream_rewind(struct ast_filestream *fs, off_t ms)
  900. {
  901. return ast_seekstream(fs, -ms * DEFAULT_SAMPLES_PER_MS, SEEK_CUR);
  902. }
  903. int ast_closestream(struct ast_filestream *f)
  904. {
  905. /* This used to destroy the filestream, but it now just decrements a refcount.
  906. * We close the stream in order to quit queuing frames now, because we might
  907. * change the writeformat, which could result in a subsequent write error, if
  908. * the format is different. */
  909. if (f == NULL) {
  910. return 0;
  911. }
  912. filestream_close(f);
  913. ao2_ref(f, -1);
  914. return 0;
  915. }
  916. /*
  917. * Look the various language-specific places where a file could exist.
  918. */
  919. int ast_fileexists(const char *filename, const char *fmt, const char *preflang)
  920. {
  921. char *buf;
  922. int buflen;
  923. if (preflang == NULL)
  924. preflang = "";
  925. buflen = strlen(preflang) + strlen(filename) + 4; /* room for everything */
  926. buf = ast_alloca(buflen);
  927. return fileexists_core(filename, fmt, preflang, buf, buflen, NULL) ? 1 : 0;
  928. }
  929. int ast_filedelete(const char *filename, const char *fmt)
  930. {
  931. return filehelper(filename, NULL, fmt, ACTION_DELETE);
  932. }
  933. int ast_filerename(const char *filename, const char *filename2, const char *fmt)
  934. {
  935. return filehelper(filename, filename2, fmt, ACTION_RENAME);
  936. }
  937. int ast_filecopy(const char *filename, const char *filename2, const char *fmt)
  938. {
  939. return filehelper(filename, filename2, fmt, ACTION_COPY);
  940. }
  941. static int __ast_file_read_dirs(const char *path, ast_file_on_file on_file,
  942. void *obj, int max_depth)
  943. {
  944. DIR *dir;
  945. struct dirent *entry;
  946. int res;
  947. if (!(dir = opendir(path))) {
  948. ast_log(LOG_ERROR, "Error opening directory - %s: %s\n",
  949. path, strerror(errno));
  950. return -1;
  951. }
  952. --max_depth;
  953. res = 0;
  954. while ((entry = readdir(dir)) != NULL && !errno) {
  955. int is_file = 0;
  956. int is_dir = 0;
  957. RAII_VAR(char *, full_path, NULL, ast_free);
  958. if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
  959. continue;
  960. }
  961. /*
  962. * If the dirent structure has a d_type use it to determine if we are dealing with
  963. * a file or directory. Unfortunately if it doesn't have it, or if the type is
  964. * unknown, or a link then we'll need to use the stat function instead.
  965. */
  966. #ifdef _DIRENT_HAVE_D_TYPE
  967. if (entry->d_type != DT_UNKNOWN && entry->d_type != DT_LNK) {
  968. is_file = entry->d_type == DT_REG;
  969. is_dir = entry->d_type == DT_DIR;
  970. } else
  971. #endif
  972. {
  973. struct stat statbuf;
  974. /*
  975. * Don't use alloca or we risk blowing out the stack if recursing
  976. * into subdirectories.
  977. */
  978. full_path = ast_malloc(strlen(path) + strlen(entry->d_name) + 2);
  979. if (!full_path) {
  980. return -1;
  981. }
  982. sprintf(full_path, "%s/%s", path, entry->d_name);
  983. if (stat(full_path, &statbuf)) {
  984. ast_log(LOG_ERROR, "Error reading path stats - %s: %s\n",
  985. full_path, strerror(errno));
  986. /*
  987. * Output an error, but keep going. It could just be
  988. * a broken link and other files could be fine.
  989. */
  990. continue;
  991. }
  992. is_file = S_ISREG(statbuf.st_mode);
  993. is_dir = S_ISDIR(statbuf.st_mode);
  994. }
  995. if (is_file) {
  996. /* If the handler returns non-zero then stop */
  997. if ((res = on_file(path, entry->d_name, obj))) {
  998. break;
  999. }
  1000. /* Otherwise move on to next item in directory */
  1001. continue;
  1002. }
  1003. if (!is_dir) {
  1004. ast_debug(5, "Skipping %s: not a regular file or directory\n", full_path);
  1005. continue;
  1006. }
  1007. /* Only re-curse into sub-directories if not at the max depth */
  1008. if (max_depth != 0) {
  1009. if (!full_path) {
  1010. /* Don't use alloca. See note above. */
  1011. full_path = ast_malloc(strlen(path) + strlen(entry->d_name) + 2);
  1012. if (!full_path) {
  1013. return -1;
  1014. }
  1015. sprintf(full_path, "%s/%s", path, entry->d_name);
  1016. }
  1017. if ((res = __ast_file_read_dirs(full_path, on_file, obj, max_depth))) {
  1018. break;
  1019. }
  1020. }
  1021. }
  1022. closedir(dir);
  1023. if (!res && errno) {
  1024. ast_log(LOG_ERROR, "Error while reading directories - %s: %s\n",
  1025. path, strerror(errno));
  1026. res = -1;
  1027. }
  1028. return res;
  1029. }
  1030. #if !defined(__GLIBC__)
  1031. /*!
  1032. * \brief Lock to hold when iterating over directories.
  1033. *
  1034. * Currently, 'readdir' is not required to be thread-safe. In most modern implementations
  1035. * it should be safe to make concurrent calls into 'readdir' that specify different directory
  1036. * streams (glibc would be one of these). However, since it is potentially unsafe for some
  1037. * implementations we'll use our own locking in order to achieve synchronization for those.
  1038. */
  1039. AST_MUTEX_DEFINE_STATIC(read_dirs_lock);
  1040. #endif
  1041. int ast_file_read_dirs(const char *dir_name, ast_file_on_file on_file, void *obj, int max_depth)
  1042. {
  1043. int res;
  1044. errno = 0;
  1045. #if !defined(__GLIBC__)
  1046. ast_mutex_lock(&read_dirs_lock);
  1047. #endif
  1048. res = __ast_file_read_dirs(dir_name, on_file, obj, max_depth);
  1049. #if !defined(__GLIBC__)
  1050. ast_mutex_unlock(&read_dirs_lock);
  1051. #endif
  1052. return res;
  1053. }
  1054. int ast_streamfile(struct ast_channel *chan, const char *filename, const char *preflang)
  1055. {
  1056. struct ast_filestream *fs;
  1057. struct ast_filestream *vfs=NULL;
  1058. off_t pos;
  1059. int seekattempt;
  1060. int res;
  1061. fs = ast_openstream(chan, filename, preflang);
  1062. if (!fs) {
  1063. struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
  1064. ast_channel_lock(chan);
  1065. ast_log(LOG_WARNING, "Unable to open %s (format %s): %s\n",
  1066. filename, ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf), strerror(errno));
  1067. ast_channel_unlock(chan);
  1068. return -1;
  1069. }
  1070. /* check to see if there is any data present (not a zero length file),
  1071. * done this way because there is no where for ast_openstream_full to
  1072. * return the file had no data. */
  1073. pos = ftello(fs->f);
  1074. seekattempt = fseeko(fs->f, -1, SEEK_END);
  1075. if (seekattempt) {
  1076. if (errno == EINVAL) {
  1077. /* Zero-length file, as opposed to a pipe */
  1078. return 0;
  1079. } else {
  1080. ast_seekstream(fs, 0, SEEK_SET);
  1081. }
  1082. } else {
  1083. fseeko(fs->f, pos, SEEK_SET);
  1084. }
  1085. vfs = ast_openvstream(chan, filename, preflang);
  1086. if (vfs) {
  1087. ast_debug(1, "Ooh, found a video stream, too, format %s\n", ast_format_get_name(vfs->fmt->format));
  1088. }
  1089. if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MASQ_NOSTREAM))
  1090. fs->orig_chan_name = ast_strdup(ast_channel_name(chan));
  1091. if (ast_applystream(chan, fs))
  1092. return -1;
  1093. if (vfs && ast_applystream(chan, vfs))
  1094. return -1;
  1095. ast_test_suite_event_notify("PLAYBACK", "Message: %s\r\nChannel: %s", filename, ast_channel_name(chan));
  1096. res = ast_playstream(fs);
  1097. if (!res && vfs)
  1098. res = ast_playstream(vfs);
  1099. if (VERBOSITY_ATLEAST(3)) {
  1100. ast_channel_lock(chan);
  1101. 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");
  1102. ast_channel_unlock(chan);
  1103. }
  1104. return res;
  1105. }
  1106. struct ast_filestream *ast_readfile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  1107. {
  1108. FILE *bfile;
  1109. struct ast_format_def *f;
  1110. struct ast_filestream *fs = NULL;
  1111. char *fn;
  1112. int format_found = 0;
  1113. AST_RWLIST_RDLOCK(&formats);
  1114. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1115. fs = NULL;
  1116. if (!exts_compare(f->exts, type))
  1117. continue;
  1118. else
  1119. format_found = 1;
  1120. fn = build_filename(filename, type);
  1121. if (!fn) {
  1122. continue;
  1123. }
  1124. errno = 0;
  1125. bfile = fopen(fn, "r");
  1126. if (!bfile || (fs = get_filestream(f, bfile)) == NULL || open_wrapper(fs) ) {
  1127. ast_log(LOG_WARNING, "Unable to open %s\n", fn);
  1128. if (fs) {
  1129. ast_closestream(fs);
  1130. }
  1131. fs = NULL;
  1132. bfile = NULL;
  1133. ast_free(fn);
  1134. break;
  1135. }
  1136. /* found it */
  1137. fs->trans = NULL;
  1138. fs->fmt = f;
  1139. fs->flags = flags;
  1140. fs->mode = mode;
  1141. fs->filename = ast_strdup(filename);
  1142. fs->vfs = NULL;
  1143. ast_free(fn);
  1144. break;
  1145. }
  1146. AST_RWLIST_UNLOCK(&formats);
  1147. if (!format_found)
  1148. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  1149. return fs;
  1150. }
  1151. struct ast_filestream *ast_writefile(const char *filename, const char *type, const char *comment, int flags, int check, mode_t mode)
  1152. {
  1153. int fd, myflags = 0;
  1154. /* compiler claims this variable can be used before initialization... */
  1155. FILE *bfile = NULL;
  1156. struct ast_format_def *f;
  1157. struct ast_filestream *fs = NULL;
  1158. char *buf = NULL;
  1159. size_t size = 0;
  1160. int format_found = 0;
  1161. AST_RWLIST_RDLOCK(&formats);
  1162. /* set the O_TRUNC flag if and only if there is no O_APPEND specified */
  1163. /* We really can't use O_APPEND as it will break WAV header updates */
  1164. if (flags & O_APPEND) {
  1165. flags &= ~O_APPEND;
  1166. } else {
  1167. myflags = O_TRUNC;
  1168. }
  1169. myflags |= O_WRONLY | O_CREAT;
  1170. /* XXX need to fix this - we should just do the fopen,
  1171. * not open followed by fdopen()
  1172. */
  1173. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1174. char *fn, *orig_fn = NULL;
  1175. if (fs)
  1176. break;
  1177. if (!exts_compare(f->exts, type))
  1178. continue;
  1179. else
  1180. format_found = 1;
  1181. fn = build_filename(filename, type);
  1182. if (!fn) {
  1183. continue;
  1184. }
  1185. fd = open(fn, flags | myflags, mode);
  1186. if (fd > -1) {
  1187. /* fdopen() the resulting file stream */
  1188. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  1189. if (!bfile) {
  1190. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  1191. close(fd);
  1192. fd = -1;
  1193. }
  1194. }
  1195. if (ast_opt_cache_record_files && (fd > -1)) {
  1196. char *c;
  1197. fclose(bfile); /* this also closes fd */
  1198. /*
  1199. We touch orig_fn just as a place-holder so other things (like vmail) see the file is there.
  1200. What we are really doing is writing to record_cache_dir until we are done then we will mv the file into place.
  1201. */
  1202. orig_fn = ast_strdupa(fn);
  1203. for (c = fn; *c; c++)
  1204. if (*c == '/')
  1205. *c = '_';
  1206. size = strlen(fn) + strlen(record_cache_dir) + 2;
  1207. buf = ast_alloca(size);
  1208. strcpy(buf, record_cache_dir);
  1209. strcat(buf, "/");
  1210. strcat(buf, fn);
  1211. ast_free(fn);
  1212. fn = buf;
  1213. fd = open(fn, flags | myflags, mode);
  1214. if (fd > -1) {
  1215. /* fdopen() the resulting file stream */
  1216. bfile = fdopen(fd, ((flags | myflags) & O_RDWR) ? "w+" : "w");
  1217. if (!bfile) {
  1218. ast_log(LOG_WARNING, "Whoa, fdopen failed: %s!\n", strerror(errno));
  1219. close(fd);
  1220. fd = -1;
  1221. }
  1222. }
  1223. }
  1224. if (fd > -1) {
  1225. errno = 0;
  1226. fs = get_filestream(f, bfile);
  1227. if (fs) {
  1228. if ((fs->write_buffer = ast_malloc(32768))) {
  1229. setvbuf(fs->f, fs->write_buffer, _IOFBF, 32768);
  1230. }
  1231. }
  1232. if (!fs || rewrite_wrapper(fs, comment)) {
  1233. ast_log(LOG_WARNING, "Unable to rewrite %s\n", fn);
  1234. close(fd);
  1235. if (orig_fn) {
  1236. unlink(fn);
  1237. unlink(orig_fn);
  1238. }
  1239. if (fs) {
  1240. ast_closestream(fs);
  1241. fs = NULL;
  1242. }
  1243. if (!buf) {
  1244. ast_free(fn);
  1245. }
  1246. continue;
  1247. }
  1248. fs->trans = NULL;
  1249. fs->fmt = f;
  1250. fs->flags = flags;
  1251. fs->mode = mode;
  1252. if (orig_fn) {
  1253. fs->realfilename = ast_strdup(orig_fn);
  1254. fs->filename = ast_strdup(fn);
  1255. } else {
  1256. fs->realfilename = NULL;
  1257. fs->filename = ast_strdup(filename);
  1258. }
  1259. fs->vfs = NULL;
  1260. /* If truncated, we'll be at the beginning; if not truncated, then append */
  1261. f->seek(fs, 0, SEEK_END);
  1262. } else if (errno != EEXIST) {
  1263. ast_log(LOG_WARNING, "Unable to open file %s: %s\n", fn, strerror(errno));
  1264. if (orig_fn)
  1265. unlink(orig_fn);
  1266. }
  1267. /* if buf != NULL then fn is already free and pointing to it */
  1268. if (!buf)
  1269. ast_free(fn);
  1270. }
  1271. AST_RWLIST_UNLOCK(&formats);
  1272. if (!format_found)
  1273. ast_log(LOG_WARNING, "No such format '%s'\n", type);
  1274. return fs;
  1275. }
  1276. static void waitstream_control(struct ast_channel *c,
  1277. enum ast_waitstream_fr_cb_values type,
  1278. ast_waitstream_fr_cb cb,
  1279. int skip_ms)
  1280. {
  1281. switch (type)
  1282. {
  1283. case AST_WAITSTREAM_CB_FASTFORWARD:
  1284. {
  1285. int eoftest;
  1286. ast_stream_fastforward(ast_channel_stream(c), skip_ms);
  1287. eoftest = fgetc(ast_channel_stream(c)->f);
  1288. if (feof(ast_channel_stream(c)->f)) {
  1289. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1290. } else {
  1291. ungetc(eoftest, ast_channel_stream(c)->f);
  1292. }
  1293. }
  1294. break;
  1295. case AST_WAITSTREAM_CB_REWIND:
  1296. ast_stream_rewind(ast_channel_stream(c), skip_ms);
  1297. break;
  1298. default:
  1299. break;
  1300. }
  1301. if (cb) {
  1302. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
  1303. cb(c, ms_len, type);
  1304. }
  1305. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1306. "Control: %s\r\n"
  1307. "SkipMs: %d\r\n",
  1308. ast_channel_name(c),
  1309. (type == AST_WAITSTREAM_CB_FASTFORWARD) ? "FastForward" : "Rewind",
  1310. skip_ms);
  1311. }
  1312. /*!
  1313. * \brief the core of all waitstream() functions
  1314. */
  1315. static int waitstream_core(struct ast_channel *c,
  1316. const char *breakon,
  1317. const char *forward,
  1318. const char *reverse,
  1319. int skip_ms,
  1320. int audiofd,
  1321. int cmdfd,
  1322. const char *context,
  1323. ast_waitstream_fr_cb cb)
  1324. {
  1325. const char *orig_chan_name = NULL;
  1326. int err = 0;
  1327. if (!breakon)
  1328. breakon = "";
  1329. if (!forward)
  1330. forward = "";
  1331. if (!reverse)
  1332. reverse = "";
  1333. /* Switch the channel to end DTMF frame only. waitstream_core doesn't care about the start of DTMF. */
  1334. ast_channel_set_flag(c, AST_FLAG_END_DTMF_ONLY);
  1335. if (ast_test_flag(ast_channel_flags(c), AST_FLAG_MASQ_NOSTREAM))
  1336. orig_chan_name = ast_strdupa(ast_channel_name(c));
  1337. if (ast_channel_stream(c) && cb) {
  1338. long ms_len = ast_tellstream(ast_channel_stream(c)) / (ast_format_get_sample_rate(ast_channel_stream(c)->fmt->format) / 1000);
  1339. cb(c, ms_len, AST_WAITSTREAM_CB_START);
  1340. }
  1341. while (ast_channel_stream(c)) {
  1342. int res;
  1343. int ms;
  1344. if (orig_chan_name && strcasecmp(orig_chan_name, ast_channel_name(c))) {
  1345. ast_stopstream(c);
  1346. err = 1;
  1347. break;
  1348. }
  1349. ms = ast_sched_wait(ast_channel_sched(c));
  1350. if (ms < 0 && !ast_channel_timingfunc(c)) {
  1351. ast_stopstream(c);
  1352. break;
  1353. }
  1354. if (ms < 0)
  1355. ms = 1000;
  1356. if (cmdfd < 0) {
  1357. res = ast_waitfor(c, ms);
  1358. if (res < 0) {
  1359. ast_log(LOG_WARNING, "Select failed (%s)\n", strerror(errno));
  1360. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1361. return res;
  1362. }
  1363. } else {
  1364. int outfd;
  1365. struct ast_channel *rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
  1366. if (!rchan && (outfd < 0) && (ms)) {
  1367. /* Continue */
  1368. if (errno == EINTR)
  1369. continue;
  1370. ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
  1371. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1372. return -1;
  1373. } else if (outfd > -1) { /* this requires cmdfd set */
  1374. /* The FD we were watching has something waiting */
  1375. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1376. return 1;
  1377. }
  1378. /* if rchan is set, it is 'c' */
  1379. res = rchan ? 1 : 0; /* map into 'res' values */
  1380. }
  1381. if (res > 0) {
  1382. struct ast_frame *fr = ast_read(c);
  1383. if (!fr) {
  1384. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1385. return -1;
  1386. }
  1387. switch (fr->frametype) {
  1388. case AST_FRAME_DTMF_END:
  1389. if (context) {
  1390. const char exten[2] = { fr->subclass.integer, '\0' };
  1391. if (ast_exists_extension(c, context, exten, 1,
  1392. S_COR(ast_channel_caller(c)->id.number.valid, ast_channel_caller(c)->id.number.str, NULL))) {
  1393. res = fr->subclass.integer;
  1394. ast_frfree(fr);
  1395. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1396. return res;
  1397. }
  1398. } else {
  1399. res = fr->subclass.integer;
  1400. if (strchr(forward, res)) {
  1401. waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
  1402. } else if (strchr(reverse, res)) {
  1403. waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
  1404. } else if (strchr(breakon, res)) {
  1405. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1406. "Control: %s\r\n",
  1407. ast_channel_name(c),
  1408. "Break");
  1409. ast_frfree(fr);
  1410. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1411. return res;
  1412. }
  1413. }
  1414. break;
  1415. case AST_FRAME_CONTROL:
  1416. switch (fr->subclass.integer) {
  1417. case AST_CONTROL_STREAM_STOP:
  1418. case AST_CONTROL_STREAM_SUSPEND:
  1419. case AST_CONTROL_STREAM_RESTART:
  1420. /* Fall-through and break out */
  1421. ast_test_suite_event_notify("PLAYBACK","Channel: %s\r\n"
  1422. "Control: %s\r\n",
  1423. ast_channel_name(c),
  1424. "Break");
  1425. res = fr->subclass.integer;
  1426. ast_frfree(fr);
  1427. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1428. return res;
  1429. case AST_CONTROL_STREAM_REVERSE:
  1430. if (!skip_ms) {
  1431. skip_ms = 3000;
  1432. }
  1433. waitstream_control(c, AST_WAITSTREAM_CB_REWIND, cb, skip_ms);
  1434. break;
  1435. case AST_CONTROL_STREAM_FORWARD:
  1436. if (!skip_ms) {
  1437. skip_ms = 3000;
  1438. }
  1439. waitstream_control(c, AST_WAITSTREAM_CB_FASTFORWARD, cb, skip_ms);
  1440. break;
  1441. case AST_CONTROL_HANGUP:
  1442. case AST_CONTROL_BUSY:
  1443. case AST_CONTROL_CONGESTION:
  1444. ast_frfree(fr);
  1445. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1446. return -1;
  1447. case AST_CONTROL_RINGING:
  1448. case AST_CONTROL_ANSWER:
  1449. case AST_CONTROL_VIDUPDATE:
  1450. case AST_CONTROL_SRCUPDATE:
  1451. case AST_CONTROL_SRCCHANGE:
  1452. case AST_CONTROL_HOLD:
  1453. case AST_CONTROL_UNHOLD:
  1454. case AST_CONTROL_CONNECTED_LINE:
  1455. case AST_CONTROL_REDIRECTING:
  1456. case AST_CONTROL_AOC:
  1457. case AST_CONTROL_UPDATE_RTP_PEER:
  1458. case AST_CONTROL_PVT_CAUSE_CODE:
  1459. case -1:
  1460. /* Unimportant */
  1461. break;
  1462. default:
  1463. ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", fr->subclass.integer);
  1464. }
  1465. break;
  1466. case AST_FRAME_VOICE:
  1467. /* Write audio if appropriate */
  1468. if (audiofd > -1) {
  1469. if (write(audiofd, fr->data.ptr, fr->datalen) < 0) {
  1470. ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
  1471. }
  1472. }
  1473. default:
  1474. /* Ignore all others */
  1475. break;
  1476. }
  1477. ast_frfree(fr);
  1478. }
  1479. ast_sched_runq(ast_channel_sched(c));
  1480. }
  1481. ast_channel_clear_flag(c, AST_FLAG_END_DTMF_ONLY);
  1482. return (err || ast_channel_softhangup_internal_flag(c)) ? -1 : 0;
  1483. }
  1484. int ast_waitstream_fr_w_cb(struct ast_channel *c,
  1485. const char *breakon,
  1486. const char *forward,
  1487. const char *reverse,
  1488. int ms,
  1489. ast_waitstream_fr_cb cb)
  1490. {
  1491. return waitstream_core(c, breakon, forward, reverse, ms,
  1492. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, cb);
  1493. }
  1494. int ast_waitstream_fr(struct ast_channel *c, const char *breakon, const char *forward, const char *reverse, int ms)
  1495. {
  1496. return waitstream_core(c, breakon, forward, reverse, ms,
  1497. -1 /* no audiofd */, -1 /* no cmdfd */, NULL /* no context */, NULL /* no callback */);
  1498. }
  1499. /*! \internal
  1500. * \brief Clean up the return value of a waitstream call
  1501. *
  1502. * It's possible for a control frame to come in from an external source and break the
  1503. * playback. From a consumer of most ast_waitstream_* function callers, this should
  1504. * appear like normal playback termination, i.e., return 0 and not the value of the
  1505. * control frame.
  1506. */
  1507. static int sanitize_waitstream_return(int return_value)
  1508. {
  1509. switch (return_value) {
  1510. case AST_CONTROL_STREAM_STOP:
  1511. case AST_CONTROL_STREAM_SUSPEND:
  1512. case AST_CONTROL_STREAM_RESTART:
  1513. /* Fall through and set return_value to 0 */
  1514. return_value = 0;
  1515. break;
  1516. default:
  1517. /* Do nothing */
  1518. break;
  1519. }
  1520. return return_value;
  1521. }
  1522. int ast_waitstream(struct ast_channel *c, const char *breakon)
  1523. {
  1524. int res;
  1525. res = waitstream_core(c, breakon, NULL, NULL, 0, -1, -1, NULL, NULL /* no callback */);
  1526. return sanitize_waitstream_return(res);
  1527. }
  1528. int ast_waitstream_full(struct ast_channel *c, const char *breakon, int audiofd, int cmdfd)
  1529. {
  1530. int res;
  1531. res = waitstream_core(c, breakon, NULL, NULL, 0,
  1532. audiofd, cmdfd, NULL /* no context */, NULL /* no callback */);
  1533. return sanitize_waitstream_return(res);
  1534. }
  1535. int ast_waitstream_exten(struct ast_channel *c, const char *context)
  1536. {
  1537. int res;
  1538. /* Waitstream, with return in the case of a valid 1 digit extension */
  1539. /* in the current or specified context being pressed */
  1540. if (!context)
  1541. context = ast_channel_context(c);
  1542. res = waitstream_core(c, NULL, NULL, NULL, 0,
  1543. -1, -1, context, NULL /* no callback */);
  1544. return sanitize_waitstream_return(res);
  1545. }
  1546. /*
  1547. * if the file name is non-empty, try to play it.
  1548. * Return 0 if success, -1 if error, digit if interrupted by a digit.
  1549. * If digits == "" then we can simply check for non-zero.
  1550. */
  1551. int ast_stream_and_wait(struct ast_channel *chan, const char *file, const char *digits)
  1552. {
  1553. int res = 0;
  1554. if (!ast_strlen_zero(file)) {
  1555. res = ast_streamfile(chan, file, ast_channel_language(chan));
  1556. if (!res) {
  1557. res = ast_waitstream(chan, digits);
  1558. }
  1559. }
  1560. return res;
  1561. }
  1562. char *ast_format_str_reduce(char *fmts)
  1563. {
  1564. struct ast_format_def *f;
  1565. struct ast_format_def *fmts_ptr[AST_MAX_FORMATS];
  1566. char *fmts_str[AST_MAX_FORMATS];
  1567. char *stringp, *type;
  1568. char *orig = fmts;
  1569. int i, j, x, first, found = 0;
  1570. int len = strlen(fmts) + 1;
  1571. int res;
  1572. if (AST_RWLIST_RDLOCK(&formats)) {
  1573. ast_log(LOG_WARNING, "Unable to lock format list\n");
  1574. return NULL;
  1575. }
  1576. stringp = ast_strdupa(fmts);
  1577. for (x = 0; (type = strsep(&stringp, "|")) && x < AST_MAX_FORMATS; x++) {
  1578. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1579. if (exts_compare(f->exts, type)) {
  1580. found = 1;
  1581. break;
  1582. }
  1583. }
  1584. fmts_str[x] = type;
  1585. if (found) {
  1586. fmts_ptr[x] = f;
  1587. } else {
  1588. fmts_ptr[x] = NULL;
  1589. }
  1590. }
  1591. AST_RWLIST_UNLOCK(&formats);
  1592. first = 1;
  1593. for (i = 0; i < x; i++) {
  1594. /* ignore invalid entries */
  1595. if (!fmts_ptr[i]) {
  1596. ast_log(LOG_WARNING, "ignoring unknown format '%s'\n", fmts_str[i]);
  1597. continue;
  1598. }
  1599. /* special handling for the first entry */
  1600. if (first) {
  1601. res = snprintf(fmts, len, "%s", fmts_str[i]);
  1602. fmts += res;
  1603. len -= res;
  1604. first = 0;
  1605. continue;
  1606. }
  1607. found = 0;
  1608. for (j = 0; j < i; j++) {
  1609. /* this is a duplicate */
  1610. if (fmts_ptr[j] == fmts_ptr[i]) {
  1611. found = 1;
  1612. break;
  1613. }
  1614. }
  1615. if (!found) {
  1616. res = snprintf(fmts, len, "|%s", fmts_str[i]);
  1617. fmts += res;
  1618. len -= res;
  1619. }
  1620. }
  1621. if (first) {
  1622. ast_log(LOG_WARNING, "no known formats found in format list (%s)\n", orig);
  1623. return NULL;
  1624. }
  1625. return orig;
  1626. }
  1627. static char *handle_cli_core_show_file_formats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1628. {
  1629. #define FORMAT "%-10s %-10s %-20s\n"
  1630. #define FORMAT2 "%-10s %-10s %-20s\n"
  1631. struct ast_format_def *f;
  1632. int count_fmt = 0;
  1633. switch (cmd) {
  1634. case CLI_INIT:
  1635. e->command = "core show file formats";
  1636. e->usage =
  1637. "Usage: core show file formats\n"
  1638. " Displays currently registered file formats (if any).\n";
  1639. return NULL;
  1640. case CLI_GENERATE:
  1641. return NULL;
  1642. }
  1643. if (a->argc != 4)
  1644. return CLI_SHOWUSAGE;
  1645. ast_cli(a->fd, FORMAT, "Format", "Name", "Extensions");
  1646. ast_cli(a->fd, FORMAT, "------", "----", "----------");
  1647. AST_RWLIST_RDLOCK(&formats);
  1648. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1649. ast_cli(a->fd, FORMAT2, ast_format_get_name(f->format), f->name, f->exts);
  1650. count_fmt++;
  1651. }
  1652. AST_RWLIST_UNLOCK(&formats);
  1653. ast_cli(a->fd, "%d file formats registered.\n", count_fmt);
  1654. return CLI_SUCCESS;
  1655. #undef FORMAT
  1656. #undef FORMAT2
  1657. }
  1658. struct ast_format *ast_get_format_for_file_ext(const char *file_ext)
  1659. {
  1660. struct ast_format_def *f;
  1661. SCOPED_RDLOCK(lock, &formats.lock);
  1662. AST_RWLIST_TRAVERSE(&formats, f, list) {
  1663. if (exts_compare(f->exts, file_ext)) {
  1664. return f->format;
  1665. }
  1666. }
  1667. return NULL;
  1668. }
  1669. static struct ast_cli_entry cli_file[] = {
  1670. AST_CLI_DEFINE(handle_cli_core_show_file_formats, "Displays file formats")
  1671. };
  1672. static void file_shutdown(void)
  1673. {
  1674. ast_cli_unregister_multiple(cli_file, ARRAY_LEN(cli_file));
  1675. STASIS_MESSAGE_TYPE_CLEANUP(ast_format_register_type);
  1676. STASIS_MESSAGE_TYPE_CLEANUP(ast_format_unregister_type);
  1677. }
  1678. int ast_file_init(void)
  1679. {
  1680. STASIS_MESSAGE_TYPE_INIT(ast_format_register_type);
  1681. STASIS_MESSAGE_TYPE_INIT(ast_format_unregister_type);
  1682. ast_cli_register_multiple(cli_file, ARRAY_LEN(cli_file));
  1683. ast_register_cleanup(file_shutdown);
  1684. return 0;
  1685. }