Debian Codegraph @

res/res_musiconhold.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2010, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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
19 /*! \file
20 *
21 * \brief Routines implementing music on hold
22 *
23 * \author Mark Spencer <[email protected]>
24 */
25
26 /*! \li \ref res_musiconhold.c uses the configuration file \ref musiconhold.conf
27 * \addtogroup configuration_file Configuration Files
28 */
29
30 /*!
31 * \page musiconhold.conf musiconhold.conf
32 * \verbinclude musiconhold.conf.sample
33 */
34
35 /*** MODULEINFO
36 <conflict>win32</conflict>
37 <support_level>core</support_level>
38 ***/
39
40 #include "asterisk.h"
41
42 #include <ctype.h>
43 #include <signal.h>
44 #include <sys/time.h>
45 #include <signal.h>
46 #include <netinet/in.h>
47 #include <sys/stat.h>
48 #include <dirent.h>
49
50 #ifdef SOLARIS
51 #include <thread.h>
52 #endif
53
54 #include "asterisk/lock.h"
55 #include "asterisk/file.h"
56 #include "asterisk/channel.h"
57 #include "asterisk/cel.h"
58 #include "asterisk/pbx.h"
59 #include "asterisk/app.h"
60 #include "asterisk/module.h"
61 #include "asterisk/translate.h"
62 #include "asterisk/say.h"
63 #include "asterisk/musiconhold.h"
64 #include "asterisk/config.h"
65 #include "asterisk/utils.h"
66 #include "asterisk/cli.h"
67 #include "asterisk/stringfields.h"
68 #include "asterisk/linkedlists.h"
69 #include "asterisk/stasis.h"
70 #include "asterisk/stasis_channels.h"
71 #include "asterisk/paths.h"
72 #include "asterisk/astobj2.h"
73 #include "asterisk/timing.h"
74 #include "asterisk/time.h"
75 #include "asterisk/poll-compat.h"
76
77 #define INITIAL_NUM_FILES 8
78 #define HANDLE_REF 1
79 #define DONT_UNREF 0
80
81 /*** DOCUMENTATION
82 <application name="MusicOnHold" language="en_US">
83 <since>
84 <version>0.1.12</version>
85 </since>
86 <synopsis>
87 Play Music On Hold indefinitely.
88 </synopsis>
89 <syntax>
90 <parameter name="class" required="true" />
91 <parameter name="duration" />
92 </syntax>
93 <description>
94 <para>Plays hold music specified by class. If omitted, the default music
95 source for the channel will be used. Change the default class with
96 Set(CHANNEL(musicclass)=...). If duration is given, hold music will be played
97 specified number of seconds. If duration is omitted, music plays indefinitely.
98 Returns <literal>0</literal> when done, <literal>-1</literal> on hangup.</para>
99 <para>This application does not automatically answer and should be preceeded by
100 an application such as Answer() or Progress().</para>
101 </description>
102 </application>
103 <application name="StartMusicOnHold" language="en_US">
104 <since>
105 <version>1.2.0</version>
106 </since>
107 <synopsis>
108 Play Music On Hold.
109 </synopsis>
110 <syntax>
111 <parameter name="class" required="true" />
112 </syntax>
113 <description>
114 <para>Starts playing music on hold, uses default music class for channel.
115 Starts playing music specified by class. If omitted, the default music
116 source for the channel will be used. Always returns <literal>0</literal>.</para>
117 </description>
118 </application>
119 <application name="StopMusicOnHold" language="en_US">
120 <since>
121 <version>1.2.0</version>
122 </since>
123 <synopsis>
124 Stop playing Music On Hold.
125 </synopsis>
126 <syntax />
127 <description>
128 <para>Stops playing music on hold.</para>
129 </description>
130 </application>
131 ***/
132
133 static const char play_moh[] = "MusicOnHold";
134 static const char start_moh[] = "StartMusicOnHold";
135 static const char stop_moh[] = "StopMusicOnHold";
136
137 static int respawn_time = 20;
138
139 struct moh_files_state {
140 /*! Holds a reference to the MOH class. */
141 struct mohclass *class;
142 struct ast_format *origwfmt;
143 struct ast_format *mohwfmt;
144 int announcement;
145 int samples;
146 int sample_queue;
147 int pos;
148 int save_pos;
149 int save_total;
150 char name[MAX_MUSICCLASS];
151 char save_pos_filename[PATH_MAX];
152 };
153
154 #define MOH_QUIET (1 << 0)
155 #define MOH_SINGLE (1 << 1)
156 #define MOH_CUSTOM (1 << 2)
157 #define MOH_RANDOMIZE (1 << 3)
158 #define MOH_SORTALPHA (1 << 4)
159 #define MOH_RANDSTART (MOH_RANDOMIZE | MOH_SORTALPHA) /*!< Sorted but start at random position */
160 #define MOH_SORTMODE (3 << 3)
161
162 #define MOH_CACHERTCLASSES (1 << 5) /*!< Should we use a separate instance of MOH for each user or not */
163 #define MOH_ANNOUNCEMENT (1 << 6) /*!< Do we play announcement files between songs on this channel? */
164 #define MOH_PREFERCHANNELCLASS (1 << 7) /*!< Should queue moh override channel moh */
165
166 #define MOH_LOOPLAST (1 << 8) /*!< Whether to loop the last file in the music class when we reach the end, rather than starting over */
167
168 /* Custom astobj2 flag */
169 #define MOH_NOTDELETED (1 << 30) /*!< Find only records that aren't deleted? */
170 #define MOH_REALTIME (1 << 31) /*!< Find only records that are realtime */
171
172 static struct ast_flags global_flags[1] = {{0}}; /*!< global MOH_ flags */
173
174 enum kill_methods {
175 KILL_METHOD_PROCESS_GROUP = 0,
176 KILL_METHOD_PROCESS
177 };
178
179 struct mohclass {
180 char name[MAX_MUSICCLASS];
181 char dir[256];
182 char args[256];
183 char announcement[256];
184 char mode[80];
185 char digit;
186 /*! An immutable vector of filenames in "files" mode */
187 struct ast_vector_string *files;
188 unsigned int flags;
189 /*! The format from the MOH source, not applicable to "files" mode */
190 struct ast_format *format;
191 /*! The pid of the external application delivering MOH */
192 int pid;
193 time_t start;
194 pthread_t thread;
195 /*! Millisecond delay between kill attempts */
196 size_t kill_delay;
197 /*! Kill method */
198 enum kill_methods kill_method;
199 /*! Source of audio */
200 int srcfd;
201 /*! Generic timer */
202 struct ast_timer *timer;
203 /*! Created on the fly, from RT engine */
204 unsigned int realtime:1;
205 unsigned int delete:1;
206 AST_LIST_HEAD_NOLOCK(, mohdata) members;
207 AST_LIST_ENTRY(mohclass) list;
208 /*!< Play the moh if the channel answered */
209 int answeredonly;
210 };
211
212 struct mohdata {
213 int pipe[2];
214 struct ast_format *origwfmt;
215 struct mohclass *parent;
216 struct ast_frame f;
217 AST_LIST_ENTRY(mohdata) list;
218 };
219
220 static struct ao2_container *mohclasses;
221
222 #define LOCAL_MPG_123 "/usr/local/bin/mpg123"
223 #define MPG_123 "/usr/bin/mpg123"
224 #define MAX_MP3S 256
225
226 static void moh_parse_options(struct ast_variable *var, struct mohclass *mohclass);
227 static int reload(void);
228
229 #define mohclass_ref(class,string) (ao2_t_ref((class), +1, (string)), class)
230
231 #ifndef AST_DEVMODE
232 #define mohclass_unref(class,string) ({ ao2_t_ref((class), -1, (string)); (struct mohclass *) NULL; })
233 #else
234 #define mohclass_unref(class,string) _mohclass_unref(class, string, __FILE__,__LINE__,__PRETTY_FUNCTION__)
235 static struct mohclass *_mohclass_unref(struct mohclass *class, const char *tag, const char *file, int line, const char *funcname)
236 {
237 struct mohclass *dup = ao2_callback(mohclasses, OBJ_POINTER, ao2_match_by_addr, class);
238
239 if (dup) {
240 if (__ao2_ref(dup, -1, tag, file, line, funcname) == 2) {
241 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",
242 class, class->name, file, line, funcname);
243 } else {
244 ao2_ref(class, -1);
245 }
246 } else {
247 __ao2_ref(class, -1, tag, file, line, funcname);
248 }
249 return NULL;
250 }
251 #endif
252
253 static void moh_post_start(struct ast_channel *chan, const char *moh_class_name)
254 {
255 struct stasis_message *message;
256 struct ast_json *json_object;
257 struct ast_json *cel_event;
258
259 ast_verb(3, "Started music on hold, class '%s', on channel '%s'\n",
260 moh_class_name, ast_channel_name(chan));
261
262 cel_event = ast_json_pack("{ s: s, s: {s: s }}",
263 "event", "MOH_STREAM_BEGIN",
264 "extra",
265 "class", moh_class_name
266 );
267 if (cel_event) {
268 ast_cel_publish_event(chan, AST_CEL_STREAM_BEGIN, cel_event);
269 } else {
270 ast_log(LOG_WARNING, "Unable to build extradata for music on hold STREAM_BEGIN event on channel %s", ast_channel_name(chan));
271 }
272 ast_json_unref(cel_event);
273
274 json_object = ast_json_pack("{s: s}", "class", moh_class_name);
275 if (!json_object) {
276 return;
277 }
278
279 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
280 ast_channel_moh_start_type(), json_object);
281 if (message) {
282 /* A channel snapshot must have been in the cache. */
283 ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
284
285 stasis_publish(ast_channel_topic(chan), message);
286 }
287 ao2_cleanup(message);
288 ast_json_unref(json_object);
289 }
290
291 static void moh_post_stop(struct ast_channel *chan)
292 {
293 struct stasis_message *message;
294 struct ast_json *cel_event;
295
296 ast_verb(3, "Stopped music on hold on %s\n", ast_channel_name(chan));
297
298 cel_event = ast_json_pack("{ s: s }", "event", "MOH_STREAM_END");
299 if (cel_event) {
300 ast_cel_publish_event(chan, AST_CEL_STREAM_END, cel_event);
301 }
302 ast_json_unref(cel_event);
303
304 message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan),
305 ast_channel_moh_stop_type(), NULL);
306 if (message) {
307 /* A channel snapshot must have been in the cache. */
308 ast_assert(((struct ast_channel_blob *) stasis_message_data(message))->snapshot != NULL);
309
310 stasis_publish(ast_channel_topic(chan), message);
311 }
312 ao2_cleanup(message);
313 }
314
315 /*
316 * Called with `chan` locked.
317 */
318 static void moh_files_release(struct ast_channel *chan, void *data)
319 {
320 struct moh_files_state *state;
321
322 if (!chan || !ast_channel_music_state(chan)) {
323 return;
324 }
325
326 state = ast_channel_music_state(chan);
327
328 if (ast_channel_stream(chan)) {
329 ast_closestream(ast_channel_stream(chan));
330 ast_channel_stream_set(chan, NULL);
331 }
332
333 moh_post_stop(chan);
334
335 ao2_ref(state->mohwfmt, -1);
336 state->mohwfmt = NULL; /* make sure to clear this format before restoring the original format */
337 if (state->origwfmt && ast_set_write_format(chan, state->origwfmt)) {
338 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format '%s'\n", ast_channel_name(chan),
339 ast_format_get_name(state->origwfmt));
340 }
341 ao2_cleanup(state->origwfmt);
342 state->origwfmt = NULL;
343
344 state->save_pos = state->pos;
345 state->announcement = 0;
346
347 state->class = mohclass_unref(state->class, "Unreffing channel's music class upon deactivation of generator");
348 }
349
350 /*
351 * Called with `chan` locked.
352 */
353 static int moh_files_next(struct ast_channel *chan)
354 {
355 struct moh_files_state *state = ast_channel_music_state(chan);
356 struct ast_vector_string *files;
357 int tries;
358 size_t file_count;
359
360 /* Discontinue a stream if it is running already */
361 if (ast_channel_stream(chan)) {
362 ast_closestream(ast_channel_stream(chan));
363 ast_channel_stream_set(chan, NULL);
364 }
365
366 if (ast_test_flag(state->class, MOH_ANNOUNCEMENT) && state->announcement == 0) {
367 state->announcement = 1;
368 if (ast_openstream_full(chan, state->class->announcement, ast_channel_language(chan), 1)) {
369 ast_debug(1, "%s Opened announcement '%s'\n", ast_channel_name(chan), state->class->announcement);
370 return 0;
371 }
372 } else {
373 state->announcement = 0;
374 }
375
376 ao2_lock(state->class);
377 files = ao2_bump(state->class->files);
378 ao2_unlock(state->class);
379
380 file_count = AST_VECTOR_SIZE(files);
381 if (!file_count) {
382 ast_log(LOG_WARNING, "No files available for class '%s'\n", state->class->name);
383 ao2_ref(files, -1);
384 return -1;
385 }
386
387 if (state->pos == 0 && ast_strlen_zero(state->save_pos_filename)) {
388 /* First time so lets play the file. */
389 state->save_pos = -1;
390 } else if (state->save_pos >= 0 && state->save_pos < file_count && !strcmp(AST_VECTOR_GET(files, state->save_pos), state->save_pos_filename)) {
391 /* If a specific file has been saved confirm it still exists and that it is still valid */
392 state->pos = state->save_pos;
393 state->save_pos = -1;
394 } else if (ast_test_flag(state->class, MOH_SORTMODE) == MOH_RANDOMIZE) {
395 /* Get a random file and ensure we can open it */
396 for (tries = 0; tries < 20; tries++) {
397 state->pos = ast_random() % file_count;
398 if (ast_fileexists(AST_VECTOR_GET(files, state->pos), NULL, NULL) > 0) {
399 break;
400 }
401 }
402 state->save_pos = -1;
403 state->samples = 0;
404 } else {
405 /* This is easy, just increment our position and make sure we don't exceed the total file count */
406 state->pos++;
407 if (ast_test_flag(state->class, MOH_LOOPLAST)) {
408 state->pos = MIN(file_count - 1, state->pos);
409 } else {
410 state->pos %= file_count;
411 }
412 state->save_pos = -1;
413 state->samples = 0;
414 }
415
416 for (tries = 0; tries < file_count; ++tries) {
417 if (ast_openstream_full(chan, AST_VECTOR_GET(files, state->pos), ast_channel_language(chan), 1)) {
418 break;
419 }
420
421 ast_log(LOG_WARNING, "Unable to open file '%s': %s\n", AST_VECTOR_GET(files, state->pos), strerror(errno));
422 state->pos++;
423 state->pos %= file_count;
424 }
425
426 if (tries == file_count) {
427 ao2_ref(files, -1);
428 return -1;
429 }
430
431 /* Record the pointer to the filename for position resuming later */
432 ast_copy_string(state->save_pos_filename, AST_VECTOR_GET(files, state->pos), sizeof(state->save_pos_filename));
433
434 ast_debug(1, "%s Opened file %d '%s'\n", ast_channel_name(chan), state->pos, state->save_pos_filename);
435
436 if (state->samples) {
437 size_t loc;
438 /* seek *SHOULD* be good since it's from a known location */
439 ast_seekstream(ast_channel_stream(chan), state->samples, SEEK_SET);
440 /* if the seek failed then recover because if there is not a valid read,
441 * moh_files_generate will return -1 and MOH will stop */
442 loc = ast_tellstream(ast_channel_stream(chan));
443 if (state->samples > loc && loc) {
444 /* seek one sample from the end for one guaranteed valid read */
445 ast_seekstream(ast_channel_stream(chan), 1, SEEK_END);
446 }
447 }
448
449 ao2_ref(files, -1);
450 return 0;
451 }
452
453 /*
454 * Called with `chan` locked.
455 */
456 static struct ast_frame *moh_files_readframe(struct ast_channel *chan)
457 {
458 struct ast_frame *f;
459
460 f = ast_readframe(ast_channel_stream(chan));
461 if (!f) {
462 /* Either there was no file stream setup or we reached EOF. */
463 if (!moh_files_next(chan)) {
464 /*
465 * Either we resetup the previously saved file stream position
466 * or we started a new file stream.
467 */
468 f = ast_readframe(ast_channel_stream(chan));
469 if (!f) {
470 /*
471 * We can get here if we were very unlucky because the
472 * resetup file stream was saved at EOF when MOH was
473 * previously stopped.
474 */
475 if (!moh_files_next(chan)) {
476 f = ast_readframe(ast_channel_stream(chan));
477 }
478 }
479 }
480 }
481
482 return f;
483 }
484
485 /*
486 * Called with `chan` locked.
487 */
488 static void moh_files_write_format_change(struct ast_channel *chan, void *data)
489 {
490 struct moh_files_state *state = ast_channel_music_state(chan);
491
492 /* In order to prevent a recursive call to this function as a result
493 * of setting the moh write format back on the channel. Clear
494 * the moh write format before setting the write format on the channel.*/
495 if (state->origwfmt) {
496 struct ast_format *tmp;
497
498 tmp = ao2_bump(ast_channel_writeformat(chan));
499 ao2_replace(state->origwfmt, NULL);
500 if (state->mohwfmt) {
501 ast_set_write_format(chan, state->mohwfmt);
502 }
503 state->origwfmt = tmp;
504 }
505 }
506
507 static int moh_files_generator(struct ast_channel *chan, void *data, int len, int samples)
508 {
509 struct moh_files_state *state;
510 struct ast_frame *f = NULL;
511 int res = 0, sample_queue = 0;
512
513 ast_channel_lock(chan);
514 state = ast_channel_music_state(chan);
515 state->sample_queue += samples;
516 /* save the sample queue value for un-locked access */
517 sample_queue = state->sample_queue;
518 ast_channel_unlock(chan);
519
520 while (sample_queue > 0) {
521 ast_channel_lock(chan);
522 f = moh_files_readframe(chan);
523 if (!f) {
524 ast_channel_unlock(chan);
525 return -1;
526 }
527
528 /* Only track our offset within the current file if we are not in the
529 * the middle of an announcement */
530 if (!state->announcement) {
531 state->samples += f->samples;
532 }
533
534 state->sample_queue -= f->samples;
535 if (ast_format_cmp(f->subclass.format, state->mohwfmt) == AST_FORMAT_CMP_NOT_EQUAL) {
536 ao2_replace(state->mohwfmt, f->subclass.format);
537 }
538
539 /* We need to be sure that we unlock
540 * the channel prior to calling
541 * ast_write, but after our references to state
542 * as it refers to chan->music_state. Update
543 * sample_queue for our loop
544 * Otherwise, the recursive locking that occurs
545 * can cause deadlocks when using indirect
546 * channels, like local channels
547 */
548 sample_queue = state->sample_queue;
549 ast_channel_unlock(chan);
550
551 res = ast_write(chan, f);
552 ast_frfree(f);
553 if (res < 0) {
554 ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
555 return -1;
556 }
557 }
558 return res;
559 }
560
561 /*
562 * Called with `chan` locked.
563 */
564 static void *moh_files_alloc(struct ast_channel *chan, void *params)
565 {
566 struct moh_files_state *state;
567 struct mohclass *class = params;
568 size_t file_count;
569
570 state = ast_channel_music_state(chan);
571 if (!state && (state = ast_calloc(1, sizeof(*state)))) {
572 ast_channel_music_state_set(chan, state);
573 ast_module_ref(ast_module_info->self);
574 } else {
575 if (!state) {
576 return NULL;
577 }
578 if (state->class) {
579 mohclass_unref(state->class, "Uh Oh. Restarting MOH with an active class");
580 ast_log(LOG_WARNING, "Uh Oh. Restarting MOH with an active class\n");
581 }
582 }
583
584 ao2_lock(class);
585 file_count = AST_VECTOR_SIZE(class->files);
586 ao2_unlock(class);
587
588 /* Resume MOH from where we left off last time or start from scratch? */
589 if (state->save_total != file_count || strcmp(state->name, class->name) != 0) {
590 /* Start MOH from scratch. */
591 ao2_cleanup(state->origwfmt);
592 ao2_cleanup(state->mohwfmt);
593 memset(state, 0, sizeof(*state));
594 if (ast_test_flag(class, MOH_RANDOMIZE) && file_count) {
595 state->pos = ast_random() % file_count;
596 }
597 }
598
599 state->class = mohclass_ref(class, "Reffing music class for channel");
600 /* it's possible state is not a new allocation, don't leak old refs */
601 ao2_replace(state->origwfmt, ast_channel_writeformat(chan));
602 ao2_replace(state->mohwfmt, ast_channel_writeformat(chan));
603 /* For comparison on restart of MOH (see above) */
604 ast_copy_string(state->name, class->name, sizeof(state->name));
605 state->save_total = file_count;
606
607 moh_post_start(chan, class->name);
608
609 return state;
610 }
611
612 static int moh_digit_match(void *obj, void *arg, int flags)
613 {
614 char *digit = arg;
615 struct mohclass *class = obj;
616
617 return (*digit == class->digit) ? CMP_MATCH | CMP_STOP : 0;
618 }
619
620 /*! \note This function should be called with the mohclasses list locked */
621 static struct mohclass *get_mohbydigit(char digit)
622 {
623 return ao2_t_callback(mohclasses, 0, moh_digit_match, &digit, "digit callback");
624 }
625
626 static void moh_handle_digit(struct ast_channel *chan, char digit)
627 {
628 struct mohclass *class;
629 const char *classname = NULL;
630
631 if ((class = get_mohbydigit(digit))) {
632 classname = ast_strdupa(class->name);
633 class = mohclass_unref(class, "Unreffing ao2_find from finding by digit");
634 ast_channel_musicclass_set(chan, classname);
635 ast_moh_stop(chan);
636 ast_moh_start(chan, classname, NULL);
637 }
638 }
639
640 static struct ast_generator moh_file_stream = {
641 .alloc = moh_files_alloc,
642 .release = moh_files_release,
643 .generate = moh_files_generator,
644 .digit = moh_handle_digit,
645 .write_format_change = moh_files_write_format_change,
646 };
647
648 static int spawn_mp3(struct mohclass *class)
649 {
650 int fds[2];
651 int files = 0;
652 char fns[MAX_MP3S][80];
653 char *argv[MAX_MP3S + 50];
654 char xargs[256];
655 char *argptr;
656 int argc = 0;
657 DIR *dir = NULL;
658 struct dirent *de;
659
660
661 if (!strcasecmp(class->dir, "nodir")) {
662 files = 1;
663 } else {
664 dir = opendir(class->dir);
665 if (!dir && strncasecmp(class->dir, "http://", 7)) {
666 ast_log(LOG_WARNING, "%s is not a valid directory\n", class->dir);
667 return -1;
668 }
669 }
670
671 if (!ast_test_flag(class, MOH_CUSTOM)) {
672 argv[argc++] = "mpg123";
673 argv[argc++] = "-q";
674 argv[argc++] = "-s";
675 argv[argc++] = "--mono";
676 argv[argc++] = "-r";
677 argv[argc++] = "8000";
678
679 if (!ast_test_flag(class, MOH_SINGLE)) {
680 argv[argc++] = "-b";
681 argv[argc++] = "2048";
682 }
683
684 argv[argc++] = "-f";
685
686 if (ast_test_flag(class, MOH_QUIET))
687 argv[argc++] = "4096";
688 else
689 argv[argc++] = "8192";
690
691 /* Look for extra arguments and add them to the list */
692 ast_copy_string(xargs, class->args, sizeof(xargs));
693 argptr = xargs;
694 while (!ast_strlen_zero(argptr)) {
695 argv[argc++] = argptr;
696 strsep(&argptr, ",");
697 }
698 } else {
699 /* Format arguments for argv vector */
700 ast_copy_string(xargs, class->args, sizeof(xargs));
701 argptr = xargs;
702 while (!ast_strlen_zero(argptr)) {
703 argv[argc++] = argptr;
704 strsep(&argptr, " ");
705 }
706 }
707
708 if (!strncasecmp(class->dir, "http://", 7)) {
709 ast_copy_string(fns[files], class->dir, sizeof(fns[files]));
710 argv[argc++] = fns[files];
711 files++;
712 } else if (dir) {
713 while ((de = readdir(dir)) && (files < MAX_MP3S)) {
714 if ((strlen(de->d_name) > 3) &&
715 ((ast_test_flag(class, MOH_CUSTOM) &&
716 (!strcasecmp(de->d_name + strlen(de->d_name) - 4, ".raw") ||
717 !strcasecmp(de->d_name + strlen(de->d_name) - 4, ".sln"))) ||
718 !strcasecmp(de->d_name + strlen(de->d_name) - 4, ".mp3"))) {
719 ast_copy_string(fns[files], de->d_name, sizeof(fns[files]));
720 argv[argc++] = fns[files];
721 files++;
722 }
723 }
724 }
725 argv[argc] = NULL;
726 if (dir) {
727 closedir(dir);
728 }
729 if (pipe(fds)) {
730 ast_log(LOG_WARNING, "Pipe failed\n");
731 return -1;
732 }
733 if (!files) {
734 ast_log(LOG_WARNING, "Found no files in '%s'\n", class->dir);
735 close(fds[0]);
736 close(fds[1]);
737 return -1;
738 }
739 if (!strncasecmp(class->dir, "http://", 7) && time(NULL) - class->start < respawn_time) {
740 sleep(respawn_time - (time(NULL) - class->start));
741 }
742
743 time(&class->start);
744 class->pid = ast_safe_fork(0);
745 if (class->pid < 0) {
746 close(fds[0]);
747 close(fds[1]);
748 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
749 return -1;
750 }
751 if (!class->pid) {
752 if (ast_opt_high_priority)
753 ast_set_priority(0);
754
755 close(fds[0]);
756 /* Stdout goes to pipe */
757 dup2(fds[1], STDOUT_FILENO);
758
759 /* Close everything else */
760 ast_close_fds_above_n(STDERR_FILENO);
761
762 /* Child */
763 if (strncasecmp(class->dir, "http://", 7) && strcasecmp(class->dir, "nodir") && chdir(class->dir) < 0) {
764 ast_log(LOG_WARNING, "chdir() failed: %s\n", strerror(errno));
765 _exit(1);
766 }
767 setpgid(0, getpid());
768 if (ast_test_flag(class, MOH_CUSTOM)) {
769 execv(argv[0], argv);
770 } else {
771 /* Default install is /usr/local/bin */
772 execv(LOCAL_MPG_123, argv);
773 /* Many places have it in /usr/bin */
774 execv(MPG_123, argv);
775 /* Check PATH as a last-ditch effort */
776 execvp("mpg123", argv);
777 }
778 /* Can't use logger, since log FDs are closed */
779 fprintf(stderr, "MOH: exec failed: %s\n", strerror(errno));
780 close(fds[1]);
781 _exit(1);
782 } else {
783 /* Parent */
784 close(fds[1]);
785 }
786 return fds[0];
787 }
788
789 static int killer(pid_t pid, int signum, enum kill_methods kill_method)
790 {
791 switch (kill_method) {
792 case KILL_METHOD_PROCESS_GROUP:
793 return killpg(pid, signum);
794 case KILL_METHOD_PROCESS:
795 return kill(pid, signum);
796 }
797
798 return -1;
799 }
800
801 static void killpid(int pid, size_t delay, enum kill_methods kill_method)
802 {
803 if (killer(pid, SIGHUP, kill_method) < 0) {
804 if (errno == ESRCH) {
805 return;
806 }
807 ast_log(LOG_WARNING, "Unable to send a SIGHUP to MOH process '%d'?!!: %s\n", pid, strerror(errno));
808 } else {
809 ast_debug(1, "Sent HUP to pid %d%s\n", pid,
810 kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
811 }
812 usleep(delay);
813 if (killer(pid, SIGTERM, kill_method) < 0) {
814 if (errno == ESRCH) {
815 return;
816 }
817 ast_log(LOG_WARNING, "Unable to terminate MOH process '%d'?!!: %s\n", pid, strerror(errno));
818 } else {
819 ast_debug(1, "Sent TERM to pid %d%s\n", pid,
820 kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
821 }
822 usleep(delay);
823 if (killer(pid, SIGKILL, kill_method) < 0) {
824 if (errno == ESRCH) {
825 return;
826 }
827 ast_log(LOG_WARNING, "Unable to kill MOH process '%d'?!!: %s\n", pid, strerror(errno));
828 } else {
829 ast_debug(1, "Sent KILL to pid %d%s\n", pid,
830 kill_method == KILL_METHOD_PROCESS_GROUP ? " and all children" : " only");
831 }
832 }
833
834 static void *monmp3thread(void *data)
835 {
836 #define MOH_MS_INTERVAL 100
837
838 struct mohclass *class = data;
839 struct mohdata *moh;
840 short sbuf[8192];
841 int res = 0, res2;
842 int len;
843 struct timeval deadline, tv_tmp;
844
845 deadline.tv_sec = 0;
846 deadline.tv_usec = 0;
847 for(;/* ever */;) {
848 pthread_testcancel();
849 /* Spawn mp3 player if it's not there */
850 if (class->srcfd < 0) {
851 if ((class->srcfd = spawn_mp3(class)) < 0) {
852 ast_log(LOG_WARNING, "Unable to spawn mp3player\n");
853 /* Try again later */
854 sleep(500);
855 continue;
856 }
857 }
858 if (class->timer) {
859 struct pollfd pfd = { .fd = ast_timer_fd(class->timer), .events = POLLIN | POLLPRI, };
860
861 #ifdef SOLARIS
862 thr_yield();
863 #endif
864 /* Pause some amount of time */
865 if (ast_poll(&pfd, 1, -1) > 0) {
866 if (ast_timer_ack(class->timer, 1) < 0) {
867 ast_log(LOG_ERROR, "Failed to acknowledge timer for mp3player\n");
868 return NULL;
869 }
870 /* 25 samples per second => 40ms framerate => 320 samples */
871 res = 320; /* 320/40 = 8 samples/ms */
872 } else {
873 ast_log(LOG_WARNING, "poll() failed: %s\n", strerror(errno));
874 res = 0;
875 }
876 pthread_testcancel();
877 } else {
878 long delta;
879 /* Reliable sleep */
880 tv_tmp = ast_tvnow();
881 if (ast_tvzero(deadline))
882 deadline = tv_tmp;
883 delta = ast_tvdiff_ms(tv_tmp, deadline);
884 if (delta < MOH_MS_INTERVAL) { /* too early */
885 deadline = ast_tvadd(deadline, ast_samp2tv(MOH_MS_INTERVAL, 1000)); /* next deadline */
886 usleep(1000 * (MOH_MS_INTERVAL - delta));
887 pthread_testcancel();
888 } else {
889 ast_log(LOG_NOTICE, "Request to schedule in the past?!?!\n");
890 deadline = tv_tmp;
891 }
892 /* 10 samples per second (MOH_MS_INTERVAL) => 100ms framerate => 800 samples */
893 res = 8 * MOH_MS_INTERVAL; /* 800/100 = 8 samples/ms */
894 }
895 /* For non-8000Hz formats, we need to alter the resolution */
896 res = res * ast_format_get_sample_rate(class->format) / 8000;
897
898 if ((strncasecmp(class->dir, "http://", 7) && strcasecmp(class->dir, "nodir")) && AST_LIST_EMPTY(&class->members))
899 continue;
900 /* Read mp3 audio */
901 len = ast_format_determine_length(class->format, res);
902
903 if ((res2 = read(class->srcfd, sbuf, len)) != len) {
904 if (!res2) {
905 close(class->srcfd);
906 class->srcfd = -1;
907 pthread_testcancel();
908 if (class->pid > 1) {
909 killpid(class->pid, class->kill_delay, class->kill_method);
910 class->pid = 0;
911 }
912 } else {
913 ast_debug(1, "Read %d bytes of audio while expecting %d\n", res2, len);
914 }
915 continue;
916 }
917
918 pthread_testcancel();
919
920 ao2_lock(class);
921 AST_LIST_TRAVERSE(&class->members, moh, list) {
922 /* Write data */
923 if ((res = write(moh->pipe[1], sbuf, res2)) != res2) {
924 ast_debug(1, "Only wrote %d of %d bytes to pipe\n", res, res2);
925 }
926 }
927 ao2_unlock(class);
928 }
929 return NULL;
930 }
931
932 static int play_moh_exec(struct ast_channel *chan, const char *data)
933 {
934 char *parse;
935 char *class;
936 int timeout = -1;
937 int res;
938 AST_DECLARE_APP_ARGS(args,
939 AST_APP_ARG(class);
940 AST_APP_ARG(duration);
941 );
942
943 parse = ast_strdupa(data);
944
945 AST_STANDARD_APP_ARGS(args, parse);
946
947 if (!ast_strlen_zero(args.duration)) {
948 if (sscanf(args.duration, "%30d", &timeout) == 1) {
949 timeout *= 1000;
950 } else {
951 ast_log(LOG_WARNING, "Invalid MusicOnHold duration '%s'. Will wait indefinitely.\n", args.duration);
952 }
953 }
954
955 class = S_OR(args.class, NULL);
956 if (ast_moh_start(chan, class, NULL)) {
957 ast_log(LOG_WARNING, "Unable to start music on hold class '%s' on channel %s\n", class, ast_channel_name(chan));
958 return 0;
959 }
960
961 if (timeout > 0)
962 res = ast_safe_sleep(chan, timeout);
963 else {
964 while (!(res = ast_safe_sleep(chan, 10000)));
965 }
966
967 ast_moh_stop(chan);
968
969 return res;
970 }
971
972 static int start_moh_exec(struct ast_channel *chan, const char *data)
973 {
974 char *parse;
975 char *class;
976 AST_DECLARE_APP_ARGS(args,
977 AST_APP_ARG(class);
978 );
979
980 parse = ast_strdupa(data);
981
982 AST_STANDARD_APP_ARGS(args, parse);
983
984 class = S_OR(args.class, NULL);
985 if (ast_moh_start(chan, class, NULL))
986 ast_log(LOG_WARNING, "Unable to start music on hold class '%s' on channel %s\n", class, ast_channel_name(chan));
987
988 return 0;
989 }
990
991 static int stop_moh_exec(struct ast_channel *chan, const char *data)
992 {
993 ast_moh_stop(chan);
994
995 return 0;
996 }
997
998 #define get_mohbyname(a,b,c) _get_mohbyname(a,b,c,__FILE__,__LINE__,__PRETTY_FUNCTION__)
999
1000 static struct mohclass *_get_mohbyname(const char *name, int warn, int flags, const char *file, int lineno, const char *funcname)
1001 {
1002 struct mohclass *moh = NULL;
1003 struct mohclass tmp_class = {
1004 .flags = 0,
1005 };
1006
1007 ast_copy_string(tmp_class.name, name, sizeof(tmp_class.name));
1008
1009 moh = __ao2_find(mohclasses, &tmp_class, flags,
1010 "get_mohbyname", file, lineno, funcname);
1011
1012 if (!moh && warn) {
1013 ast_log(LOG_WARNING, "Music on Hold class '%s' not found in memory. Verify your configuration.\n", name);
1014 }
1015
1016 return moh;
1017 }
1018
1019 static struct mohdata *mohalloc(struct mohclass *cl)
1020 {
1021 struct mohdata *moh;
1022
1023 if (!(moh = ast_calloc(1, sizeof(*moh))))
1024 return NULL;
1025
1026 if (ast_pipe_nonblock(moh->pipe)) {
1027 ast_log(LOG_WARNING, "Failed to create pipe: %s\n", strerror(errno));
1028 ast_free(moh);
1029 return NULL;
1030 }
1031
1032 moh->f.frametype = AST_FRAME_VOICE;
1033 moh->f.subclass.format = cl->format;
1034 moh->f.offset = AST_FRIENDLY_OFFSET;
1035
1036 moh->parent = mohclass_ref(cl, "Reffing music class for mohdata parent");
1037
1038 ao2_lock(cl);
1039 AST_LIST_INSERT_HEAD(&cl->members, moh, list);
1040 ao2_unlock(cl);
1041
1042 return moh;
1043 }
1044
1045 /*
1046 * Called with `chan` locked.
1047 */
1048 static void moh_release(struct ast_channel *chan, void *data)
1049 {
1050 struct mohdata *moh = data;
1051 struct mohclass *class = moh->parent;
1052 struct ast_format *oldwfmt;
1053
1054 ao2_lock(class);
1055 AST_LIST_REMOVE(&moh->parent->members, moh, list);
1056 ao2_unlock(class);
1057
1058 close(moh->pipe[0]);
1059 close(moh->pipe[1]);
1060
1061 oldwfmt = moh->origwfmt;
1062
1063 moh->parent = class = mohclass_unref(class, "unreffing moh->parent upon deactivation of generator");
1064
1065 ast_free(moh);
1066
1067 if (chan) {
1068 struct moh_files_state *state;
1069
1070 state = ast_channel_music_state(chan);
1071 if (state && state->class) {
1072 state->class = mohclass_unref(state->class, "Unreffing channel's music class upon deactivation of generator");
1073 }
1074 if (oldwfmt && ast_set_write_format(chan, oldwfmt)) {
1075 ast_log(LOG_WARNING, "Unable to restore channel '%s' to format %s\n",
1076 ast_channel_name(chan), ast_format_get_name(oldwfmt));
1077 }
1078
1079 moh_post_stop(chan);
1080 }
1081
1082 ao2_cleanup(oldwfmt);
1083 }
1084
1085 /*
1086 * Called with `chan` locked.
1087 */
1088 static void *moh_alloc(struct ast_channel *chan, void *params)
1089 {
1090 struct mohdata *res;
1091 struct mohclass *class = params;
1092 struct moh_files_state *state;
1093
1094 /* Initiating music_state for current channel. Channel should know name of moh class */
1095 state = ast_channel_music_state(chan);
1096 if (!state && (state = ast_calloc(1, sizeof(*state)))) {
1097 ast_channel_music_state_set(chan, state);
1098 ast_module_ref(ast_module_info->self);
1099 } else {
1100 if (!state) {
1101 return NULL;
1102 }
1103 if (state->class) {
1104 mohclass_unref(state->class, "Uh Oh. Restarting MOH with an active class");
1105 ast_log(LOG_WARNING, "Uh Oh. Restarting MOH with an active class\n");
1106 }
1107 ao2_cleanup(state->origwfmt);
1108 ao2_cleanup(state->mohwfmt);
1109 memset(state, 0, sizeof(*state));
1110 }
1111
1112 if ((res = mohalloc(class))) {
1113 res->origwfmt = ao2_bump(ast_channel_writeformat(chan));
1114 if (ast_set_write_format(chan, class->format)) {
1115 ast_log(LOG_WARNING, "Unable to set channel '%s' to format '%s'\n", ast_channel_name(chan),
1116 ast_format_get_name(class->format));
1117 moh_release(NULL, res);
1118 res = NULL;
1119 } else {
1120 state->class = mohclass_ref(class, "Placing reference into state container");
1121 moh_post_start(chan, class->name);
1122 }
1123 }
1124 return res;
1125 }
1126
1127 static int moh_generate(struct ast_channel *chan, void *data, int len, int samples)
1128 {
1129 struct mohdata *moh = data;
1130 short buf[1280 + AST_FRIENDLY_OFFSET / 2];
1131 int res;
1132
1133 len = ast_format_determine_length(moh->parent->format, samples);
1134
1135 if (len > sizeof(buf) - AST_FRIENDLY_OFFSET) {
1136 ast_log(LOG_WARNING, "Only doing %d of %d requested bytes on %s\n", (int)sizeof(buf), len, ast_channel_name(chan));
1137 len = sizeof(buf) - AST_FRIENDLY_OFFSET;
1138 }
1139 res = read(moh->pipe[0], buf + AST_FRIENDLY_OFFSET/2, len);
1140 if (res <= 0)
1141 return 0;
1142
1143 moh->f.datalen = res;
1144 moh->f.data.ptr = buf + AST_FRIENDLY_OFFSET / 2;
1145 moh->f.samples = ast_codec_samples_count(&moh->f);
1146
1147 if (ast_write(chan, &moh->f) < 0) {
1148 ast_log(LOG_WARNING, "Failed to write frame to '%s': %s\n", ast_channel_name(chan), strerror(errno));
1149 return -1;
1150 }
1151
1152 return 0;
1153 }
1154
1155 static struct ast_generator mohgen = {
1156 .alloc = moh_alloc,
1157 .release = moh_release,
1158 .generate = moh_generate,
1159 .digit = moh_handle_digit,
1160 };
1161
1162 static void moh_file_vector_destructor(void *obj)
1163 {
1164 struct ast_vector_string *files = obj;
1165 AST_VECTOR_RESET(files, ast_free);
1166 AST_VECTOR_FREE(files);
1167 }
1168
1169 static struct ast_vector_string *moh_file_vector_alloc(int initial_capacity)
1170 {
1171 struct ast_vector_string *files = ao2_alloc_options(
1172 sizeof(struct ast_vector_string),
1173 moh_file_vector_destructor,
1174 AO2_ALLOC_OPT_LOCK_NOLOCK);
1175 if (files) {
1176 AST_VECTOR_INIT(files, initial_capacity);
1177 }
1178 return files;
1179 }
1180
1181 static void moh_parse_options(struct ast_variable *var, struct mohclass *mohclass)
1182 {
1183 struct ast_vector_string *playlist_entries = NULL;
1184
1185 for (; var; var = var->next) {
1186 if (!strcasecmp(var->name, "name")) {
1187 ast_copy_string(mohclass->name, var->value, sizeof(mohclass->name));
1188 } else if (!strcasecmp(var->name, "mode")) {
1189 ast_copy_string(mohclass->mode, var->value, sizeof(mohclass->mode));
1190 } else if (!strcasecmp(var->name, "entry")) {
1191 if (ast_begins_with(var->value, "/") || strstr(var->value, "://")) {
1192 char *dup;
1193
1194 if (!playlist_entries) {
1195 playlist_entries = moh_file_vector_alloc(16);
1196 if (!playlist_entries) {
1197 continue;
1198 }
1199 }
1200
1201 dup = ast_strdup(var->value);
1202 if (!dup) {
1203 continue;
1204 }
1205
1206 if (ast_begins_with(dup, "/")) {
1207 char *last_pos_dot = strrchr(dup, '.');
1208 char *last_pos_slash = strrchr(dup, '/');
1209 if (last_pos_dot && last_pos_dot > last_pos_slash) {
1210 ast_log(LOG_WARNING, "The playlist entry '%s' may include an extension, which could prevent it from playing.\n",
1211 dup);
1212 }
1213 }
1214
1215 AST_VECTOR_APPEND(playlist_entries, dup);
1216 } else {
1217 ast_log(LOG_ERROR, "Playlist entries must be a URL or an absolute path, '%s' provided.\n", var->value);
1218 }
1219 } else if (!strcasecmp(var->name, "directory")) {
1220 ast_copy_string(mohclass->dir, var->value, sizeof(mohclass->dir));
1221 } else if (!strcasecmp(var->name, "application")) {
1222 ast_copy_string(mohclass->args, var->value, sizeof(mohclass->args));
1223 } else if (!strcasecmp(var->name, "announcement")) {
1224 ast_copy_string(mohclass->announcement, var->value, sizeof(mohclass->announcement));
1225 ast_set_flag(mohclass, MOH_ANNOUNCEMENT);
1226 } else if (!strcasecmp(var->name, "digit") && (isdigit(*var->value) || strchr("*#", *var->value))) {
1227 mohclass->digit = *var->value;
1228 } else if (!strcasecmp(var->name, "random")) {
1229 static int deprecation_warning = 0;
1230 if (!deprecation_warning) {
1231 ast_log(LOG_WARNING, "Music on hold 'random' setting is deprecated in 14. Please use 'sort=random' instead.\n");
1232 deprecation_warning = 1;
1233 }
1234 ast_set2_flag(mohclass, ast_true(var->value), MOH_RANDOMIZE);
1235 } else if (!strcasecmp(var->name, "sort")) {
1236 if (!strcasecmp(var->value, "random")) {
1237 ast_set_flag(mohclass, MOH_RANDOMIZE);
1238 } else if (!strcasecmp(var->value, "alpha")) {
1239 ast_set_flag(mohclass, MOH_SORTALPHA);
1240 } else if (!strcasecmp(var->value, "randstart")) {
1241 ast_set_flag(mohclass, MOH_RANDSTART);
1242 }
1243 } else if (!strcasecmp(var->name, "loop_last")) {
1244 if (ast_true(var->value)) {
1245 ast_set_flag(mohclass, MOH_LOOPLAST);
1246 } else {
1247 ast_clear_flag(mohclass, MOH_LOOPLAST);
1248 }
1249 } else if (!strcasecmp(var->name, "format") && !ast_strlen_zero(var->value)) {
1250 ao2_cleanup(mohclass->format);
1251 mohclass->format = ast_format_cache_get(var->value);
1252 if (!mohclass->format) {
1253 ast_log(LOG_WARNING, "Unknown format '%s' -- defaulting to SLIN\n", var->value);
1254 mohclass->format = ao2_bump(ast_format_slin);
1255 }
1256 } else if (!strcasecmp(var->name, "kill_escalation_delay")) {
1257 if (sscanf(var->value, "%zu", &mohclass->kill_delay) == 1) {
1258 mohclass->kill_delay *= 1000;
1259 } else {
1260 ast_log(LOG_WARNING, "kill_escalation_delay '%s' is invalid. Setting to 100ms\n", var->value);
1261 mohclass->kill_delay = 100000;
1262 }
1263 } else if (!strcasecmp(var->name, "kill_method")) {
1264 if (!strcasecmp(var->value, "process")) {
1265 mohclass->kill_method = KILL_METHOD_PROCESS;
1266 } else if (!strcasecmp(var->value, "process_group")) {
1267 mohclass->kill_method = KILL_METHOD_PROCESS_GROUP;
1268 } else {
1269 ast_log(LOG_WARNING, "kill_method '%s' is invalid. Setting to 'process_group'\n", var->value);
1270 mohclass->kill_method = KILL_METHOD_PROCESS_GROUP;
1271 }
1272 } else if (!strcasecmp(var->name, "answeredonly")) {
1273 mohclass->answeredonly = ast_true(var->value) ? 1: 0;
1274 }
1275 }
1276
1277 if (playlist_entries) {
1278 /* If we aren't in playlist mode, drop any list we may have already built */
1279 if (strcasecmp(mohclass->mode, "playlist")) {
1280 ast_log(LOG_NOTICE, "Ignoring playlist entries because we are in '%s' mode.\n",
1281 mohclass->mode);
1282 ao2_ref(playlist_entries, -1);
1283 return;
1284 }
1285
1286 AST_VECTOR_COMPACT(playlist_entries);
1287
1288 /* We don't need to lock here because we are the thread that
1289 * created this mohclass and we haven't published it yet */
1290 ao2_ref(mohclass->files, -1);
1291 mohclass->files = playlist_entries;
1292 }
1293 }
1294
1295 static int on_moh_file(const char *directory, const char *filename, void *obj)
1296 {
1297 struct ast_vector_string *files = obj;
1298 char *full_path;
1299 const char *extension;
1300
1301 /* Skip files that starts with a dot */
1302 if (*filename == '.') {
1303 ast_debug(4, "Skipping '%s/%s' because it starts with a dot\n",
1304 directory, filename);
1305 return 0;
1306 }
1307
1308 /* We can't do anything with files that don't have an extension,
1309 * so check that first and punt if we can't find something */
1310 extension = strrchr(filename, '.');
1311 if (!extension) {
1312 ast_debug(4, "Skipping '%s/%s' because it doesn't have an extension\n",
1313 directory, filename);
1314 return 0;
1315 }
1316
1317 /* The extension needs at least two characters (after the .) to be useful */
1318 if (strlen(extension) < 3) {
1319 ast_debug(4, "Skipping '%s/%s' because it doesn't have at least a two "
1320 "character extension\n", directory, filename);
1321 return 0;
1322 }
1323
1324 /* Build the full path (excluding the extension) */
1325 if (ast_asprintf(&full_path, "%s/%.*s",
1326 directory,
1327 (int) (extension - filename), filename) < 0) {
1328 /* If we don't have enough memory to build this path, there is no
1329 * point in continuing */
1330 return 1;
1331 }
1332
1333 /* If the file is present in multiple formats, ensure we only put it
1334 * into the list once. Pretty sure this is O(n^2). */
1335 if (AST_VECTOR_GET_CMP(files, &full_path[0], !strcmp)) {
1336 ast_free(full_path);
1337 return 0;
1338 }
1339
1340 if (AST_VECTOR_APPEND(files, full_path)) {
1341 /* AST_VECTOR_APPEND() can only fail on allocation failure, so
1342 * we stop iterating */
1343 ast_free(full_path);
1344 return 1;
1345 }
1346
1347 return 0;
1348 }
1349
1350 static int moh_filename_strcasecmp(const void *a, const void *b)
1351 {
1352 const char **s1 = (const char **) a;
1353 const char **s2 = (const char **) b;
1354 return strcasecmp(*s1, *s2);
1355 }
1356
1357 static int moh_scan_files(struct mohclass *class) {
1358
1359 char dir_path[PATH_MAX - sizeof(class->dir)];
1360 struct ast_vector_string *files;
1361
1362 if (class->dir[0] != '/') {
1363 snprintf(dir_path, sizeof(dir_path), "%s/%s", ast_config_AST_DATA_DIR, class->dir);
1364 } else {
1365 ast_copy_string(dir_path, class->dir, sizeof(dir_path));
1366 }
1367
1368 ast_debug(4, "Scanning '%s' for files for class '%s'\n", dir_path, class->name);
1369
1370 /* 16 seems like a reasonable default */
1371 files = moh_file_vector_alloc(16);
1372 if (!files) {
1373 return -1;
1374 }
1375
1376 if (ast_file_read_dir(dir_path, on_moh_file, files)) {
1377 ao2_ref(files, -1);
1378 return -1;
1379 }
1380
1381 if (ast_test_flag(class, MOH_SORTALPHA)) {
1382 AST_VECTOR_SORT(files, moh_filename_strcasecmp);
1383 }
1384
1385 AST_VECTOR_COMPACT(files);
1386
1387 ao2_lock(class);
1388 ao2_ref(class->files, -1);
1389 class->files = files;
1390 ao2_unlock(class);
1391
1392 return AST_VECTOR_SIZE(files);
1393 }
1394
1395 static int init_files_class(struct mohclass *class)
1396 {
1397 int res;
1398
1399 res = moh_scan_files(class);
1400
1401 if (res < 0) {
1402 return -1;
1403 }
1404
1405 if (!res) {
1406 ast_verb(3, "Files not found in %s for moh class:%s\n",
1407 class->dir, class->name);
1408 return -1;
1409 }
1410
1411 return 0;
1412 }
1413
1414 static void moh_rescan_files(void) {
1415 struct ao2_iterator i;
1416 struct mohclass *c;
1417
1418 i = ao2_iterator_init(mohclasses, 0);
1419
1420 while ((c = ao2_iterator_next(&i))) {
1421 if (!strcasecmp(c->mode, "files")) {
1422 moh_scan_files(c);
1423 }
1424 ao2_ref(c, -1);
1425 }
1426
1427 ao2_iterator_destroy(&i);
1428 }
1429
1430 static int moh_diff(struct mohclass *old, struct mohclass *new)
1431 {
1432 if (!old || !new) {
1433 return -1;
1434 }
1435
1436 if (strcmp(old->dir, new->dir)) {
1437 return -1;
1438 } else if (strcmp(old->mode, new->mode)) {
1439 return -1;
1440 } else if (strcmp(old->args, new->args)) {
1441 return -1;
1442 } else if (old->flags != new->flags) {
1443 return -1;
1444 }
1445
1446 return 0;
1447 }
1448
1449 static int init_app_class(struct mohclass *class)
1450 {
1451 if (!strcasecmp(class->mode, "custom")) {
1452 ast_set_flag(class, MOH_CUSTOM);
1453 } else if (!strcasecmp(class->mode, "mp3nb")) {
1454 ast_set_flag(class, MOH_SINGLE);
1455 } else if (!strcasecmp(class->mode, "quietmp3nb")) {
1456 ast_set_flag(class, MOH_SINGLE | MOH_QUIET);
1457 } else if (!strcasecmp(class->mode, "quietmp3")) {
1458 ast_set_flag(class, MOH_QUIET);
1459 }
1460
1461 class->srcfd = -1;
1462
1463 if (!(class->timer = ast_timer_open())) {
1464 ast_log(LOG_WARNING, "Unable to create timer: %s\n", strerror(errno));
1465 return -1;
1466 }
1467 if (class->timer && ast_timer_set_rate(class->timer, 25)) {
1468 ast_log(LOG_WARNING, "Unable to set 40ms frame rate: %s\n", strerror(errno));
1469 ast_timer_close(class->timer);
1470 class->timer = NULL;
1471 }
1472
1473 if (ast_pthread_create_background(&class->thread, NULL, monmp3thread, class)) {
1474 ast_log(LOG_WARNING, "Unable to create moh thread...\n");
1475 if (class->timer) {
1476 ast_timer_close(class->timer);
1477 class->timer = NULL;
1478 }
1479 return -1;
1480 }
1481
1482 return 0;
1483 }
1484
1485 /*!
1486 * \note This function owns the reference it gets to moh if unref is true
1487 */
1488 #define moh_register(moh, reload, unref) _moh_register(moh, reload, unref, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1489 static int _moh_register(struct mohclass *moh, int reload, int unref, const char *file, int line, const char *funcname)
1490 {
1491 struct mohclass *mohclass = NULL;
1492
1493 mohclass = _get_mohbyname(moh->name, 0, MOH_NOTDELETED, file, line, funcname);
1494
1495 if (mohclass && !moh_diff(mohclass, moh)) {
1496 ast_log(LOG_WARNING, "Music on Hold class '%s' already exists\n", moh->name);
1497 mohclass = mohclass_unref(mohclass, "unreffing mohclass we just found by name");
1498 if (unref) {
1499 moh = mohclass_unref(moh, "unreffing potential new moh class (it is a duplicate)");
1500 }
1501 return -1;
1502 } else if (mohclass) {
1503 /* Found a class, but it's different from the one being registered */
1504 mohclass = mohclass_unref(mohclass, "unreffing mohclass we just found by name");
1505 }
1506
1507 time(&moh->start);
1508 moh->start -= respawn_time;
1509
1510 if (!strcasecmp(moh->mode, "files")) {
1511 if (init_files_class(moh)) {
1512 if (unref) {
1513 moh = mohclass_unref(moh, "unreffing potential new moh class (init_files_class failed)");
1514 }
1515 return -1;
1516 }
1517 } else if (!strcasecmp(moh->mode, "playlist")) {
1518 size_t file_count;
1519
1520 ao2_lock(moh);
1521 file_count = AST_VECTOR_SIZE(moh->files);
1522 ao2_unlock(moh);
1523
1524 if (!file_count) {
1525 if (unref) {
1526 moh = mohclass_unref(moh, "unreffing potential new moh class (no playlist entries)");
1527 }
1528 return -1;
1529 }
1530 } else if (!strcasecmp(moh->mode, "mp3") || !strcasecmp(moh->mode, "mp3nb") ||
1531 !strcasecmp(moh->mode, "quietmp3") || !strcasecmp(moh->mode, "quietmp3nb") ||
1532 !strcasecmp(moh->mode, "httpmp3") || !strcasecmp(moh->mode, "custom")) {
1533 if (init_app_class(moh)) {
1534 if (unref) {
1535 moh = mohclass_unref(moh, "unreffing potential new moh class (init_app_class_failed)");
1536 }
1537 return -1;
1538 }
1539 } else {
1540 ast_log(LOG_WARNING, "Don't know how to do a mode '%s' music on hold\n", moh->mode);
1541 if (unref) {
1542 moh = mohclass_unref(moh, "unreffing potential new moh class (unknown mode)");
1543 }
1544 return -1;
1545 }
1546
1547 ao2_t_link(mohclasses, moh, "Adding class to container");
1548
1549 if (unref) {
1550 moh = mohclass_unref(moh, "Unreffing new moh class because we just added it to the container");
1551 }
1552
1553 return 0;
1554 }
1555
1556 #define moh_unregister(a) _moh_unregister(a,__FILE__,__LINE__,__PRETTY_FUNCTION__)
1557 static int _moh_unregister(struct mohclass *moh, const char *file, int line, const char *funcname)
1558 {
1559 ao2_t_unlink(mohclasses, moh, "Removing class from container");
1560 return 0;
1561 }
1562
1563 /*
1564 * Called with `chan` UNLOCKED.
1565 */
1566 static void local_ast_moh_cleanup(struct ast_channel *chan)
1567 {
1568 struct moh_files_state *state;
1569
1570 ast_channel_lock(chan);
1571 state = ast_channel_music_state(chan);
1572 if (state) {
1573 ast_channel_music_state_set(chan, NULL);
1574 if (state->class) {
1575 /* This should never happen. We likely just leaked some resource. */
1576 state->class =
1577 mohclass_unref(state->class, "Uh Oh. Cleaning up MOH with an active class");
1578 ast_log(LOG_WARNING, "Uh Oh. Cleaning up MOH with an active class\n");
1579 }
1580 ao2_cleanup(state->origwfmt);
1581 ao2_cleanup(state->mohwfmt);
1582 ast_free(state);
1583 /* Only held a module reference if we had a music state */
1584 ast_module_unref(ast_module_info->self);
1585 }
1586 ast_channel_unlock(chan);
1587 }
1588
1589 /*! \brief Support routing for 'moh unregister class' CLI
1590 * This is in charge of generating all strings that match a prefix in the
1591 * given position. As many functions of this kind, each invokation has
1592 * O(state) time complexity so be careful in using it.
1593 */
1594 static char *complete_mohclass_realtime(const char *line, const char *word, int pos, int state)
1595 {
1596 int which=0;
1597 struct mohclass *cur;
1598 char *c = NULL;
1599 int wordlen = strlen(word);
1600 struct ao2_iterator i;
1601
1602 if (pos != 3) {
1603 return NULL;
1604 }
1605
1606 i = ao2_iterator_init(mohclasses, 0);
1607 while ((cur = ao2_t_iterator_next(&i, "iterate thru mohclasses"))) {
1608 if (cur->realtime && !strncasecmp(cur->name, word, wordlen) && ++which > state) {
1609 c = ast_strdup(cur->name);
1610 mohclass_unref(cur, "drop ref in iterator loop break");
1611 break;
1612 }
1613 mohclass_unref(cur, "drop ref in iterator loop");
1614 }
1615 ao2_iterator_destroy(&i);
1616
1617 return c;
1618 }
1619
1620 static char *handle_cli_moh_unregister_class(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1621 {
1622 struct mohclass *cur;
1623 int len;
1624 int found = 0;
1625 struct ao2_iterator i;
1626
1627 switch (cmd) {
1628 case CLI_INIT:
1629 e->command = "moh unregister class";
1630 e->usage =
1631 "Usage: moh unregister class <class>\n"
1632 " Unregisters a realtime moh class.\n";
1633 return NULL;
1634 case CLI_GENERATE:
1635 return complete_mohclass_realtime(a->line, a->word, a->pos, a->n);
1636 }
1637
1638 if (a->argc != 4)
1639 return CLI_SHOWUSAGE;
1640
1641 len = strlen(a->argv[3]);
1642
1643 i = ao2_iterator_init(mohclasses, 0);
1644 while ((cur = ao2_t_iterator_next(&i, "iterate thru mohclasses"))) {
1645 if (cur->realtime && len == strlen(cur->name) && !strncasecmp(cur->name, a->argv[3], len)) {
1646 found = 1;
1647 break;
1648 }
1649 mohclass_unref(cur, "drop ref in iterator loop");
1650 }
1651 ao2_iterator_destroy(&i);
1652
1653 if (found) {
1654 moh_unregister(cur);
1655 mohclass_unref(cur, "drop ref after unregister");
1656 } else {
1657 ast_cli(a->fd, "No such realtime moh class '%s'\n", a->argv[3]);
1658 }
1659
1660 return CLI_SUCCESS;
1661 }
1662
1663
1664
1665 static void moh_class_destructor(void *obj);
1666
1667 #define moh_class_malloc() _moh_class_malloc(__FILE__,__LINE__,__PRETTY_FUNCTION__)
1668
1669 static struct mohclass *_moh_class_malloc(const char *file, int line, const char *funcname)
1670 {
1671 struct mohclass *class;
1672
1673 class = __ao2_alloc(sizeof(*class), moh_class_destructor, AO2_ALLOC_OPT_LOCK_MUTEX,
1674 "Allocating new moh class", file, line, funcname);
1675 if (class) {
1676 class->format = ao2_bump(ast_format_slin);
1677 class->srcfd = -1;
1678 class->kill_delay = 100000;
1679
1680 /* We create an empty one by default */
1681 class->files = moh_file_vector_alloc(0);
1682 if (!class->files) {
1683 ao2_ref(class, -1);
1684 return NULL;
1685 }
1686 }
1687
1688 return class;
1689 }
1690
1691 static struct ast_variable *load_realtime_musiconhold(const char *name)
1692 {
1693 struct ast_variable *var = ast_load_realtime("musiconhold", "name", name, SENTINEL);
1694
1695 if (var) {
1696 const char *mode = ast_variable_find_in_list(var, "mode");
1697 if (ast_strings_equal(mode, "playlist")) {
1698 struct ast_config *entries = ast_load_realtime_multientry("musiconhold_entry", "position >=", "0", "name", name, SENTINEL);
1699 char *category = NULL;
1700 size_t entry_count = 0;
1701
1702 /* entries is NULL if there are no results */
1703 if (entries) {
1704 while ((category = ast_category_browse(entries, category))) {
1705 const char *entry = ast_variable_retrieve(entries, category, "entry");
1706
1707 if (entry) {
1708 struct ast_variable *dup = ast_variable_new("entry", entry, "");
1709 if (dup) {
1710 entry_count++;
1711 ast_variable_list_append(&var, dup);
1712 }
1713 }
1714 }
1715 ast_config_destroy(entries);
1716 }
1717
1718 if (entry_count == 0) {
1719 /* Behave as though this class doesn't exist */
1720 ast_variables_destroy(var);
1721 var = NULL;
1722 }
1723 }
1724 }
1725
1726 if (!var) {
1727 ast_log(LOG_WARNING,
1728 "Music on Hold class '%s' not found in memory/database. "
1729 "Verify your configuration.\n",
1730 name);
1731 }
1732 return var;
1733 }
1734
1735 /*
1736 * Called with `chan` UNLOCKED.
1737 */
1738 static int local_ast_moh_start(struct ast_channel *chan, const char *mclass, const char *interpclass)
1739 {
1740 struct mohclass *mohclass = NULL;
1741 struct moh_files_state *state;
1742 struct ast_variable *var = NULL;
1743 int res = 0;
1744 int i;
1745 int realtime_possible = ast_check_realtime("musiconhold");
1746 int warn_if_not_in_memory = !realtime_possible;
1747 const char *classes[] = {NULL, NULL, interpclass, "default"};
1748
1749 if (ast_test_flag(global_flags, MOH_PREFERCHANNELCLASS)) {
1750 classes[0] = ast_channel_musicclass(chan);
1751 classes[1] = mclass;
1752 } else {
1753 classes[0] = mclass;
1754 classes[1] = ast_channel_musicclass(chan);
1755 }
1756
1757 /* The following is the order of preference for which class to use:
1758 * 1) The channels explicitly set musicclass, which should *only* be
1759 * set by a call to Set(CHANNEL(musicclass)=whatever) in the dialplan.
1760 * Unless preferchannelclass in musiconhold.conf is false
1761 * 2) The mclass argument. If a channel is calling ast_moh_start() as the
1762 * result of receiving a HOLD control frame, this should be the
1763 * payload that came with the frame.
1764 * 3) The channels explicitly set musicclass, which should *only* be
1765 * set by a call to Set(CHANNEL(musicclass)=whatever) in the dialplan.
1766 * 4) The interpclass argument. This would be from the mohinterpret
1767 * option from channel drivers. This is the same as the old musicclass
1768 * option.
1769 * 5) The default class.
1770 */
1771
1772 for (i = 0; i < ARRAY_LEN(classes); ++i) {
1773 if (!ast_strlen_zero(classes[i])) {
1774 mohclass = get_mohbyname(classes[i], warn_if_not_in_memory, 0);
1775 if (!mohclass && realtime_possible) {
1776 var = load_realtime_musiconhold(classes[i]);
1777 }
1778 if (mohclass || var) {
1779 break;
1780 }
1781 }
1782 }
1783
1784 /* If no moh class found in memory, then check RT. Note that the logic used
1785 * above guarantees that if var is non-NULL, then mohclass must be NULL.
1786 */
1787 if (var) {
1788 if ((mohclass = moh_class_malloc())) {
1789 mohclass->realtime = 1;
1790
1791 moh_parse_options(var, mohclass);
1792 ast_variables_destroy(var);
1793
1794 if (ast_strlen_zero(mohclass->dir)) {
1795 if (!strcasecmp(mohclass->mode, "custom") || !strcasecmp(mohclass->mode, "playlist")) {
1796 strcpy(mohclass->dir, "nodir");
1797 } else {
1798 ast_log(LOG_WARNING, "A directory must be specified for class '%s'!\n", mohclass->name);
1799 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no directory specified)");
1800 return -1;
1801 }
1802 }
1803 if (ast_strlen_zero(mohclass->mode)) {
1804 ast_log(LOG_WARNING, "A mode must be specified for class '%s'!\n", mohclass->name);
1805 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no mode specified)");
1806 return -1;
1807 }
1808 if (ast_strlen_zero(mohclass->args) && !strcasecmp(mohclass->mode, "custom")) {
1809 ast_log(LOG_WARNING, "An application must be specified for class '%s'!\n", mohclass->name);
1810 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no app specified for custom mode");
1811 return -1;
1812 }
1813
1814 if (ast_test_flag(global_flags, MOH_CACHERTCLASSES)) {
1815 /* CACHERTCLASSES enabled, let's add this class to default tree */
1816 ast_channel_lock(chan);
1817 state = ast_channel_music_state(chan);
1818 if (state && state->class) {
1819 /* Class already exist for this channel */
1820 ast_log(LOG_NOTICE, "This channel already has a MOH class attached (%s)!\n", state->class->name);
1821 }
1822 ast_channel_unlock(chan);
1823 /* We don't want moh_register to unref the mohclass because we do it at the end of this function as well.
1824 * If we allowed moh_register to unref the mohclass,too, then the count would be off by one. The result would
1825 * be that the destructor would be called when the generator on the channel is deactivated. The container then
1826 * has a pointer to a freed mohclass, so any operations involving the mohclass container would result in reading
1827 * invalid memory.
1828 */
1829 if (moh_register(mohclass, 0, DONT_UNREF) == -1) {
1830 mohclass = mohclass_unref(mohclass, "unreffing mohclass failed to register");
1831 return -1;
1832 }
1833 } else {
1834 /* We don't register RT moh class, so let's init it manually */
1835
1836 time(&mohclass->start);
1837 mohclass->start -= respawn_time;
1838
1839 if (!strcasecmp(mohclass->mode, "files")) {
1840 /*
1841 * XXX moh_scan_files returns -1 if it is unable to open the
1842 * configured directory or there is a memory allocation
1843 * failure. Otherwise it returns the number of files for this music
1844 * class. This check is only checking if the number of files is zero
1845 * and it ignores the -1 case. To avoid a behavior change we keep this
1846 * as-is, but we should address what the 'correct' behavior should be.
1847 */
1848 if (!moh_scan_files(mohclass)) {
1849 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (moh_scan_files failed)");
1850 return -1;
1851 }
1852 if (strchr(mohclass->args, 'r')) {
1853 static int deprecation_warning = 0;
1854 if (!deprecation_warning) {
1855 ast_log(LOG_WARNING, "Music on hold 'application=r' setting is deprecated in 14. Please use 'sort=random' instead.\n");
1856 deprecation_warning = 1;
1857 }
1858 ast_set_flag(mohclass, MOH_RANDOMIZE);
1859 }
1860 } else if (!strcasecmp(mohclass->mode, "playlist")) {
1861 size_t file_count;
1862
1863 ao2_lock(mohclass);
1864 file_count = AST_VECTOR_SIZE(mohclass->files);
1865 ao2_unlock(mohclass);
1866
1867 if (!file_count) {
1868 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (no playlist entries)");
1869 return -1;
1870 }
1871 } 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")) {
1872
1873 if (!strcasecmp(mohclass->mode, "custom"))
1874 ast_set_flag(mohclass, MOH_CUSTOM);
1875 else if (!strcasecmp(mohclass->mode, "mp3nb"))
1876 ast_set_flag(mohclass, MOH_SINGLE);
1877 else if (!strcasecmp(mohclass->mode, "quietmp3nb"))
1878 ast_set_flag(mohclass, MOH_SINGLE | MOH_QUIET);
1879 else if (!strcasecmp(mohclass->mode, "quietmp3"))
1880 ast_set_flag(mohclass, MOH_QUIET);
1881
1882 mohclass->srcfd = -1;
1883 if (!(mohclass->timer = ast_timer_open())) {
1884 ast_log(LOG_WARNING, "Unable to create timer: %s\n", strerror(errno));
1885 }
1886 if (mohclass->timer && ast_timer_set_rate(mohclass->timer, 25)) {
1887 ast_log(LOG_WARNING, "Unable to set 40ms frame rate: %s\n", strerror(errno));
1888 ast_timer_close(mohclass->timer);
1889 mohclass->timer = NULL;
1890 }
1891
1892 /* Let's check if this channel already had a moh class before */
1893 ast_channel_lock(chan);
1894 state = ast_channel_music_state(chan);
1895 if (state && state->class) {
1896 /* Class already exist for this channel */
1897 ast_log(LOG_NOTICE, "This channel already has a MOH class attached (%s)!\n", state->class->name);
1898 if (state->class->realtime && !ast_test_flag(global_flags, MOH_CACHERTCLASSES) && !strcasecmp(mohclass->name, state->class->name)) {
1899 /* we found RT class with the same name, seems like we should continue playing existing one */
1900 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (channel already has one)");
1901 mohclass = mohclass_ref(state->class, "using existing class from state");
1902 }
1903 ast_channel_unlock(chan);
1904 } else {
1905 ast_channel_unlock(chan);
1906 if (ast_pthread_create_background(&mohclass->thread, NULL, monmp3thread, mohclass)) {
1907 ast_log(LOG_WARNING, "Unable to create moh...\n");
1908 if (mohclass->timer) {
1909 ast_timer_close(mohclass->timer);
1910 mohclass->timer = NULL;
1911 }
1912 mohclass = mohclass_unref(mohclass, "Unreffing potential mohclass (failed to create background thread)");
1913 return -1;
1914 }
1915 }
1916 } else {
1917 ast_log(LOG_WARNING, "Don't know how to do a mode '%s' music on hold\n", mohclass->mode);
1918 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (unknown mode)");
1919 return -1;
1920 }
1921 }
1922 } else {
1923 ast_variables_destroy(var);
1924 var = NULL;
1925 }
1926 }
1927
1928 if (!mohclass) {
1929 return -1;
1930 }
1931
1932 if (mohclass->answeredonly && (ast_channel_state(chan) != AST_STATE_UP)) {
1933 ast_verb(3, "The channel '%s' is not answered yet. Ignore the moh request.\n", ast_channel_name(chan));
1934 return -1;
1935 }
1936
1937 /* If we are using a cached realtime class with files, re-scan the files */
1938 if (!var && ast_test_flag(global_flags, MOH_CACHERTCLASSES) && mohclass->realtime && !strcasecmp(mohclass->mode, "files")) {
1939 /*
1940 * XXX moh_scan_files returns -1 if it is unable to open the configured directory
1941 * or there is a memory allocation failure. Otherwise it returns the number of
1942 * files for this music class. This check is only checking if the number of files
1943 * is zero and it ignores the -1 case. To avoid a behavior change we keep this
1944 * as-is, but we should address what the 'correct' behavior should be.
1945 */
1946 if (!moh_scan_files(mohclass)) {
1947 mohclass = mohclass_unref(mohclass, "unreffing potential mohclass (moh_scan_files failed)");
1948 return -1;
1949 }
1950 }
1951
1952 ast_channel_lock(chan);
1953 state = ast_channel_music_state(chan);
1954 if (!state || !state->class || strcmp(mohclass->name, state->class->name)) {
1955 size_t file_count;
1956
1957 ao2_lock(mohclass);
1958 file_count = AST_VECTOR_SIZE(mohclass->files);
1959 ao2_unlock(mohclass);
1960
1961 if (file_count) {
1962 res = ast_activate_generator(chan, &moh_file_stream, mohclass);
1963 } else {
1964 res = ast_activate_generator(chan, &mohgen, mohclass);
1965 }
1966 }
1967 ast_channel_unlock(chan);
1968 if (!res) {
1969 ast_channel_lock(chan);
1970 ast_channel_latest_musicclass_set(chan, mohclass->name);
1971 ast_set_flag(ast_channel_flags(chan), AST_FLAG_MOH);
1972 ast_channel_unlock(chan);
1973 }
1974
1975 mohclass = mohclass_unref(mohclass, "unreffing local reference to mohclass in local_ast_moh_start");
1976
1977 return res;
1978 }
1979
1980 /*
1981 * Called with `chan` UNLOCKED.
1982 */
1983 static void local_ast_moh_stop(struct ast_channel *chan)
1984 {
1985 ast_deactivate_generator(chan);
1986
1987 ast_channel_lock(chan);
1988 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_MOH);
1989 if (ast_channel_music_state(chan)) {
1990 if (ast_channel_stream(chan)) {
1991 ast_closestream(ast_channel_stream(chan));
1992 ast_channel_stream_set(chan, NULL);
1993 }
1994 }
1995 ast_channel_unlock(chan);
1996 }
1997
1998 static void moh_class_destructor(void *obj)
1999 {
2000 struct mohclass *class = obj;
2001 struct mohdata *member;
2002 pthread_t tid = 0;
2003
2004 ast_debug(1, "Destroying MOH class '%s'\n", class->name);
2005
2006 ao2_lock(class);
2007 while ((member = AST_LIST_REMOVE_HEAD(&class->members, list))) {
2008 ast_free(member);
2009 }
2010 ao2_cleanup(class->files);
2011 ao2_unlock(class);
2012
2013 /* Kill the thread first, so it cannot restart the child process while the
2014 * class is being destroyed */
2015 if (class->thread != AST_PTHREADT_NULL && class->thread != 0) {
2016 tid = class->thread;
2017 class->thread = AST_PTHREADT_NULL;
2018 pthread_cancel(tid);
2019 /* We'll collect the exit status later, after we ensure all the readers
2020 * are dead. */
2021 }
2022
2023 if (class->pid > 1) {
2024 char buff[8192];
2025 int bytes, tbytes = 0, stime = 0;
2026
2027 ast_debug(1, "killing %d!\n", class->pid);
2028
2029 stime = time(NULL) + 2;
2030 killpid(class->pid, class->kill_delay, class->kill_method);
2031
2032 while ((ast_wait_for_input(class->srcfd, 100) > 0) &&
2033 (bytes = read(class->srcfd, buff, 8192)) && time(NULL) < stime) {
2034 tbytes = tbytes + bytes;
2035 }
2036
2037 ast_debug(1, "mpg123 pid %d and child died after %d bytes read\n",
2038 class->pid, tbytes);
2039
2040 class->pid = 0;
2041 close(class->srcfd);
2042 class->srcfd = -1;
2043 }
2044
2045 if (class->timer) {
2046 ast_timer_close(class->timer);
2047 class->timer = NULL;
2048 }
2049
2050 ao2_cleanup(class->format);
2051
2052 /* Finally, collect the exit status of the monitor thread */
2053 if (tid > 0) {
2054 pthread_join(tid, NULL);
2055 }
2056
2057 }
2058
2059 static int moh_class_mark(void *obj, void *arg, int flags)
2060 {
2061 struct mohclass *class = obj;
2062
2063 if ( ((flags & MOH_REALTIME) && class->realtime) || !(flags & MOH_REALTIME) ) {
2064 class->delete = 1;
2065 }
2066
2067 return 0;
2068 }
2069
2070 static int moh_classes_delete_marked(void *obj, void *arg, int flags)
2071 {
2072 struct mohclass *class = obj;
2073
2074 return class->delete ? CMP_MATCH : 0;
2075 }
2076
2077 static int load_moh_classes(int reload)
2078 {
2079 struct ast_config *cfg;
2080 struct ast_variable *var;
2081 struct mohclass *class;
2082 char *cat;
2083 int numclasses = 0;
2084 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2085
2086 cfg = ast_config_load("musiconhold.conf", config_flags);
2087
2088 if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
2089 if (ast_check_realtime("musiconhold") && reload) {
2090 ao2_t_callback(mohclasses, OBJ_NODATA | MOH_REALTIME, moh_class_mark, NULL, "Mark realtime classes for deletion");
2091 ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, moh_classes_delete_marked, NULL, "Purge marked classes");
2092 }
2093 moh_rescan_files();
2094 return 0;
2095 }
2096
2097 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEINVALID) {
2098 if (ast_check_realtime("musiconhold") && reload) {
2099 ao2_t_callback(mohclasses, OBJ_NODATA, moh_class_mark, NULL, "Mark deleted classes");
2100 ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, moh_classes_delete_marked, NULL, "Purge marked classes");
2101 }
2102 return 0;
2103 }
2104
2105 if (reload) {
2106 ao2_t_callback(mohclasses, OBJ_NODATA, moh_class_mark, NULL, "Mark deleted classes");
2107 }
2108
2109 ast_clear_flag(global_flags, AST_FLAGS_ALL);
2110 ast_set2_flag(global_flags, 1, MOH_PREFERCHANNELCLASS);
2111
2112 cat = ast_category_browse(cfg, NULL);
2113 for (; cat; cat = ast_category_browse(cfg, cat)) {
2114 /* Setup common options from [general] section */
2115 if (!strcasecmp(cat, "general")) {
2116 for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
2117 if (!strcasecmp(var->name, "cachertclasses")) {
2118 ast_set2_flag(global_flags, ast_true(var->value), MOH_CACHERTCLASSES);
2119 } else if (!strcasecmp(var->name, "preferchannelclass")) {
2120 ast_set2_flag(global_flags, ast_true(var->value), MOH_PREFERCHANNELCLASS);
2121 } else {
2122 ast_log(LOG_WARNING, "Unknown option '%s' in [general] section of musiconhold.conf\n", var->name);
2123 }
2124 }
2125 continue;
2126 }
2127
2128 if (!(class = moh_class_malloc())) {
2129 break;
2130 }
2131
2132 moh_parse_options(ast_variable_browse(cfg, cat), class);
2133 /* For compatibility with the past, we overwrite any name=name
2134 * with the context [name]. */
2135 ast_copy_string(class->name, cat, sizeof(class->name));
2136
2137 if (ast_strlen_zero(class->dir)) {
2138 if (!strcasecmp(class->mode, "custom") || !strcasecmp(class->mode, "playlist")) {
2139 strcpy(class->dir, "nodir");
2140 } else {
2141 ast_log(LOG_WARNING, "A directory must be specified for class '%s'!\n", class->name);
2142 class = mohclass_unref(class, "unreffing potential mohclass (no directory)");
2143 continue;
2144 }
2145 }
2146 if (ast_strlen_zero(class->mode)) {
2147 ast_log(LOG_WARNING, "A mode must be specified for class '%s'!\n", class->name);
2148 class = mohclass_unref(class, "unreffing potential mohclass (no mode)");
2149 continue;
2150 }
2151 if (ast_strlen_zero(class->args) && !strcasecmp(class->mode, "custom")) {
2152 ast_log(LOG_WARNING, "An application must be specified for class '%s'!\n", class->name);
2153 class = mohclass_unref(class, "unreffing potential mohclass (no app for custom mode)");
2154 continue;
2155 }
2156
2157 /* Don't leak a class when it's already registered */
2158 if (!moh_register(class, reload, HANDLE_REF)) {
2159 numclasses++;
2160 }
2161 }
2162
2163 ast_config_destroy(cfg);
2164
2165 ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
2166 moh_classes_delete_marked, NULL, "Purge marked classes");
2167
2168 return numclasses;
2169 }
2170
2171 static void ast_moh_destroy(void)
2172 {
2173 ast_verb(2, "Destroying musiconhold processes\n");
2174 if (mohclasses) {
2175 ao2_t_callback(mohclasses, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "Destroy callback");
2176 ao2_ref(mohclasses, -1);
2177 mohclasses = NULL;
2178 }
2179 }
2180
2181 static char *handle_cli_moh_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2182 {
2183 switch (cmd) {
2184 case CLI_INIT:
2185 e->command = "moh reload";
2186 e->usage =
2187 "Usage: moh reload\n"
2188 " Reloads the MusicOnHold module.\n"
2189 " Alias for 'module reload res_musiconhold.so'\n";
2190 return NULL;
2191 case CLI_GENERATE:
2192 return NULL;
2193 }
2194
2195 if (a->argc != e->args)
2196 return CLI_SHOWUSAGE;
2197
2198 /* The module loader will prevent concurrent reloads from occurring, so we delegate */
2199 ast_module_reload("res_musiconhold");
2200
2201 return CLI_SUCCESS;
2202 }
2203
2204 static char *handle_cli_moh_show_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2205 {
2206 struct mohclass *class;
2207 struct ao2_iterator i;
2208
2209 switch (cmd) {
2210 case CLI_INIT:
2211 e->command = "moh show files";
2212 e->usage =
2213 "Usage: moh show files\n"
2214 " Lists all loaded file-based MusicOnHold classes and their\n"
2215 " files.\n";
2216 return NULL;
2217 case CLI_GENERATE:
2218 return NULL;
2219 }
2220
2221 if (a->argc != e->args)
2222 return CLI_SHOWUSAGE;
2223
2224 i = ao2_iterator_init(mohclasses, 0);
2225 for (; (class = ao2_t_iterator_next(&i, "Show files iterator")); mohclass_unref(class, "Unref iterator in moh show files")) {
2226 struct ast_vector_string *files;
2227
2228 ao2_lock(class);
2229 files = ao2_bump(class->files);
2230 ao2_unlock(class);
2231
2232 if (AST_VECTOR_SIZE(files)) {
2233 int x;
2234 ast_cli(a->fd, "Class: %s\n", class->name);
2235 for (x = 0; x < AST_VECTOR_SIZE(files); x++) {
2236 ast_cli(a->fd, "\tFile: %s\n", AST_VECTOR_GET(files, x));
2237 }
2238 }
2239
2240 ao2_ref(files, -1);
2241 }
2242 ao2_iterator_destroy(&i);
2243
2244 return CLI_SUCCESS;
2245 }
2246
2247 static char *handle_cli_moh_show_classes(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2248 {
2249 struct mohclass *class;
2250 struct ao2_iterator i;
2251
2252 switch (cmd) {
2253 case CLI_INIT:
2254 e->command = "moh show classes";
2255 e->usage =
2256 "Usage: moh show classes\n"
2257 " Lists all MusicOnHold classes.\n";
2258 return NULL;
2259 case CLI_GENERATE:
2260 return NULL;
2261 }
2262
2263 if (a->argc != e->args)
2264 return CLI_SHOWUSAGE;
2265
2266 i = ao2_iterator_init(mohclasses, 0);
2267 for (; (class = ao2_t_iterator_next(&i, "Show classes iterator")); mohclass_unref(class, "Unref iterator in moh show classes")) {
2268 ast_cli(a->fd, "Class: %s\n", class->name);
2269 ast_cli(a->fd, "\tMode: %s\n", S_OR(class->mode, "<none>"));
2270 ast_cli(a->fd, "\tDirectory: %s\n", S_OR(class->dir, "<none>"));
2271 if (ast_test_flag(class, MOH_ANNOUNCEMENT)) {
2272 ast_cli(a->fd, "\tAnnouncement: %s\n", S_OR(class->announcement, "<none>"));
2273 }
2274 if (ast_test_flag(class, MOH_CUSTOM)) {
2275 ast_cli(a->fd, "\tApplication: %s\n", S_OR(class->args, "<none>"));
2276 ast_cli(a->fd, "\tKill Escalation Delay: %zu ms\n", class->kill_delay / 1000);
2277 ast_cli(a->fd, "\tKill Method: %s\n",
2278 class->kill_method == KILL_METHOD_PROCESS ? "process" : "process_group");
2279 }
2280 if (strcasecmp(class->mode, "files")) {
2281 ast_cli(a->fd, "\tFormat: %s\n", ast_format_get_name(class->format));
2282 }
2283 }
2284 ao2_iterator_destroy(&i);
2285
2286 return CLI_SUCCESS;
2287 }
2288
2289 static struct ast_cli_entry cli_moh[] = {
2290 AST_CLI_DEFINE(handle_cli_moh_reload, "Reload MusicOnHold"),
2291 AST_CLI_DEFINE(handle_cli_moh_show_classes, "List MusicOnHold classes"),
2292 AST_CLI_DEFINE(handle_cli_moh_show_files, "List MusicOnHold file-based classes"),
2293 AST_CLI_DEFINE(handle_cli_moh_unregister_class, "Unregister realtime MusicOnHold class")
2294 };
2295
2296 static int moh_class_hash(const void *obj, const int flags)
2297 {
2298 const struct mohclass *class = obj;
2299
2300 return ast_str_case_hash(class->name);
2301 }
2302
2303 static int moh_class_cmp(void *obj, void *arg, int flags)
2304 {
2305 struct mohclass *class = obj, *class2 = arg;
2306
2307 return strcasecmp(class->name, class2->name) ? 0 :
2308 (flags & MOH_NOTDELETED) && (class->delete || class2->delete) ? 0 :
2309 CMP_MATCH | CMP_STOP;
2310 }
2311
2312 /*!
2313 * \brief Load the module
2314 *
2315 * Module loading including tests for configuration or dependencies.
2316 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
2317 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
2318 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
2319 * configuration file or other non-critical problem return
2320 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
2321 */
2322 static int load_module(void)
2323 {
2324 int res;
2325
2326 mohclasses = ao2_t_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 53,
2327 moh_class_hash, NULL, moh_class_cmp, "Moh class container");
2328 if (!mohclasses) {
2329 return AST_MODULE_LOAD_DECLINE;
2330 }
2331
2332 if (!load_moh_classes(0) && ast_check_realtime("musiconhold") == 0) { /* No music classes configured, so skip it */
2333 ast_log(LOG_WARNING, "No music on hold classes configured, "
2334 "disabling music on hold.\n");
2335 } else {
2336 ast_install_music_functions(local_ast_moh_start, local_ast_moh_stop,
2337 local_ast_moh_cleanup);
2338 }
2339
2340 res = ast_register_application_xml(play_moh, play_moh_exec);
2341 ast_register_atexit(ast_moh_destroy);
2342 ast_cli_register_multiple(cli_moh, ARRAY_LEN(cli_moh));
2343 if (!res)
2344 res = ast_register_application_xml(start_moh, start_moh_exec);
2345 if (!res)
2346 res = ast_register_application_xml(stop_moh, stop_moh_exec);
2347
2348 return AST_MODULE_LOAD_SUCCESS;
2349 }
2350
2351 static int reload(void)
2352 {
2353 if (load_moh_classes(1)) {
2354 ast_install_music_functions(local_ast_moh_start, local_ast_moh_stop,
2355 local_ast_moh_cleanup);
2356 }
2357
2358 return AST_MODULE_LOAD_SUCCESS;
2359 }
2360
2361 static int moh_class_inuse(void *obj, void *arg, int flags)
2362 {
2363 struct mohclass *class = obj;
2364
2365 return AST_LIST_EMPTY(&class->members) ? 0 : CMP_MATCH | CMP_STOP;
2366 }
2367
2368 static int unload_module(void)
2369 {
2370 int res = 0;
2371 struct mohclass *class = NULL;
2372
2373 /* XXX This check shouldn't be required if module ref counting was being used
2374 * properly ... */
2375 if ((class = ao2_t_callback(mohclasses, 0, moh_class_inuse, NULL, "Module unload callback"))) {
2376 class = mohclass_unref(class, "unref of class from module unload callback");
2377 res = -1;
2378 }
2379
2380 if (res < 0) {
2381 ast_log(LOG_WARNING, "Unable to unload res_musiconhold due to active MOH channels\n");
2382 return res;
2383 }
2384
2385 ast_uninstall_music_functions();
2386
2387 ast_moh_destroy();
2388 res = ast_unregister_application(play_moh);
2389 res |= ast_unregister_application(start_moh);
2390 res |= ast_unregister_application(stop_moh);
2391 ast_cli_unregister_multiple(cli_moh, ARRAY_LEN(cli_moh));
2392 ast_unregister_atexit(ast_moh_destroy);
2393
2394 return res;
2395 }
2396
2397 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Music On Hold Resource",
2398 .support_level = AST_MODULE_SUPPORT_CORE,
2399 .load = load_module,
2400 .unload = unload_module,
2401 .reload = reload,
2402 .load_pri = AST_MODPRI_CHANNEL_DEPEND,
2403 );