res_musiconhold.c 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2010, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Routines implementing music on hold
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. /*! \li \ref res_musiconhold.c uses the configuration file \ref musiconhold.conf
  25. * \addtogroup configuration_file Configuration Files
  26. */
  27. /*!
  28. * \page musiconhold.conf musiconhold.conf
  29. * \verbinclude musiconhold.conf.sample
  30. */
  31. /*** MODULEINFO
  32. <conflict>win32</conflict>
  33. <support_level>core</support_level>
  34. ***/
  35. #include "asterisk.h"
  36. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  37. #include <ctype.h>
  38. #include <signal.h>
  39. #include <sys/time.h>
  40. #include <sys/signal.h>
  41. #include <netinet/in.h>
  42. #include <sys/stat.h>
  43. #include <dirent.h>
  44. #ifdef SOLARIS
  45. #include <thread.h>
  46. #endif
  47. #include "asterisk/lock.h"
  48. #include "asterisk/file.h"
  49. #include "asterisk/channel.h"
  50. #include "asterisk/pbx.h"
  51. #include "asterisk/app.h"
  52. #include "asterisk/module.h"
  53. #include "asterisk/translate.h"
  54. #include "asterisk/say.h"
  55. #include "asterisk/musiconhold.h"
  56. #include "asterisk/config.h"
  57. #include "asterisk/utils.h"
  58. #include "asterisk/cli.h"
  59. #include "asterisk/stringfields.h"
  60. #include "asterisk/linkedlists.h"
  61. #include "asterisk/stasis.h"
  62. #include "asterisk/stasis_channels.h"
  63. #include "asterisk/paths.h"
  64. #include "asterisk/astobj2.h"
  65. #include "asterisk/timing.h"
  66. #include "asterisk/time.h"
  67. #include "asterisk/poll-compat.h"
  68. #define INITIAL_NUM_FILES 8
  69. #define HANDLE_REF 1
  70. #define DONT_UNREF 0
  71. /*** DOCUMENTATION
  72. <application name="MusicOnHold" language="en_US">
  73. <synopsis>
  74. Play Music On Hold indefinitely.
  75. </synopsis>
  76. <syntax>
  77. <parameter name="class" required="true" />
  78. <parameter name="duration" />
  79. </syntax>
  80. <description>
  81. <para>Plays hold music specified by class. If omitted, the default music
  82. source for the channel will be used. Change the default class with
  83. Set(CHANNEL(musicclass)=...). If duration is given, hold music will be played
  84. specified number of seconds. If duration is ommited, music plays indefinitely.
  85. Returns <literal>0</literal> when done, <literal>-1</literal> on hangup.</para>
  86. <para>This application does not automatically answer and should be preceeded by
  87. an application such as Answer() or Progress().</para>
  88. </description>
  89. </application>
  90. <application name="StartMusicOnHold" language="en_US">
  91. <synopsis>
  92. Play Music On Hold.
  93. </synopsis>
  94. <syntax>
  95. <parameter name="class" required="true" />
  96. </syntax>
  97. <description>
  98. <para>Starts playing music on hold, uses default music class for channel.
  99. Starts playing music specified by class. If omitted, the default music
  100. source for the channel will be used. Always returns <literal>0</literal>.</para>
  101. </description>
  102. </application>
  103. <application name="StopMusicOnHold" language="en_US">
  104. <synopsis>
  105. Stop playing Music On Hold.
  106. </synopsis>
  107. <syntax />
  108. <description>
  109. <para>Stops playing music on hold.</para>
  110. </description>
  111. </application>
  112. ***/
  113. static const char play_moh[] = "MusicOnHold";
  114. static const char start_moh[] = "StartMusicOnHold";
  115. static const char stop_moh[] = "StopMusicOnHold";
  116. static int respawn_time = 20;
  117. struct moh_files_state {
  118. /*! Holds a reference to the MOH class. */
  119. struct mohclass *class;
  120. struct ast_format *origwfmt;
  121. struct ast_format *mohwfmt;
  122. int announcement;
  123. int samples;
  124. int sample_queue;
  125. int pos;
  126. int save_pos;
  127. int save_total;
  128. char name[MAX_MUSICCLASS];
  129. char save_pos_filename[PATH_MAX];
  130. };
  131. #define MOH_QUIET (1 << 0)
  132. #define MOH_SINGLE (1 << 1)
  133. #define MOH_CUSTOM (1 << 2)
  134. #define MOH_RANDOMIZE (1 << 3)
  135. #define MOH_SORTALPHA (1 << 4)
  136. #define MOH_CACHERTCLASSES (1 << 5) /*!< Should we use a separate instance of MOH for each user or not */
  137. #define MOH_ANNOUNCEMENT (1 << 6) /*!< Do we play announcement files between songs on this channel? */
  138. /* Custom astobj2 flag */
  139. #define MOH_NOTDELETED (1 << 30) /*!< Find only records that aren't deleted? */
  140. #define MOH_REALTIME (1 << 31) /*!< Find only records that are realtime */
  141. static struct ast_flags global_flags[1] = {{0}}; /*!< global MOH_ flags */
  142. enum kill_methods {
  143. KILL_METHOD_PROCESS_GROUP = 0,
  144. KILL_METHOD_PROCESS
  145. };
  146. struct mohclass {
  147. char name[MAX_MUSICCLASS];
  148. char dir[256];
  149. char args[256];
  150. char announcement[256];
  151. char mode[80];
  152. char digit;
  153. /*! A dynamically sized array to hold the list of filenames in "files" mode */
  154. char **filearray;
  155. /*! The current size of the filearray */
  156. int allowed_files;
  157. /*! The current number of files loaded into the filearray */
  158. int total_files;
  159. unsigned int flags;
  160. /*! The format from the MOH source, not applicable to "files" mode */
  161. struct ast_format *format;
  162. /*! The pid of the external application delivering MOH */
  163. int pid;
  164. time_t start;
  165. pthread_t thread;
  166. /*! Millisecond delay between kill attempts */
  167. size_t kill_delay;
  168. /*! Kill method */
  169. enum kill_methods kill_method;
  170. /*! Source of audio */
  171. int srcfd;
  172. /*! Generic timer */
  173. struct ast_timer *timer;
  174. /*! Created on the fly, from RT engine */
  175. unsigned int realtime:1;
  176. unsigned int delete:1;
  177. AST_LIST_HEAD_NOLOCK(, mohdata) members;
  178. AST_LIST_ENTRY(mohclass) list;
  179. };
  180. struct mohdata {
  181. int pipe[2];
  182. struct ast_format *origwfmt;
  183. struct mohclass *parent;
  184. struct ast_frame f;
  185. AST_LIST_ENTRY(mohdata) list;
  186. };
  187. static struct ao2_container *mohclasses;
  188. #define LOCAL_MPG_123 "/usr/local/bin/mpg123"
  189. #define MPG_123 "/usr/bin/mpg123"
  190. #define MAX_MP3S 256
  191. static int reload(void);
  192. #define mohclass_ref(class,string) (ao2_t_ref((class), +1, (string)), class)
  193. #ifndef REF_DEBUG
  194. #define mohclass_unref(class,string) ({ ao2_t_ref((class), -1, (string)); (struct mohclass *) NULL; })
  195. #else
  196. #define mohclass_unref(class,string) _mohclass_unref(class, string, __FILE__,__LINE__,__PRETTY_FUNCTION__)
  197. static struct mohclass *_mohclass_unref(struct mohclass *class, const char *tag, const char *file, int line, const char *funcname)
  198. {
  199. struct mohclass *dup = ao2_callback(mohclasses, OBJ_POINTER, ao2_match_by_addr, class);
  200. if (dup) {
  201. if (__ao2_ref_debug(dup, -1, (char *) tag, (char *) file, line, funcname) == 2) {
  202. ast_log(LOG_WARNING, "Attempt to unref mohclass %p (%s) when only 1 ref remained, and class is still in a container! (at %s:%d (%s))\n",
  203. class, class->name, file, line, funcname);
  204. } else {
  205. ao2_ref(class, -1);
  206. }
  207. } else {
  208. __ao2_ref_debug(class, -1, (char *) tag, (char *) file, line, funcname);
  209. }
  210. return NULL;
  211. }
  212. #endif
  213. static void moh_post_start(struct ast_channel *chan, const char *moh_class_name)
  214. {
  215. struct stasis_message *message;
  216. struct ast_json *json_object;
  217. ast_verb(3, "Started music on hold, class '%s', on channel '%s'\n",
  218. moh_class_name, ast_channel_name(chan));
  219. json_object = ast_json_pack("{s: s}", "class", moh_class_name);
  220. if (!json_object) {
  221. return;
  222. }
  223. message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
  224. ast_channel_moh_start_type(), json_object);
  225. if (message) {
  226. /* A channel snapshot must have been in the cache. */
  227. ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
  228. stasis_publish(ast_channel_topic(chan), message);
  229. }
  230. ao2_cleanup(message);
  231. ast_json_unref(json_object);
  232. }
  233. static void moh_post_stop(struct ast_channel *chan)
  234. {
  235. struct stasis_message *message;
  236. ast_verb(3, "Stopped music on hold on %s\n", ast_channel_name(chan));
  237. message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
  238. ast_channel_moh_stop_type(), NULL);
  239. if (message) {
  240. /* A channel snapshot must have been in the cache. */
  241. ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
  242. stasis_publish(ast_channel_topic(chan), message);
  243. }
  244. ao2_cleanup(message);
  245. }
  246. static void moh_files_release(struct ast_channel *chan, void *data)
  247. {
  248. struct moh_files_state *state;
  249. if (!chan || !ast_channel_music_state(chan)) {
  250. return;
  251. }
  252. state = ast_channel_music_state(chan);
  253. if (ast_channel_stream(chan)) {
  254. ast_closestream(ast_channel_stream(chan));
  255. ast_channel_stream_set(chan, NULL);
  256. }
  257. moh_post_stop(chan);
  258. ao2_ref(state->mohwfmt, -1);
  259. state->mohwfmt = NULL; /* make sure to clear this format before restoring the original format */
  260. if (state->origwfmt && ast_set_write_format(chan, state->origwfmt)) {
  261. ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n", ast_channel_name(chan),
  262. ast_format_get_name(state->origwfmt));
  263. }
  264. ao2_cleanup(state->origwfmt);
  265. state->origwfmt = NULL;
  266. state->save_pos = state->pos;
  267. state->announcement = 0;
  268. state->class = mohclass_unref(state->class, "Unreffing channel's music class upon deactivation of generator");
  269. }
  270. static int ast_moh_files_next(struct ast_channel *chan)
  271. {
  272. struct moh_files_state *state = ast_channel_music_state(chan);
  273. int tries;
  274. /* Discontinue a stream if it is running already */
  275. if (ast_channel_stream(chan)) {
  276. ast_closestream(ast_channel_stream(chan));
  277. ast_channel_stream_set(chan, NULL);
  278. }
  279. if (ast_test_flag(state->class, MOH_ANNOUNCEMENT) && state->announcement == 0) {
  280. state->announcement = 1;
  281. if (ast_openstream_full(chan, state->class->announcement, ast_channel_language(chan), 1)) {
  282. ast_debug(1, "%s Opened announcement '%s'\n", ast_channel_name(chan), state->class->announcement);
  283. return 0;
  284. }
  285. } else {
  286. state->announcement = 0;
  287. }
  288. if (!state->class->total_files) {
  289. ast_log(LOG_WARNING, "No files available for class '%s'\n", state->class->name);
  290. return -1;
  291. }
  292. if (state->pos == 0 && ast_strlen_zero(state->save_pos_filename)) {
  293. /* First time so lets play the file. */
  294. state->save_pos = -1;
  295. } else if (state->save_pos >= 0 && state->save_pos < state->class->total_files && !strcmp(state->class->filearray[state->save_pos], state->save_pos_filename)) {
  296. /* If a specific file has been saved confirm it still exists and that it is still valid */
  297. state->pos = state->save_pos;
  298. state->save_pos = -1;
  299. } else if (ast_test_flag(state->class, MOH_RANDOMIZE)) {
  300. /* Get a random file and ensure we can open it */
  301. for (tries = 0; tries < 20; tries++) {
  302. state->pos = ast_random() % state->class->total_files;
  303. if (ast_fileexists(state->class->filearray[state->pos], NULL, NULL) > 0) {
  304. break;
  305. }
  306. }
  307. state->save_pos = -1;
  308. state->samples = 0;
  309. } else {
  310. /* This is easy, just increment our position and make sure we don't exceed the total file count */
  311. state->pos++;
  312. state->pos %= state->class->total_files;
  313. state->save_pos = -1;
  314. state->samples = 0;
  315. }
  316. for (tries = 0; tries < state->class->total_files; ++tries) {
  317. if (ast_openstream_full(chan, state->class->filearray[state->pos], ast_channel_language(chan), 1)) {
  318. break;
  319. }
  320. ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", state->class->filearray[state->pos], strerror(errno));
  321. state->pos++;
  322. state->pos %= state->class->total_files;
  323. }
  324. if (tries == state->class->total_files) {
  325. return -1;
  326. }
  327. /* Record the pointer to the filename for position resuming later */
  328. ast_copy_string(state->save_pos_filename, state->class->filearray[state->pos], sizeof(state->save_pos_filename));
  329. ast_debug(1, "%s Opened file %d '%s'\n", ast_channel_name(chan), state->pos, state->class->filearray[state->pos]);
  330. if (state->samples) {
  331. size_t loc;
  332. /* seek *SHOULD* be good since it's from a known location */
  333. ast_seekstream(ast_channel_stream(chan), state->samples, SEEK_SET);
  334. /* if the seek failed then recover because if there is not a valid read,
  335. * moh_files_generate will return -1 and MOH will stop */
  336. loc = ast_tellstream(ast_channel_stream(chan));
  337. if (state->samples > loc && loc) {
  338. /* seek one sample from the end for one guaranteed valid read */
  339. ast_seekstream(ast_channel_stream(chan), 1, SEEK_END);
  340. }
  341. }
  342. return 0;
  343. }
  344. static struct ast_frame *moh_files_readframe(struct ast_channel *chan)
  345. {
  346. struct ast_frame *f;
  347. f = ast_readframe(ast_channel_stream(chan));
  348. if (!f) {
  349. /* Either there was no file stream setup or we reached EOF. */
  350. if (!ast_moh_files_next(chan)) {
  351. /*
  352. * Either we resetup the previously saved file stream position
  353. * or we started a new file stream.
  354. */
  355. f = ast_readframe(ast_channel_stream(chan));
  356. if (!f) {
  357. /*
  358. * We can get here if we were very unlucky because the
  359. * resetup file stream was saved at EOF when MOH was
  360. * previously stopped.
  361. */
  362. if (!ast_moh_files_next(chan)) {
  363. f = ast_readframe(ast_channel_stream(chan));
  364. }
  365. }
  366. }
  367. }
  368. return f;
  369. }
  370. static void moh_files_write_format_change(struct ast_channel *chan, void *data)
  371. {
  372. struct moh_files_state *state = ast_channel_music_state(chan);
  373. /* In order to prevent a recursive call to this function as a result
  374. * of setting the moh write format back on the channel. Clear
  375. * the moh write format before setting the write format on the channel.*/
  376. if (state->origwfmt) {
  377. struct ast_format *tmp;
  378. tmp = ao2_bump(ast_channel_writeformat(chan));
  379. ao2_replace(state->origwfmt, NULL);
  380. if (state->mohwfmt) {
  381. ast_set_write_format(chan, state->mohwfmt);
  382. }
  383. state->origwfmt = tmp;
  384. }
  385. }
  386. static int moh_files_generator(struct ast_channel *chan, void *data, int len, int samples)
  387. {
  388. struct moh_files_state *state = ast_channel_music_state(chan);
  389. struct ast_frame *f = NULL;
  390. int res = 0;
  391. state->sample_queue += samples;
  392. while (state->sample_queue > 0) {
  393. ast_channel_lock(chan);
  394. f = moh_files_readframe(chan);
  395. /* We need to be sure that we unlock
  396. * the channel prior to calling
  397. * ast_write. Otherwise, the recursive locking
  398. * that occurs can cause deadlocks when using
  399. * indirect channels, like local channels
  400. */
  401. ast_channel_unlock(chan);
  402. if (!f) {
  403. return -1;
  404. }
  405. state->samples += f->samples;
  406. state->sample_queue -= f->samples;
  407. if (ast_format_cmp(f->subclass.format, state->mohwfmt) == AST_FORMAT_CMP_NOT_EQUAL) {
  408. ao2_replace(state->mohwfmt, f->subclass.format);
  409. }
  410. res = ast_write(chan, f);
  411. ast_frfree(f);
  412. if (res < 0) {
  413. ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
  414. return -1;
  415. }
  416. }
  417. return res;
  418. }
  419. static void *moh_files_alloc(struct ast_channel *chan, void *params)
  420. {
  421. struct moh_files_state *state;
  422. struct mohclass *class = params;
  423. state = ast_channel_music_state(chan);
  424. if (!state && (state = ast_calloc(1, sizeof(*state)))) {
  425. ast_channel_music_state_set(chan, state);
  426. ast_module_ref(ast_module_info->self);
  427. } else {
  428. if (!state) {
  429. return NULL;
  430. }
  431. if (state->class) {
  432. mohclass_unref(state->class, "Uh Oh. Restarting MOH with an active class");
  433. ast_log(LOG_WARNING, "Uh Oh. Restarting MOH with an active class\n");
  434. }
  435. }
  436. /* Resume MOH from where we left off last time or start from scratch? */
  437. if (state->save_total != class->total_files || strcmp(state->name, class->name) != 0) {
  438. /* Start MOH from scratch. */
  439. ao2_cleanup(state->origwfmt);
  440. ao2_cleanup(state->mohwfmt);
  441. memset(state, 0, sizeof(*state));
  442. if (ast_test_flag(class, MOH_RANDOMIZE) && class->total_files) {
  443. state->pos = ast_random() % class->total_files;
  444. }
  445. }
  446. state->class = mohclass_ref(class, "Reffing music class for channel");
  447. /* it's possible state is not a new allocation, don't leak old refs */
  448. ao2_replace(state->origwfmt, ast_channel_writeformat(chan));
  449. ao2_replace(state->mohwfmt, ast_channel_writeformat(chan));
  450. /* For comparison on restart of MOH (see above) */
  451. ast_copy_string(state->name, class->name, sizeof(state->name));
  452. state->save_total = class->total_files;
  453. moh_post_start(chan, class->name);
  454. return state;
  455. }
  456. static int moh_digit_match(void *obj, void *arg, int flags)
  457. {
  458. char *digit = arg;
  459. struct mohclass *class = obj;
  460. return (*digit == class->digit) ? CMP_MATCH | CMP_STOP : 0;
  461. }
  462. /*! \note This function should be called with the mohclasses list locked */
  463. static struct mohclass *get_mohbydigit(char digit)
  464. {
  465. return ao2_t_callback(mohclasses, 0, moh_digit_match, &digit, "digit callback");
  466. }
  467. static void moh_handle_digit(struct ast_channel *chan, char digit)
  468. {
  469. struct mohclass *class;
  470. const char *classname = NULL;
  471. if ((class = get_mohbydigit(digit))) {
  472. classname = ast_strdupa(class->name);
  473. class = mohclass_unref(class, "Unreffing ao2_find from finding by digit");
  474. ast_channel_musicclass_set(chan, classname);
  475. ast_moh_stop(chan);
  476. ast_moh_start(chan, classname, NULL);
  477. }
  478. }
  479. static struct ast_generator moh_file_stream = {
  480. .alloc = moh_files_alloc,
  481. .release = moh_files_release,
  482. .generate = moh_files_generator,
  483. .digit = moh_handle_digit,
  484. .write_format_change = moh_files_write_format_change,
  485. };
  486. static int spawn_mp3(struct mohclass *class)
  487. {
  488. int fds[2];
  489. int files = 0;
  490. char fns[MAX_MP3S][80];
  491. char *argv[MAX_MP3S + 50];
  492. char xargs[256];
  493. char *argptr;
  494. int argc = 0;
  495. DIR *dir = NULL;
  496. struct dirent *de;
  497. if (!strcasecmp(class->dir, "nodir")) {
  498. files = 1;
  499. } else {
  500. dir = opendir(class->dir);
  501. if (!dir && strncasecmp(class->dir, "http://", 7)) {
  502. ast_log(LOG_WARNING, "%s is not a valid directory\n", class->dir);
  503. return -1;
  504. }
  505. }
  506. if (!ast_test_flag(class, MOH_CUSTOM)) {
  507. argv[argc++] = "mpg123";
  508. argv[argc++] = "-q";
  509. argv[argc++] = "-s";
  510. argv[argc++] = "--mono";
  511. argv[argc++] = "-r";
  512. argv[argc++] = "8000";
  513. if (!ast_test_flag(class, MOH_SINGLE)) {
  514. argv[argc++] = "-b";
  515. argv[argc++] = "2048";
  516. }
  517. argv[argc++] = "-f";
  518. if (ast_test_flag(class, MOH_QUIET))
  519. argv[argc++] = "4096";
  520. else
  521. argv[argc++] = "8192";
  522. /* Look for extra arguments and add them to the list */
  523. ast_copy_string(xargs, class->args, sizeof(xargs));
  524. argptr = xargs;
  525. while (!ast_strlen_zero(argptr)) {
  526. argv[argc++] = argptr;
  527. strsep(&argptr, ",");
  528. }
  529. } else {
  530. /* Format arguments for argv vector */
  531. ast_copy_string(xargs, class->args, sizeof(xargs));
  532. argptr = xargs;
  533. while (!ast_strlen_zero(argptr)) {
  534. argv[argc++] = argptr;
  535. strsep(&argptr, " ");
  536. }
  537. }
  538. if (!strncasecmp(class->dir, "http://", 7)) {
  539. ast_copy_string(fns[files], class->dir, sizeof(fns[files]));
  540. argv[argc++] = fns[files];
  541. files++;
  542. } else if (dir) {
  543. while ((de = readdir(dir)) && (files < MAX_MP3S)) {
  544. if ((strlen(de->d_name) > 3) &&
  545. ((ast_test_flag(class, MOH_CUSTOM) &&
  546. (!strcasecmp(de->d_name + strlen(de->d_name) - 4, ".raw") ||
  547. !strcasecmp(de->d_name + strlen(de->d_name) - 4, ".sln"))) ||
  548. !strcasecmp(de->d_name + strlen(de->d_name) - 4, ".mp3"))) {
  549. ast_copy_string(fns[files], de->d_name, sizeof(fns[files]));
  550. argv[argc++] = fns[files];
  551. files++;
  552. }
  553. }
  554. }
  555. argv[argc] = NULL;
  556. if (dir) {
  557. closedir(dir);
  558. }
  559. if (pipe(fds)) {
  560. ast_log(LOG_WARNING, "Pipe failed\n");
  561. return -1;
  562. }
  563. if (!files) {
  564. ast_log(LOG_WARNING, "Found no files in '%s'\n", class->dir);
  565. close(fds[0]);
  566. close(fds[1]);
  567. return -1;
  568. }
  569. if (!strncasecmp(class->dir, "http://", 7) && time(NULL) - class->start < respawn_time) {
  570. sleep(respawn_time - (time(NULL) - class->start));
  571. }
  572. time(&class->start);
  573. class->pid = ast_safe_fork(0);
  574. if (class->pid < 0) {
  575. close(fds[0]);
  576. close(fds[1]);
  577. ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
  578. return -1;
  579. }
  580. if (!class->pid) {
  581. if (ast_opt_high_priority)
  582. ast_set_priority(0);
  583. close(fds[0]);
  584. /* Stdout goes to pipe */
  585. dup2(fds[1], STDOUT_FILENO);
  586. /* Close everything else */
  587. ast_close_fds_above_n(STDERR_FILENO);
  588. /* Child */
  589. if (strncasecmp(class->dir, "http://", 7) && strcasecmp(class->dir, "nodir") && chdir(class->dir) < 0) {
  590. ast_log(LOG_WARNING, "chdir() failed: %s\n", strerror(errno));
  591. _exit(1);
  592. }
  593. setpgid(0, getpid());
  594. if (ast_test_flag(class, MOH_CUSTOM)) {
  595. execv(argv[0], argv);
  596. } else {
  597. /* Default install is /usr/local/bin */
  598. execv(LOCAL_MPG_123, argv);
  599. /* Many places have it in /usr/bin */
  600. execv(MPG_123, argv);
  601. /* Check PATH as a last-ditch effort */
  602. execvp("mpg123", argv);
  603. }
  604. /* Can't use logger, since log FDs are closed */
  605. fprintf(stderr, "MOH: exec failed: %s\n", strerror(errno));
  606. close(fds[1]);
  607. _exit(1);
  608. } else {
  609. /* Parent */
  610. close(fds[1]);
  611. }
  612. return fds[0];
  613. }
  614. static int killer(pid_t pid, int signum, enum kill_methods kill_method)
  615. {
  616. switch (kill_method) {
  617. case KILL_METHOD_PROCESS_GROUP:
  618. return killpg(pid, signum);
  619. case KILL_METHOD_PROCESS:
  620. return kill(pid, signum);
  621. }
  622. return -1;
  623. }
  624. static void killpid(int pid, size_t delay, enum kill_methods kill_method)
  625. {
  626. if (killer(pid, SIGHUP, kill_method) < 0) {
  627. if (errno == ESRCH) {
  628. return;
  629. }
  630. ast_log(LOG_WARNING, "Unable to send a SIGHUP to MOH process '%d'?!!: %s\n", pid, strerror(errno));
  631. } else {
  632. ast_debug(1, "Sent HUP to pid %d%s\n", pid,
  633. kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
  634. }
  635. usleep(delay);
  636. if (killer(pid, SIGTERM, kill_method) < 0) {
  637. if (errno == ESRCH) {
  638. return;
  639. }
  640. ast_log(LOG_WARNING, "Unable to terminate MOH process '%d'?!!: %s\n", pid, strerror(errno));
  641. } else {
  642. ast_debug(1, "Sent TERM to pid %d%s\n", pid,
  643. kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
  644. }
  645. usleep(delay);
  646. if (killer(pid, SIGKILL, kill_method) < 0) {
  647. if (errno == ESRCH) {
  648. return;
  649. }
  650. ast_log(LOG_WARNING, "Unable to kill MOH process '%d'?!!: %s\n", pid, strerror(errno));
  651. } else {
  652. ast_debug(1, "Sent KILL to pid %d%s\n", pid,
  653. kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
  654. }
  655. }
  656. static void *monmp3thread(void *data)
  657. {
  658. #define MOH_MS_INTERVAL 100
  659. struct mohclass *class = data;
  660. struct mohdata *moh;
  661. short sbuf[8192];
  662. int res = 0, res2;
  663. int len;
  664. struct timeval deadline, tv_tmp;
  665. deadline.tv_sec = 0;
  666. deadline.tv_usec = 0;
  667. for(;/* ever */;) {
  668. pthread_testcancel();
  669. /* Spawn mp3 player if it's not there */
  670. if (class->srcfd < 0) {
  671. if ((class->srcfd = spawn_mp3(class)) < 0) {
  672. ast_log(LOG_WARNING, "Unable to spawn mp3player\n");
  673. /* Try again later */
  674. sleep(500);
  675. continue;
  676. }
  677. }
  678. if (class->timer) {
  679. struct pollfd pfd = { .fd = ast_timer_fd(class->timer), .events = POLLIN | POLLPRI, };
  680. #ifdef SOLARIS
  681. thr_yield();
  682. #endif
  683. /* Pause some amount of time */
  684. if (ast_poll(&pfd, 1, -1) > 0) {
  685. if (ast_timer_ack(class->timer, 1) < 0) {
  686. ast_log(LOG_ERROR, "Failed to acknowledge timer for mp3player\n");
  687. return NULL;
  688. }
  689. /* 25 samples per second => 40ms framerate => 320 samples */
  690. res = 320; /* 320/40 = 8 samples/ms */
  691. } else {
  692. ast_log(LOG_WARNING, "poll() failed: %s\n", strerror(errno));
  693. res = 0;
  694. }
  695. pthread_testcancel();
  696. } else {
  697. long delta;
  698. /* Reliable sleep */
  699. tv_tmp = ast_tvnow();
  700. if (ast_tvzero(deadline))
  701. deadline = tv_tmp;
  702. delta = ast_tvdiff_ms(tv_tmp, deadline);
  703. if (delta < MOH_MS_INTERVAL) { /* too early */
  704. deadline = ast_tvadd(deadline, ast_samp2tv(MOH_MS_INTERVAL, 1000)); /* next deadline */
  705. usleep(1000 * (MOH_MS_INTERVAL - delta));
  706. pthread_testcancel();
  707. } else {
  708. ast_log(LOG_NOTICE, "Request to schedule in the past?!?!\n");
  709. deadline = tv_tmp;
  710. }
  711. /* 10 samples per second (MOH_MS_INTERVAL) => 100ms framerate => 800 samples */
  712. res = 8 * MOH_MS_INTERVAL; /* 800/100 = 8 samples/ms */
  713. }
  714. /* For non-8000Hz formats, we need to alter the resolution */
  715. res = res * ast_format_get_sample_rate(class->format) / 8000;
  716. if ((strncasecmp(class->dir, "http://", 7) && strcasecmp(class->dir, "nodir")) && AST_LIST_EMPTY(&class->members))
  717. continue;
  718. /* Read mp3 audio */
  719. len = ast_format_determine_length(class->format, res);
  720. if ((res2 = read(class->srcfd, sbuf, len)) != len) {
  721. if (!res2) {
  722. close(class->srcfd);
  723. class->srcfd = -1;
  724. pthread_testcancel();
  725. if (class->pid > 1) {
  726. killpid(class->pid, class->kill_delay, class->kill_method);
  727. class->pid = 0;
  728. }
  729. } else {
  730. ast_debug(1, "Read %d bytes of audio while expecting %d\n", res2, len);
  731. }
  732. continue;
  733. }
  734. pthread_testcancel();
  735. ao2_lock(class);
  736. AST_LIST_TRAVERSE(&class->members, moh, list) {
  737. /* Write data */
  738. if ((res = write(moh->pipe[1], sbuf, res2)) != res2) {
  739. ast_debug(1, "Only wrote %d of %d bytes to pipe\n", res, res2);
  740. }
  741. }
  742. ao2_unlock(class);
  743. }
  744. return NULL;
  745. }
  746. static int play_moh_exec(struct ast_channel *chan, const char *data)
  747. {
  748. char *parse;
  749. char *class;
  750. int timeout = -1;
  751. int res;
  752. AST_DECLARE_APP_ARGS(args,
  753. AST_APP_ARG(class);
  754. AST_APP_ARG(duration);
  755. );
  756. parse = ast_strdupa(data);
  757. AST_STANDARD_APP_ARGS(args, parse);
  758. if (!ast_strlen_zero(args.duration)) {
  759. if (sscanf(args.duration, "%30d", &timeout) == 1) {
  760. timeout *= 1000;
  761. } else {
  762. ast_log(LOG_WARNING, "Invalid MusicOnHold duration '%s'. Will wait indefinitely.\n", args.duration);
  763. }
  764. }
  765. class = S_OR(args.class, NULL);
  766. if (ast_moh_start(chan, class, NULL)) {
  767. ast_log(LOG_WARNING, "Unable to start music on hold class '%s' on channel %s\n", class, ast_channel_name(chan));
  768. return 0;
  769. }
  770. if (timeout > 0)
  771. res = ast_safe_sleep(chan, timeout);
  772. else {
  773. while (!(res = ast_safe_sleep(chan, 10000)));
  774. }
  775. ast_moh_stop(chan);
  776. return res;
  777. }
  778. static int start_moh_exec(struct ast_channel *chan, const char *data)
  779. {
  780. char *parse;
  781. char *class;
  782. AST_DECLARE_APP_ARGS(args,
  783. AST_APP_ARG(class);
  784. );
  785. parse = ast_strdupa(data);
  786. AST_STANDARD_APP_ARGS(args, parse);
  787. class = S_OR(args.class, NULL);
  788. if (ast_moh_start(chan, class, NULL))
  789. ast_log(LOG_WARNING, "Unable to start music on hold class '%s' on channel %s\n", class, ast_channel_name(chan));
  790. return 0;
  791. }
  792. static int stop_moh_exec(struct ast_channel *chan, const char *data)
  793. {
  794. ast_moh_stop(chan);
  795. return 0;
  796. }
  797. #define get_mohbyname(a,b,c) _get_mohbyname(a,b,c,__FILE__,__LINE__,__PRETTY_FUNCTION__)
  798. static struct mohclass *_get_mohbyname(const char *name, int warn, int flags, const char *file, int lineno, const char *funcname)
  799. {
  800. struct mohclass *moh = NULL;
  801. struct mohclass tmp_class = {
  802. .flags = 0,
  803. };
  804. ast_copy_string(tmp_class.name, name, sizeof(tmp_class.name));
  805. #ifdef REF_DEBUG
  806. moh = __ao2_find_debug(mohclasses, &tmp_class, flags,
  807. "get_mohbyname", file, lineno, funcname);
  808. #else
  809. moh = __ao2_find(mohclasses, &tmp_class, flags);
  810. #endif
  811. if (!moh && warn) {
  812. ast_log(LOG_WARNING, "Music on Hold class '%s' not found in memory. Verify your configuration.\n", name);
  813. }
  814. return moh;
  815. }
  816. static struct mohdata *mohalloc(struct mohclass *cl)
  817. {
  818. struct mohdata *moh;
  819. if (!(moh = ast_calloc(1, sizeof(*moh))))
  820. return NULL;
  821. if (pipe(moh->pipe)) {
  822. ast_log(LOG_WARNING, "Failed to create pipe: %s\n", strerror(errno));
  823. ast_free(moh);
  824. return NULL;
  825. }
  826. /* Make entirely non-blocking */
  827. ast_fd_set_flags(moh->pipe[0], O_NONBLOCK);
  828. ast_fd_set_flags(moh->pipe[1], O_NONBLOCK);
  829. moh->f.frametype = AST_FRAME_VOICE;
  830. moh->f.subclass.format = cl->format;
  831. moh->f.offset = AST_FRIENDLY_OFFSET;
  832. moh->parent = mohclass_ref(cl, "Reffing music class for mohdata parent");
  833. ao2_lock(cl);
  834. AST_LIST_INSERT_HEAD(&cl->members, moh, list);
  835. ao2_unlock(cl);
  836. return moh;
  837. }
  838. static void moh_release(struct ast_channel *chan, void *data)
  839. {
  840. struct mohdata *moh = data;
  841. struct mohclass *class = moh->parent;
  842. struct ast_format *oldwfmt;
  843. ao2_lock(class);
  844. AST_LIST_REMOVE(&moh->parent->members, moh, list);
  845. ao2_unlock(class);
  846. close(moh->pipe[0]);
  847. close(moh->pipe[1]);
  848. oldwfmt = moh->origwfmt;
  849. moh->parent = class = mohclass_unref(class, "unreffing moh->parent upon deactivation of generator");
  850. ast_free(moh);
  851. if (chan) {
  852. struct moh_files_state *state;
  853. state = ast_channel_music_state(chan);
  854. if (state && state->class) {
  855. state->class = mohclass_unref(state->class, "Unreffing channel's music class upon deactivation of generator");
  856. }
  857. if (oldwfmt && ast_set_write_format(chan, oldwfmt)) {
  858. ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n",
  859. ast_channel_name(chan), ast_format_get_name(oldwfmt));
  860. }
  861. moh_post_stop(chan);
  862. }
  863. ao2_cleanup(oldwfmt);
  864. }
  865. static void *moh_alloc(struct ast_channel *chan, void *params)
  866. {
  867. struct mohdata *res;
  868. struct mohclass *class = params;
  869. struct moh_files_state *state;
  870. /* Initiating music_state for current channel. Channel should know name of moh class */
  871. state = ast_channel_music_state(chan);
  872. if (!state && (state = ast_calloc(1, sizeof(*state)))) {
  873. ast_channel_music_state_set(chan, state);
  874. ast_module_ref(ast_module_info->self);
  875. } else {
  876. if (!state) {
  877. return NULL;
  878. }
  879. if (state->class) {
  880. mohclass_unref(state->class, "Uh Oh. Restarting MOH with an active class");
  881. ast_log(LOG_WARNING, "Uh Oh. Restarting MOH with an active class\n");
  882. }
  883. ao2_cleanup(state->origwfmt);
  884. ao2_cleanup(state->mohwfmt);
  885. memset(state, 0, sizeof(*state));
  886. }
  887. if ((res = mohalloc(class))) {
  888. res->origwfmt = ao2_bump(ast_channel_writeformat(chan));
  889. if (ast_set_write_format(chan, class->format)) {
  890. ast_log(LOG_WARNING, "Unable to set channel '%s' to format '%s'\n", ast_channel_name(chan),
  891. ast_format_get_name(class->format));
  892. moh_release(NULL, res);
  893. res = NULL;
  894. } else {
  895. state->class = mohclass_ref(class, "Placing reference into state container");
  896. moh_post_start(chan, class->name);
  897. }
  898. }
  899. return res;
  900. }
  901. static int moh_generate(struct ast_channel *chan, void *data, int len, int samples)
  902. {
  903. struct mohdata *moh = data;
  904. short buf[1280 + AST_FRIENDLY_OFFSET / 2];
  905. int res;
  906. len = ast_format_determine_length(moh->parent->format, samples);
  907. if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
  908. ast_log(LOG_WARNING, "Only doing %d of %d requested bytes on %s\n", (int)sizeof(buf), len, ast_channel_name(chan));
  909. len = sizeof(buf) - AST_FRIENDLY_OFFSET;
  910. }
  911. res = read(moh->pipe[0], buf + AST_FRIENDLY_OFFSET/2, len);
  912. if (res <= 0)
  913. return 0;
  914. moh->f.datalen = res;
  915. moh->f.data.ptr = buf + AST_FRIENDLY_OFFSET / 2;
  916. moh->f.samples = ast_codec_samples_count(&moh->f);
  917. if (ast_write(chan, &moh->f) < 0) {
  918. ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
  919. return -1;
  920. }
  921. return 0;
  922. }
  923. static struct ast_generator mohgen = {
  924. .alloc = moh_alloc,
  925. .release = moh_release,
  926. .generate = moh_generate,
  927. .digit = moh_handle_digit,
  928. };
  929. static int moh_add_file(struct mohclass *class, const char *filepath)
  930. {
  931. if (!class->allowed_files) {
  932. class->filearray = ast_calloc(1, INITIAL_NUM_FILES * sizeof(*class->filearray));
  933. if (!class->filearray) {
  934. return -1;
  935. }
  936. class->allowed_files = INITIAL_NUM_FILES;
  937. } else if (class->total_files == class->allowed_files) {
  938. char **new_array;
  939. new_array = ast_realloc(class->filearray, class->allowed_files * sizeof(*class->filearray) * 2);
  940. if (!new_array) {
  941. return -1;
  942. }
  943. class->filearray = new_array;
  944. class->allowed_files *= 2;
  945. }
  946. class->filearray[class->total_files] = ast_strdup(filepath);
  947. if (!class->filearray[class->total_files]) {
  948. return -1;
  949. }
  950. class->total_files++;
  951. return 0;
  952. }
  953. static int moh_sort_compare(const void *i1, const void *i2)
  954. {
  955. char *s1, *s2;
  956. s1 = ((char **)i1)[0];
  957. s2 = ((char **)i2)[0];
  958. return strcasecmp(s1, s2);
  959. }
  960. static int moh_scan_files(struct mohclass *class) {
  961. DIR *files_DIR;
  962. struct dirent *files_dirent;
  963. char dir_path[PATH_MAX - sizeof(class->dir)];
  964. char filepath[PATH_MAX];
  965. char *ext;
  966. struct stat statbuf;
  967. int i;
  968. if (class->dir[0] != '/') {
  969. snprintf(dir_path, sizeof(dir_path), "%s/%s", ast_config_AST_DATA_DIR, class->dir);
  970. } else {
  971. ast_copy_string(dir_path, class->dir, sizeof(dir_path));
  972. }
  973. ast_debug(4, "Scanning '%s' for files for class '%s'\n", dir_path, class->name);
  974. files_DIR = opendir(dir_path);
  975. if (!files_DIR) {
  976. ast_log(LOG_WARNING, "Cannot open dir %s or dir does not exist\n", dir_path);
  977. return -1;
  978. }
  979. for (i = 0; i < class->total_files; i++) {
  980. ast_free(class->filearray[i]);
  981. }
  982. class->total_files = 0;
  983. while ((files_dirent = readdir(files_DIR))) {
  984. /* The file name must be at least long enough to have the file type extension */
  985. if ((strlen(files_dirent->d_name) < 4))
  986. continue;
  987. /* Skip files that starts with a dot */
  988. if (files_dirent->d_name[0] == '.')
  989. continue;
  990. /* Skip files without extensions... they are not audio */
  991. if (!strchr(files_dirent->d_name, '.'))
  992. continue;
  993. snprintf(filepath, sizeof(filepath), "%s/%s", dir_path, files_dirent->d_name);
  994. if (stat(filepath, &statbuf))
  995. continue;
  996. if (!S_ISREG(statbuf.st_mode))
  997. continue;
  998. if ((ext = strrchr(filepath, '.')))
  999. *ext = '\0';
  1000. /* if the file is present in multiple formats, ensure we only put it into the list once */
  1001. for (i = 0; i < class->total_files; i++)
  1002. if (!strcmp(filepath, class->filearray[i]))
  1003. break;
  1004. if (i == class->total_files) {
  1005. if (moh_add_file(class, filepath))
  1006. break;
  1007. }
  1008. }
  1009. closedir(files_DIR);
  1010. if (ast_test_flag(class, MOH_SORTALPHA))
  1011. qsort(&class->filearray[0], class->total_files, sizeof(char *), moh_sort_compare);
  1012. return class->total_files;
  1013. }
  1014. static int init_files_class(struct mohclass *class)
  1015. {
  1016. int res;
  1017. res = moh_scan_files(class);
  1018. if (res < 0) {
  1019. return -1;
  1020. }
  1021. if (!res) {
  1022. ast_verb(3, "Files not found in %s for moh class:%s\n",
  1023. class->dir, class->name);
  1024. return -1;
  1025. }
  1026. return 0;
  1027. }
  1028. static void moh_rescan_files(void) {
  1029. struct ao2_iterator i;
  1030. struct mohclass *c;
  1031. i = ao2_iterator_init(mohclasses, 0);
  1032. while ((c = ao2_iterator_next(&i))) {
  1033. if (!strcasecmp(c->mode, "files")) {
  1034. moh_scan_files(c);
  1035. }
  1036. ao2_ref(c, -1);
  1037. }
  1038. ao2_iterator_destroy(&i);
  1039. }
  1040. static int moh_diff(struct mohclass *old, struct mohclass *new)
  1041. {
  1042. if (!old || !new) {
  1043. return -1;
  1044. }
  1045. if (strcmp(old->dir, new->dir)) {
  1046. return -1;
  1047. } else if (strcmp(old->mode, new->mode)) {
  1048. return -1;
  1049. } else if (strcmp(old->args, new->args)) {
  1050. return -1;
  1051. } else if (old->flags != new->flags) {
  1052. return -1;
  1053. }
  1054. return 0;
  1055. }
  1056. static int init_app_class(struct mohclass *class)
  1057. {
  1058. if (!strcasecmp(class->mode, "custom")) {
  1059. ast_set_flag(class, MOH_CUSTOM);
  1060. } else if (!strcasecmp(class->mode, "mp3nb")) {
  1061. ast_set_flag(class, MOH_SINGLE);
  1062. } else if (!strcasecmp(class->mode, "quietmp3nb")) {
  1063. ast_set_flag(class, MOH_SINGLE | MOH_QUIET);
  1064. } else if (!strcasecmp(class->mode, "quietmp3")) {
  1065. ast_set_flag(class, MOH_QUIET);
  1066. }
  1067. class->srcfd = -1;
  1068. if (!(class->timer = ast_timer_open())) {
  1069. ast_log(LOG_WARNING, "Unable to create timer: %s\n", strerror(errno));
  1070. return -1;
  1071. }
  1072. if (class->timer && ast_timer_set_rate(class->timer, 25)) {
  1073. ast_log(LOG_WARNING, "Unable to set 40ms frame rate: %s\n", strerror(errno));
  1074. ast_timer_close(class->timer);
  1075. class->timer = NULL;
  1076. }
  1077. if (ast_pthread_create_background(&class->thread, NULL, monmp3thread, class)) {
  1078. ast_log(LOG_WARNING, "Unable to create moh thread...\n");
  1079. if (class->timer) {
  1080. ast_timer_close(class->timer);
  1081. class->timer = NULL;
  1082. }
  1083. return -1;
  1084. }
  1085. return 0;
  1086. }
  1087. /*!
  1088. * \note This function owns the reference it gets to moh if unref is true
  1089. */
  1090. #define moh_register(moh, reload, unref) _moh_register(moh, reload, unref, __FILE__, __LINE__, __PRETTY_FUNCTION__)
  1091. static int _moh_register(struct mohclass *moh, int reload, int unref, const char *file, int line, const char *funcname)
  1092. {
  1093. struct mohclass *mohclass = NULL;
  1094. mohclass = _get_mohbyname(moh->name, 0, MOH_NOTDELETED, file, line, funcname);
  1095. if (mohclass && !moh_diff(mohclass, moh)) {
  1096. ast_log(LOG_WARNING, "Music on Hold class '%s' already exists\n", moh->name);
  1097. mohclass = mohclass_unref(mohclass, "unreffing mohclass we just found by name");
  1098. if (unref) {
  1099. moh = mohclass_unref(moh, "unreffing potential new moh class (it is a duplicate)");
  1100. }
  1101. return -1;
  1102. } else if (mohclass) {
  1103. /* Found a class, but it's different from the one being registered */
  1104. mohclass = mohclass_unref(mohclass, "unreffing mohclass we just found by name");
  1105. }
  1106. time(&moh->start);
  1107. moh->start -= respawn_time;
  1108. if (!strcasecmp(moh->mode, "files")) {
  1109. if (init_files_class(moh)) {
  1110. if (unref) {
  1111. moh = mohclass_unref(moh, "unreffing potential new moh class (init_files_class failed)");
  1112. }
  1113. return -1;
  1114. }
  1115. } else if (!strcasecmp(moh->mode, "mp3") || !strcasecmp(moh->mode, "mp3nb") ||
  1116. !strcasecmp(moh->mode, "quietmp3") || !strcasecmp(moh->mode, "quietmp3nb") ||
  1117. !strcasecmp(moh->mode, "httpmp3") || !strcasecmp(moh->mode, "custom")) {
  1118. if (init_app_class(moh)) {
  1119. if (unref) {
  1120. moh = mohclass_unref(moh, "unreffing potential new moh class (init_app_class_failed)");
  1121. }
  1122. return -1;
  1123. }
  1124. } else {
  1125. ast_log(LOG_WARNING, "Don't know how to do a mode '%s' music on hold\n", moh->mode);
  1126. if (unref) {
  1127. moh = mohclass_unref(moh, "unreffing potential new moh class (unknown mode)");
  1128. }
  1129. return -1;
  1130. }
  1131. ao2_t_link(mohclasses, moh, "Adding class to container");
  1132. if (unref) {
  1133. moh = mohclass_unref(moh, "Unreffing new moh class because we just added it to the container");
  1134. }
  1135. return 0;
  1136. }
  1137. static void local_ast_moh_cleanup(struct ast_channel *chan)
  1138. {
  1139. struct moh_files_state *state = ast_channel_music_state(chan);
  1140. if (state) {
  1141. ast_channel_music_state_set(chan, NULL);
  1142. if (state->class) {
  1143. /* This should never happen. We likely just leaked some resource. */
  1144. state->class =
  1145. mohclass_unref(state->class, "Uh Oh. Cleaning up MOH with an active class");
  1146. ast_log(LOG_WARNING, "Uh Oh. Cleaning up MOH with an active class\n");
  1147. }
  1148. ao2_cleanup(state->origwfmt);
  1149. ao2_cleanup(state->mohwfmt);
  1150. ast_free(state);
  1151. /* Only held a module reference if we had a music state */
  1152. ast_module_unref(ast_module_info->self);
  1153. }
  1154. }
  1155. static void moh_class_destructor(void *obj);
  1156. #define moh_class_malloc() _moh_class_malloc(__FILE__,__LINE__,__PRETTY_FUNCTION__)
  1157. static struct mohclass *_moh_class_malloc(const char *file, int line, const char *funcname)
  1158. {
  1159. struct mohclass *class;
  1160. if ((class =
  1161. #ifdef REF_DEBUG
  1162. __ao2_alloc_debug(sizeof(*class), moh_class_destructor,
  1163. AO2_ALLOC_OPT_LOCK_MUTEX, "Allocating new moh class", file, line, funcname, 1)
  1164. #elif defined(__AST_DEBUG_MALLOC)
  1165. __ao2_alloc_debug(sizeof(*class), moh_class_destructor,
  1166. AO2_ALLOC_OPT_LOCK_MUTEX, "Allocating new moh class", file, line, funcname, 0)
  1167. #else
  1168. ao2_alloc(sizeof(*class), moh_class_destructor)
  1169. #endif
  1170. )) {
  1171. class->format = ao2_bump(ast_format_slin);
  1172. class->srcfd = -1;
  1173. class->kill_delay = 100000;
  1174. }
  1175. return class;
  1176. }
  1177. static struct ast_variable *load_realtime_musiconhold(const char *name)
  1178. {
  1179. struct ast_variable *var = ast_load_realtime("musiconhold", "name", name, SENTINEL);
  1180. if (!var) {
  1181. ast_log(LOG_WARNING,
  1182. "Music on Hold class '%s' not found in memory/database. "
  1183. "Verify your configuration.\n",
  1184. name);
  1185. }
  1186. return var;
  1187. }
  1188. static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
  1189. {
  1190. struct mohclass *mohclass = NULL;
  1191. struct moh_files_state *state = ast_channel_music_state(chan);
  1192. struct ast_variable *var = NULL;
  1193. int res = 0;
  1194. int realtime_possible = ast_check_realtime("musiconhold");
  1195. int warn_if_not_in_memory = !realtime_possible;
  1196. /* The following is the order of preference for which class to use:
  1197. * 1) The channels explicitly set musicclass, which should *only* be
  1198. * set by a call to Set(CHANNEL(musicclass)=whatever) in the dialplan.
  1199. * 2) The mclass argument. If a channel is calling ast_moh_start() as the
  1200. * result of receiving a HOLD control frame, this should be the
  1201. * payload that came with the frame.
  1202. * 3) The interpclass argument. This would be from the mohinterpret
  1203. * option from channel drivers. This is the same as the old musicclass
  1204. * option.
  1205. * 4) The default class.
  1206. */
  1207. if (!ast_strlen_zero(ast_channel_musicclass(chan))) {
  1208. mohclass = get_mohbyname(ast_channel_musicclass(chan), warn_if_not_in_memory, 0);
  1209. if (!mohclass && realtime_possible) {
  1210. var = load_realtime_musiconhold(ast_channel_musicclass(chan));
  1211. }
  1212. }
  1213. if (!mohclass && !var && !ast_strlen_zero(mclass)) {
  1214. mohclass = get_mohbyname(mclass, warn_if_not_in_memory, 0);
  1215. if (!mohclass && realtime_possible) {
  1216. var = load_realtime_musiconhold(mclass);
  1217. }
  1218. }
  1219. if (!mohclass && !var && !ast_strlen_zero(interpclass)) {
  1220. mohclass = get_mohbyname(interpclass, warn_if_not_in_memory, 0);
  1221. if (!mohclass && realtime_possible) {
  1222. var = load_realtime_musiconhold(interpclass);
  1223. }
  1224. }
  1225. if (!mohclass && !var) {
  1226. mohclass = get_mohbyname("default", warn_if_not_in_memory, 0);
  1227. if (!mohclass && realtime_possible) {
  1228. var = load_realtime_musiconhold("default");
  1229. }
  1230. }
  1231. /* If no moh class found in memory, then check RT. Note that the logic used
  1232. * above guarantees that if var is non-NULL, then mohclass must be NULL.
  1233. */
  1234. if (var) {
  1235. struct ast_variable *tmp = NULL;
  1236. if ((mohclass = moh_class_malloc())) {
  1237. mohclass->realtime = 1;
  1238. for (tmp = var; tmp; tmp = tmp->next) {
  1239. if (!strcasecmp(tmp->name, "name"))
  1240. ast_copy_string(mohclass->name, tmp->value, sizeof(mohclass->name));
  1241. else if (!strcasecmp(tmp->name, "mode"))
  1242. ast_copy_string(mohclass->mode, tmp->value, sizeof(mohclass->mode));
  1243. else if (!strcasecmp(tmp->name, "directory"))
  1244. ast_copy_string(mohclass->dir, tmp->value, sizeof(mohclass->dir));
  1245. else if (!strcasecmp(tmp->name, "application"))
  1246. ast_copy_string(mohclass->args, tmp->value, sizeof(mohclass->args));
  1247. else if (!strcasecmp(tmp->name, "digit") && (isdigit(*tmp->value) || strchr("*#", *tmp->value)))
  1248. mohclass->digit = *tmp->value;
  1249. else if (!strcasecmp(tmp->name, "random"))
  1250. ast_set2_flag(mohclass, ast_true(tmp->value), MOH_RANDOMIZE);
  1251. else if (!strcasecmp(tmp->name, "sort") && !strcasecmp(tmp->value, "random"))
  1252. ast_set_flag(mohclass, MOH_RANDOMIZE);
  1253. else if (!strcasecmp(tmp->name, "sort") && !strcasecmp(tmp->value, "alpha"))
  1254. ast_set_flag(mohclass, MOH_SORTALPHA);
  1255. else if (!strcasecmp(tmp->name, "format")) {
  1256. ao2_cleanup(mohclass->format);
  1257. mohclass->format = ast_format_cache_get(tmp->value);
  1258. if (!mohclass->format) {
  1259. ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", tmp->value);
  1260. mohclass->format = ao2_bump(ast_format_slin);
  1261. }
  1262. }
  1263. }
  1264. ast_variables_destroy(var);
  1265. if (ast_strlen_zero(mohclass->dir)) {
  1266. if (!strcasecmp(mohclass->mode, "custom")) {
  1267. strcpy(mohclass->dir, "nodir");
  1268. } else {
  1269. ast_log(LOG_WARNING, "A directory must be specified for class '%s'!\n", mohclass->name);
  1270. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no directory specified)");
  1271. return -1;
  1272. }
  1273. }
  1274. if (ast_strlen_zero(mohclass->mode)) {
  1275. ast_log(LOG_WARNING, "A mode must be specified for class '%s'!\n", mohclass->name);
  1276. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no mode specified)");
  1277. return -1;
  1278. }
  1279. if (ast_strlen_zero(mohclass->args) && !strcasecmp(mohclass->mode, "custom")) {
  1280. ast_log(LOG_WARNING, "An application must be specified for class '%s'!\n", mohclass->name);
  1281. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no app specified for custom mode");
  1282. return -1;
  1283. }
  1284. if (ast_test_flag(global_flags, MOH_CACHERTCLASSES)) {
  1285. /* CACHERTCLASSES enabled, let's add this class to default tree */
  1286. if (state && state->class) {
  1287. /* Class already exist for this channel */
  1288. ast_log(LOG_NOTICE, "This channel already has a MOH class attached (%s)!\n", state->class->name);
  1289. }
  1290. /* We don't want moh_register to unref the mohclass because we do it at the end of this function as well.
  1291. * If we allowed moh_register to unref the mohclass,too, then the count would be off by one. The result would
  1292. * be that the destructor would be called when the generator on the channel is deactivated. The container then
  1293. * has a pointer to a freed mohclass, so any operations involving the mohclass container would result in reading
  1294. * invalid memory.
  1295. */
  1296. if (moh_register(mohclass, 0, DONT_UNREF) == -1) {
  1297. mohclass = mohclass_unref(mohclass, "unreffing mohclass failed to register");
  1298. return -1;
  1299. }
  1300. } else {
  1301. /* We don't register RT moh class, so let's init it manualy */
  1302. time(&mohclass->start);
  1303. mohclass->start -= respawn_time;
  1304. if (!strcasecmp(mohclass->mode, "files")) {
  1305. if (!moh_scan_files(mohclass)) {
  1306. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (moh_scan_files failed)");
  1307. return -1;
  1308. }
  1309. if (strchr(mohclass->args, 'r'))
  1310. ast_set_flag(mohclass, MOH_RANDOMIZE);
  1311. } else if (!strcasecmp(mohclass->mode, "mp3") || !strcasecmp(mohclass->mode, "mp3nb") || !strcasecmp(mohclass->mode, "quietmp3") || !strcasecmp(mohclass->mode, "quietmp3nb") || !strcasecmp(mohclass->mode, "httpmp3") || !strcasecmp(mohclass->mode, "custom")) {
  1312. if (!strcasecmp(mohclass->mode, "custom"))
  1313. ast_set_flag(mohclass, MOH_CUSTOM);
  1314. else if (!strcasecmp(mohclass->mode, "mp3nb"))
  1315. ast_set_flag(mohclass, MOH_SINGLE);
  1316. else if (!strcasecmp(mohclass->mode, "quietmp3nb"))
  1317. ast_set_flag(mohclass, MOH_SINGLE | MOH_QUIET);
  1318. else if (!strcasecmp(mohclass->mode, "quietmp3"))
  1319. ast_set_flag(mohclass, MOH_QUIET);
  1320. mohclass->srcfd = -1;
  1321. if (!(mohclass->timer = ast_timer_open())) {
  1322. ast_log(LOG_WARNING, "Unable to create timer: %s\n", strerror(errno));
  1323. }
  1324. if (mohclass->timer && ast_timer_set_rate(mohclass->timer, 25)) {
  1325. ast_log(LOG_WARNING, "Unable to set 40ms frame rate: %s\n", strerror(errno));
  1326. ast_timer_close(mohclass->timer);
  1327. mohclass->timer = NULL;
  1328. }
  1329. /* Let's check if this channel already had a moh class before */
  1330. if (state && state->class) {
  1331. /* Class already exist for this channel */
  1332. ast_log(LOG_NOTICE, "This channel already has a MOH class attached (%s)!\n", state->class->name);
  1333. if (state->class->realtime && !ast_test_flag(global_flags, MOH_CACHERTCLASSES) && !strcasecmp(mohclass->name, state->class->name)) {
  1334. /* we found RT class with the same name, seems like we should continue playing existing one */
  1335. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (channel already has one)");
  1336. mohclass = mohclass_ref(state->class, "using existing class from state");
  1337. }
  1338. } else {
  1339. if (ast_pthread_create_background(&mohclass->thread, NULL, monmp3thread, mohclass)) {
  1340. ast_log(LOG_WARNING, "Unable to create moh...\n");
  1341. if (mohclass->timer) {
  1342. ast_timer_close(mohclass->timer);
  1343. mohclass->timer = NULL;
  1344. }
  1345. mohclass = mohclass_unref(mohclass, "Unreffing potential mohclass (failed to create background thread)");
  1346. return -1;
  1347. }
  1348. }
  1349. } else {
  1350. ast_log(LOG_WARNING, "Don't know how to do a mode '%s' music on hold\n", mohclass->mode);
  1351. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (unknown mode)");
  1352. return -1;
  1353. }
  1354. }
  1355. } else {
  1356. ast_variables_destroy(var);
  1357. var = NULL;
  1358. }
  1359. }
  1360. if (!mohclass) {
  1361. return -1;
  1362. }
  1363. /* If we are using a cached realtime class with files, re-scan the files */
  1364. if (!var && ast_test_flag(global_flags, MOH_CACHERTCLASSES) && mohclass->realtime && !strcasecmp(mohclass->mode, "files")) {
  1365. if (!moh_scan_files(mohclass)) {
  1366. mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (moh_scan_files failed)");
  1367. return -1;
  1368. }
  1369. }
  1370. if (!state || !state->class || strcmp(mohclass->name, state->class->name)) {
  1371. if (mohclass->total_files) {
  1372. res = ast_activate_generator(chan, &moh_file_stream, mohclass);
  1373. } else {
  1374. res = ast_activate_generator(chan, &mohgen, mohclass);
  1375. }
  1376. }
  1377. if (!res) {
  1378. ast_channel_lock(chan);
  1379. ast_channel_latest_musicclass_set(chan, mohclass->name);
  1380. ast_set_flag(ast_channel_flags(chan), AST_FLAG_MOH);
  1381. ast_channel_unlock(chan);
  1382. }
  1383. mohclass = mohclass_unref(mohclass, "unreffing local reference to mohclass in local_ast_moh_start");
  1384. return res;
  1385. }
  1386. static void local_ast_moh_stop(struct ast_channel *chan)
  1387. {
  1388. ast_deactivate_generator(chan);
  1389. ast_channel_lock(chan);
  1390. ast_clear_flag(ast_channel_flags(chan), AST_FLAG_MOH);
  1391. if (ast_channel_music_state(chan)) {
  1392. if (ast_channel_stream(chan)) {
  1393. ast_closestream(ast_channel_stream(chan));
  1394. ast_channel_stream_set(chan, NULL);
  1395. }
  1396. }
  1397. ast_channel_unlock(chan);
  1398. }
  1399. static void moh_class_destructor(void *obj)
  1400. {
  1401. struct mohclass *class = obj;
  1402. struct mohdata *member;
  1403. pthread_t tid = 0;
  1404. ast_debug(1, "Destroying MOH class '%s'\n", class->name);
  1405. ao2_lock(class);
  1406. while ((member = AST_LIST_REMOVE_HEAD(&class->members, list))) {
  1407. ast_free(member);
  1408. }
  1409. ao2_unlock(class);
  1410. /* Kill the thread first, so it cannot restart the child process while the
  1411. * class is being destroyed */
  1412. if (class->thread != AST_PTHREADT_NULL && class->thread != 0) {
  1413. tid = class->thread;
  1414. class->thread = AST_PTHREADT_NULL;
  1415. pthread_cancel(tid);
  1416. /* We'll collect the exit status later, after we ensure all the readers
  1417. * are dead. */
  1418. }
  1419. if (class->pid > 1) {
  1420. char buff[8192];
  1421. int bytes, tbytes = 0, stime = 0;
  1422. ast_debug(1, "killing %d!\n", class->pid);
  1423. stime = time(NULL) + 2;
  1424. killpid(class->pid, class->kill_delay, class->kill_method);
  1425. while ((ast_wait_for_input(class->srcfd, 100) > 0) &&
  1426. (bytes = read(class->srcfd, buff, 8192)) && time(NULL) < stime) {
  1427. tbytes = tbytes + bytes;
  1428. }
  1429. ast_debug(1, "mpg123 pid %d and child died after %d bytes read\n",
  1430. class->pid, tbytes);
  1431. class->pid = 0;
  1432. close(class->srcfd);
  1433. class->srcfd = -1;
  1434. }
  1435. if (class->filearray) {
  1436. int i;
  1437. for (i = 0; i < class->total_files; i++) {
  1438. ast_free(class->filearray[i]);
  1439. }
  1440. ast_free(class->filearray);
  1441. class->filearray = NULL;
  1442. }
  1443. if (class->timer) {
  1444. ast_timer_close(class->timer);
  1445. class->timer = NULL;
  1446. }
  1447. ao2_cleanup(class->format);
  1448. /* Finally, collect the exit status of the monitor thread */
  1449. if (tid > 0) {
  1450. pthread_join(tid, NULL);
  1451. }
  1452. }
  1453. static int moh_class_mark(void *obj, void *arg, int flags)
  1454. {
  1455. struct mohclass *class = obj;
  1456. if ( ((flags & MOH_REALTIME) && class->realtime) || !(flags & MOH_REALTIME) ) {
  1457. class->delete = 1;
  1458. }
  1459. return 0;
  1460. }
  1461. static int moh_classes_delete_marked(void *obj, void *arg, int flags)
  1462. {
  1463. struct mohclass *class = obj;
  1464. return class->delete ? CMP_MATCH : 0;
  1465. }
  1466. static int load_moh_classes(int reload)
  1467. {
  1468. struct ast_config *cfg;
  1469. struct ast_variable *var;
  1470. struct mohclass *class;
  1471. char *cat;
  1472. int numclasses = 0;
  1473. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  1474. cfg = ast_config_load("musiconhold.conf", config_flags);
  1475. if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  1476. if (ast_check_realtime("musiconhold") && reload) {
  1477. ao2_t_callback(mohclasses, OBJ_NODATA | MOH_REALTIME, moh_class_mark, NULL, "Mark realtime classes for deletion");
  1478. ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, moh_classes_delete_marked, NULL, "Purge marked classes");
  1479. }
  1480. moh_rescan_files();
  1481. return 0;
  1482. }
  1483. if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
  1484. if (ast_check_realtime("musiconhold") && reload) {
  1485. ao2_t_callback(mohclasses, OBJ_NODATA, moh_class_mark, NULL, "Mark deleted classes");
  1486. ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, moh_classes_delete_marked, NULL, "Purge marked classes");
  1487. }
  1488. return 0;
  1489. }
  1490. if (reload) {
  1491. ao2_t_callback(mohclasses, OBJ_NODATA, moh_class_mark, NULL, "Mark deleted classes");
  1492. }
  1493. ast_clear_flag(global_flags, AST_FLAGS_ALL);
  1494. cat = ast_category_browse(cfg, NULL);
  1495. for (; cat; cat = ast_category_browse(cfg, cat)) {
  1496. /* Setup common options from [general] section */
  1497. if (!strcasecmp(cat, "general")) {
  1498. for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
  1499. if (!strcasecmp(var->name, "cachertclasses")) {
  1500. ast_set2_flag(global_flags, ast_true(var->value), MOH_CACHERTCLASSES);
  1501. } else {
  1502. ast_log(LOG_WARNING, "Unknown option '%s' in [general] section of musiconhold.conf\n", var->name);
  1503. }
  1504. }
  1505. }
  1506. /* These names were deprecated in 1.4 and should not be used until after the next major release. */
  1507. if (!strcasecmp(cat, "classes") || !strcasecmp(cat, "moh_files") ||
  1508. !strcasecmp(cat, "general")) {
  1509. continue;
  1510. }
  1511. if (!(class = moh_class_malloc())) {
  1512. break;
  1513. }
  1514. ast_copy_string(class->name, cat, sizeof(class->name));
  1515. for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
  1516. if (!strcasecmp(var->name, "mode")) {
  1517. ast_copy_string(class->mode, var->value, sizeof(class->mode));
  1518. } else if (!strcasecmp(var->name, "directory")) {
  1519. ast_copy_string(class->dir, var->value, sizeof(class->dir));
  1520. } else if (!strcasecmp(var->name, "application")) {
  1521. ast_copy_string(class->args, var->value, sizeof(class->args));
  1522. } else if (!strcasecmp(var->name, "announcement")) {
  1523. ast_copy_string(class->announcement, var->value, sizeof(class->announcement));
  1524. ast_set_flag(class, MOH_ANNOUNCEMENT);
  1525. } else if (!strcasecmp(var->name, "digit") && (isdigit(*var->value) || strchr("*#", *var->value))) {
  1526. class->digit = *var->value;
  1527. } else if (!strcasecmp(var->name, "random")) {
  1528. ast_set2_flag(class, ast_true(var->value), MOH_RANDOMIZE);
  1529. } else if (!strcasecmp(var->name, "sort") && !strcasecmp(var->value, "random")) {
  1530. ast_set_flag(class, MOH_RANDOMIZE);
  1531. } else if (!strcasecmp(var->name, "sort") && !strcasecmp(var->value, "alpha")) {
  1532. ast_set_flag(class, MOH_SORTALPHA);
  1533. } else if (!strcasecmp(var->name, "format")) {
  1534. ao2_cleanup(class->format);
  1535. class->format = ast_format_cache_get(var->value);
  1536. if (!class->format) {
  1537. ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", var->value);
  1538. class->format = ao2_bump(ast_format_slin);
  1539. }
  1540. } else if (!strcasecmp(var->name, "kill_escalation_delay")) {
  1541. if (sscanf(var->value, "%zu", &class->kill_delay) == 1) {
  1542. class->kill_delay *= 1000;
  1543. } else {
  1544. ast_log(LOG_WARNING, "kill_escalation_delay '%s' is invalid. Setting to 100ms\n", var->value);
  1545. class->kill_delay = 100000;
  1546. }
  1547. } else if (!strcasecmp(var->name, "kill_method")) {
  1548. if (!strcasecmp(var->value, "process")) {
  1549. class->kill_method = KILL_METHOD_PROCESS;
  1550. } else if (!strcasecmp(var->value, "process_group")){
  1551. class->kill_method = KILL_METHOD_PROCESS_GROUP;
  1552. } else {
  1553. ast_log(LOG_WARNING, "kill_method '%s' is invalid. Setting to 'process_group'\n", var->value);
  1554. class->kill_method = KILL_METHOD_PROCESS_GROUP;
  1555. }
  1556. }
  1557. }
  1558. if (ast_strlen_zero(class->dir)) {
  1559. if (!strcasecmp(class->mode, "custom")) {
  1560. strcpy(class->dir, "nodir");
  1561. } else {
  1562. ast_log(LOG_WARNING, "A directory must be specified for class '%s'!\n", class->name);
  1563. class = mohclass_unref(class, "unreffing potential mohclass (no directory)");
  1564. continue;
  1565. }
  1566. }
  1567. if (ast_strlen_zero(class->mode)) {
  1568. ast_log(LOG_WARNING, "A mode must be specified for class '%s'!\n", class->name);
  1569. class = mohclass_unref(class, "unreffing potential mohclass (no mode)");
  1570. continue;
  1571. }
  1572. if (ast_strlen_zero(class->args) && !strcasecmp(class->mode, "custom")) {
  1573. ast_log(LOG_WARNING, "An application must be specified for class '%s'!\n", class->name);
  1574. class = mohclass_unref(class, "unreffing potential mohclass (no app for custom mode)");
  1575. continue;
  1576. }
  1577. /* Don't leak a class when it's already registered */
  1578. if (!moh_register(class, reload, HANDLE_REF)) {
  1579. numclasses++;
  1580. }
  1581. }
  1582. ast_config_destroy(cfg);
  1583. ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
  1584. moh_classes_delete_marked, NULL, "Purge marked classes");
  1585. return numclasses;
  1586. }
  1587. static void ast_moh_destroy(void)
  1588. {
  1589. ast_verb(2, "Destroying musiconhold processes\n");
  1590. if (mohclasses) {
  1591. ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "Destroy callback");
  1592. ao2_ref(mohclasses, -1);
  1593. mohclasses = NULL;
  1594. }
  1595. }
  1596. static char *handle_cli_moh_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1597. {
  1598. switch (cmd) {
  1599. case CLI_INIT:
  1600. e->command = "moh reload";
  1601. e->usage =
  1602. "Usage: moh reload\n"
  1603. " Reloads the MusicOnHold module.\n"
  1604. " Alias for 'module reload res_musiconhold.so'\n";
  1605. return NULL;
  1606. case CLI_GENERATE:
  1607. return NULL;
  1608. }
  1609. if (a->argc != e->args)
  1610. return CLI_SHOWUSAGE;
  1611. /* The module loader will prevent concurrent reloads from occurring, so we delegate */
  1612. ast_module_reload("res_musiconhold");
  1613. return CLI_SUCCESS;
  1614. }
  1615. static char *handle_cli_moh_show_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1616. {
  1617. struct mohclass *class;
  1618. struct ao2_iterator i;
  1619. switch (cmd) {
  1620. case CLI_INIT:
  1621. e->command = "moh show files";
  1622. e->usage =
  1623. "Usage: moh show files\n"
  1624. " Lists all loaded file-based MusicOnHold classes and their\n"
  1625. " files.\n";
  1626. return NULL;
  1627. case CLI_GENERATE:
  1628. return NULL;
  1629. }
  1630. if (a->argc != e->args)
  1631. return CLI_SHOWUSAGE;
  1632. i = ao2_iterator_init(mohclasses, 0);
  1633. for (; (class = ao2_t_iterator_next(&i, "Show files iterator")); mohclass_unref(class, "Unref iterator in moh show files")) {
  1634. int x;
  1635. if (!class->total_files) {
  1636. continue;
  1637. }
  1638. ast_cli(a->fd, "Class: %s\n", class->name);
  1639. for (x = 0; x < class->total_files; x++) {
  1640. ast_cli(a->fd, "\tFile: %s\n", class->filearray[x]);
  1641. }
  1642. }
  1643. ao2_iterator_destroy(&i);
  1644. return CLI_SUCCESS;
  1645. }
  1646. static char *handle_cli_moh_show_classes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  1647. {
  1648. struct mohclass *class;
  1649. struct ao2_iterator i;
  1650. switch (cmd) {
  1651. case CLI_INIT:
  1652. e->command = "moh show classes";
  1653. e->usage =
  1654. "Usage: moh show classes\n"
  1655. " Lists all MusicOnHold classes.\n";
  1656. return NULL;
  1657. case CLI_GENERATE:
  1658. return NULL;
  1659. }
  1660. if (a->argc != e->args)
  1661. return CLI_SHOWUSAGE;
  1662. i = ao2_iterator_init(mohclasses, 0);
  1663. for (; (class = ao2_t_iterator_next(&i, "Show classes iterator")); mohclass_unref(class, "Unref iterator in moh show classes")) {
  1664. ast_cli(a->fd, "Class: %s\n", class->name);
  1665. ast_cli(a->fd, "\tMode: %s\n", S_OR(class->mode, "<none>"));
  1666. ast_cli(a->fd, "\tDirectory: %s\n", S_OR(class->dir, "<none>"));
  1667. if (ast_test_flag(class, MOH_ANNOUNCEMENT)) {
  1668. ast_cli(a->fd, "\tAnnouncement: %s\n", S_OR(class->announcement, "<none>"));
  1669. }
  1670. if (ast_test_flag(class, MOH_CUSTOM)) {
  1671. ast_cli(a->fd, "\tApplication: %s\n", S_OR(class->args, "<none>"));
  1672. ast_cli(a->fd, "\tKill Escalation Delay: %zu ms\n", class->kill_delay / 1000);
  1673. ast_cli(a->fd, "\tKill Method: %s\n",
  1674. class->kill_method == KILL_METHOD_PROCESS ? "process" : "process_group");
  1675. }
  1676. if (strcasecmp(class->mode, "files")) {
  1677. ast_cli(a->fd, "\tFormat: %s\n", ast_format_get_name(class->format));
  1678. }
  1679. }
  1680. ao2_iterator_destroy(&i);
  1681. return CLI_SUCCESS;
  1682. }
  1683. static struct ast_cli_entry cli_moh[] = {
  1684. AST_CLI_DEFINE(handle_cli_moh_reload, "Reload MusicOnHold"),
  1685. AST_CLI_DEFINE(handle_cli_moh_show_classes, "List MusicOnHold classes"),
  1686. AST_CLI_DEFINE(handle_cli_moh_show_files, "List MusicOnHold file-based classes")
  1687. };
  1688. static int moh_class_hash(const void *obj, const int flags)
  1689. {
  1690. const struct mohclass *class = obj;
  1691. return ast_str_case_hash(class->name);
  1692. }
  1693. static int moh_class_cmp(void *obj, void *arg, int flags)
  1694. {
  1695. struct mohclass *class = obj, *class2 = arg;
  1696. return strcasecmp(class->name, class2->name) ? 0 :
  1697. (flags & MOH_NOTDELETED) && (class->delete || class2->delete) ? 0 :
  1698. CMP_MATCH | CMP_STOP;
  1699. }
  1700. /*!
  1701. * \brief Load the module
  1702. *
  1703. * Module loading including tests for configuration or dependencies.
  1704. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  1705. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  1706. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  1707. * configuration file or other non-critical problem return
  1708. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  1709. */
  1710. static int load_module(void)
  1711. {
  1712. int res;
  1713. mohclasses = ao2_t_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 53,
  1714. moh_class_hash, NULL, moh_class_cmp, "Moh class container");
  1715. if (!mohclasses) {
  1716. return AST_MODULE_LOAD_DECLINE;
  1717. }
  1718. if (!load_moh_classes(0) && ast_check_realtime("musiconhold") == 0) { /* No music classes configured, so skip it */
  1719. ast_log(LOG_WARNING, "No music on hold classes configured, "
  1720. "disabling music on hold.\n");
  1721. } else {
  1722. ast_install_music_functions(local_ast_moh_start, local_ast_moh_stop,
  1723. local_ast_moh_cleanup);
  1724. }
  1725. res = ast_register_application_xml(play_moh, play_moh_exec);
  1726. ast_register_atexit(ast_moh_destroy);
  1727. ast_cli_register_multiple(cli_moh, ARRAY_LEN(cli_moh));
  1728. if (!res)
  1729. res = ast_register_application_xml(start_moh, start_moh_exec);
  1730. if (!res)
  1731. res = ast_register_application_xml(stop_moh, stop_moh_exec);
  1732. return AST_MODULE_LOAD_SUCCESS;
  1733. }
  1734. static int reload(void)
  1735. {
  1736. if (load_moh_classes(1)) {
  1737. ast_install_music_functions(local_ast_moh_start, local_ast_moh_stop,
  1738. local_ast_moh_cleanup);
  1739. }
  1740. return AST_MODULE_LOAD_SUCCESS;
  1741. }
  1742. static int moh_class_inuse(void *obj, void *arg, int flags)
  1743. {
  1744. struct mohclass *class = obj;
  1745. return AST_LIST_EMPTY(&class->members) ? 0 : CMP_MATCH | CMP_STOP;
  1746. }
  1747. static int unload_module(void)
  1748. {
  1749. int res = 0;
  1750. struct mohclass *class = NULL;
  1751. /* XXX This check shouldn't be required if module ref counting was being used
  1752. * properly ... */
  1753. if ((class = ao2_t_callback(mohclasses, 0, moh_class_inuse, NULL, "Module unload callback"))) {
  1754. class = mohclass_unref(class, "unref of class from module unload callback");
  1755. res = -1;
  1756. }
  1757. if (res < 0) {
  1758. ast_log(LOG_WARNING, "Unable to unload res_musiconhold due to active MOH channels\n");
  1759. return res;
  1760. }
  1761. ast_uninstall_music_functions();
  1762. ast_moh_destroy();
  1763. res = ast_unregister_application(play_moh);
  1764. res |= ast_unregister_application(start_moh);
  1765. res |= ast_unregister_application(stop_moh);
  1766. ast_cli_unregister_multiple(cli_moh, ARRAY_LEN(cli_moh));
  1767. ast_unregister_atexit(ast_moh_destroy);
  1768. return res;
  1769. }
  1770. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Music On Hold Resource",
  1771. .support_level = AST_MODULE_SUPPORT_CORE,
  1772. .load = load_module,
  1773. .unload = unload_module,
  1774. .reload = reload,
  1775. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  1776. );