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