res_musiconhold.c 59 KB

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