file.c 46 KB

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