Remove compiler warning for uninitialized variable
[asterisk/asterisk.git] / channels / chan_console.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2006 - 2008, Digium, Inc.
5  *
6  * Russell Bryant <russell@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
19 /*! 
20  * \file 
21  * \brief Cross-platform console channel driver 
22  *
23  * \author Russell Bryant <russell@digium.com>
24  *
25  * \note Some of the code in this file came from chan_oss and chan_alsa.
26  *       chan_oss,  Mark Spencer <markster@digium.com>
27  *       chan_oss,  Luigi Rizzo
28  *       chan_alsa, Matthew Fredrickson <creslin@digium.com>
29  * 
30  * \ingroup channel_drivers
31  *
32  * \extref Portaudio http://www.portaudio.com/
33  *
34  * To install portaudio v19 from svn, check it out using the following command:
35  *  - svn co https://www.portaudio.com/repos/portaudio/branches/v19-devel
36  *
37  * \note Since this works with any audio system that libportaudio supports,
38  * including ALSA and OSS, this may someday deprecate chan_alsa and chan_oss.
39  * However, before that can be done, it needs to *at least* have all of the
40  * features that these other channel drivers have.  The features implemented
41  * in at least one of the other console channel drivers that are not yet
42  * implemented here are:
43  *
44  * - Set Auto-answer from the dialplan
45  * - transfer CLI command
46  * - boost CLI command and .conf option
47  * - console_video support
48  */
49
50 /*** MODULEINFO
51         <depend>portaudio</depend>
52  ***/
53
54 #include "asterisk.h"
55
56 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
57
58 #include <sys/signal.h>  /* SIGURG */
59
60 #include <portaudio.h>
61
62 #include "asterisk/module.h"
63 #include "asterisk/channel.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/causes.h"
66 #include "asterisk/cli.h"
67 #include "asterisk/musiconhold.h"
68 #include "asterisk/callerid.h"
69 #include "asterisk/astobj2.h"
70
71 /*! 
72  * \brief The sample rate to request from PortAudio 
73  *
74  * \todo Make this optional.  If this is only going to talk to 8 kHz endpoints,
75  *       then it makes sense to use 8 kHz natively.
76  */
77 #define SAMPLE_RATE      16000
78
79 /*! 
80  * \brief The number of samples to configure the portaudio stream for
81  *
82  * 320 samples (20 ms) is the most common frame size in Asterisk.  So, the code
83  * in this module reads 320 sample frames from the portaudio stream and queues
84  * them up on the Asterisk channel.  Frames of any size can be written to a
85  * portaudio stream, but the portaudio documentation does say that for high
86  * performance applications, the data should be written to Pa_WriteStream in
87  * the same size as what is used to initialize the stream.
88  */
89 #define NUM_SAMPLES      320
90
91 /*! \brief Mono Input */
92 #define INPUT_CHANNELS   1
93
94 /*! \brief Mono Output */
95 #define OUTPUT_CHANNELS  1
96
97 /*! 
98  * \brief Maximum text message length
99  * \note This should be changed if there is a common definition somewhere
100  *       that defines the maximum length of a text message.
101  */
102 #define TEXT_SIZE       256
103
104 #ifndef MIN
105 #define MIN(a,b) ((a) < (b) ? (a) : (b))
106 #endif
107 #ifndef MAX
108 #define MAX(a,b) ((a) > (b) ? (a) : (b))
109 #endif
110
111 /*! \brief Dance, Kirby, Dance! @{ */
112 #define V_BEGIN " --- <(\"<) --- "
113 #define V_END   " --- (>\")> ---\n"
114 /*! @} */
115
116 static const char config_file[] = "console.conf";
117
118 /*!
119  * \brief Console pvt structure
120  *
121  * Currently, this is a singleton object.  However, multiple instances will be
122  * needed when this module is updated for multiple device support.
123  */
124 static struct console_pvt {
125         AST_DECLARE_STRING_FIELDS(
126                 /*! Name of the device */
127                 AST_STRING_FIELD(name);
128                 AST_STRING_FIELD(input_device);
129                 AST_STRING_FIELD(output_device);
130                 /*! Default context for outgoing calls */
131                 AST_STRING_FIELD(context);
132                 /*! Default extension for outgoing calls */
133                 AST_STRING_FIELD(exten);
134                 /*! Default CallerID number */
135                 AST_STRING_FIELD(cid_num);
136                 /*! Default CallerID name */
137                 AST_STRING_FIELD(cid_name);
138                 /*! Default MOH class to listen to, if:
139                  *    - No MOH class set on the channel
140                  *    - Peer channel putting this device on hold did not suggest a class */
141                 AST_STRING_FIELD(mohinterpret);
142                 /*! Default language */
143                 AST_STRING_FIELD(language);
144         );
145         /*! Current channel for this device */
146         struct ast_channel *owner;
147         /*! Current PortAudio stream for this device */
148         PaStream *stream;
149         /*! A frame for preparing to queue on to the channel */
150         struct ast_frame fr;
151         /*! Running = 1, Not running = 0 */
152         unsigned int streamstate:1;
153         /*! On-hook = 0, Off-hook = 1 */
154         unsigned int hookstate:1;
155         /*! Unmuted = 0, Muted = 1 */
156         unsigned int muted:1;
157         /*! Automatically answer incoming calls */
158         unsigned int autoanswer:1;
159         /*! Ignore context in the console dial CLI command */
160         unsigned int overridecontext:1;
161         /*! Set during a reload so that we know to destroy this if it is no longer
162          *  in the configuration file. */
163         unsigned int destroy:1;
164         /*! ID for the stream monitor thread */
165         pthread_t thread;
166 } globals;
167
168 AST_MUTEX_DEFINE_STATIC(globals_lock);
169
170 static struct ao2_container *pvts;
171 #define NUM_PVT_BUCKETS 7
172
173 static struct console_pvt *active_pvt;
174 AST_RWLOCK_DEFINE_STATIC(active_lock);
175
176 /*! 
177  * \brief Global jitterbuffer configuration 
178  *
179  * \note Disabled by default.
180  */
181 static struct ast_jb_conf default_jbconf = {
182         .flags = 0,
183         .max_size = -1,
184         .resync_threshold = -1,
185         .impl = ""
186 };
187 static struct ast_jb_conf global_jbconf;
188
189 /*! Channel Technology Callbacks @{ */
190 static struct ast_channel *console_request(const char *type, int format, 
191         void *data, int *cause);
192 static int console_digit_begin(struct ast_channel *c, char digit);
193 static int console_digit_end(struct ast_channel *c, char digit, unsigned int duration);
194 static int console_text(struct ast_channel *c, const char *text);
195 static int console_hangup(struct ast_channel *c);
196 static int console_answer(struct ast_channel *c);
197 static struct ast_frame *console_read(struct ast_channel *chan);
198 static int console_call(struct ast_channel *c, char *dest, int timeout);
199 static int console_write(struct ast_channel *chan, struct ast_frame *f);
200 static int console_indicate(struct ast_channel *chan, int cond, 
201         const void *data, size_t datalen);
202 static int console_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
203 /*! @} */
204
205 /*!
206  * \brief Formats natively supported by this module.
207  */
208 #define SUPPORTED_FORMATS ( AST_FORMAT_SLINEAR16 )
209
210 static const struct ast_channel_tech console_tech = {
211         .type = "Console",
212         .description = "Console Channel Driver",
213         .capabilities = SUPPORTED_FORMATS,
214         .requester = console_request,
215         .send_digit_begin = console_digit_begin,
216         .send_digit_end = console_digit_end,
217         .send_text = console_text,
218         .hangup = console_hangup,
219         .answer = console_answer,
220         .read = console_read,
221         .call = console_call,
222         .write = console_write,
223         .indicate = console_indicate,
224         .fixup = console_fixup,
225 };
226
227 /*! \brief lock a console_pvt struct */
228 #define console_pvt_lock(pvt) ao2_lock(pvt)
229
230 /*! \brief unlock a console_pvt struct */
231 #define console_pvt_unlock(pvt) ao2_unlock(pvt)
232
233 static inline struct console_pvt *ref_pvt(struct console_pvt *pvt)
234 {
235         if (pvt)
236                 ao2_ref(pvt, +1);
237         return pvt;
238 }
239
240 static inline struct console_pvt *unref_pvt(struct console_pvt *pvt)
241 {
242         ao2_ref(pvt, -1);
243         return NULL;
244 }
245
246 static struct console_pvt *find_pvt(const char *name)
247 {
248         struct console_pvt tmp_pvt = {
249                 .name = name,
250         };
251
252         return ao2_find(pvts, &tmp_pvt, OBJ_POINTER);
253 }
254
255 /*!
256  * \brief Stream monitor thread 
257  *
258  * \arg data A pointer to the console_pvt structure that contains the portaudio
259  *      stream that needs to be monitored.
260  *
261  * This function runs in its own thread to monitor data coming in from a
262  * portaudio stream.  When enough data is available, it is queued up to
263  * be read from the Asterisk channel.
264  */
265 static void *stream_monitor(void *data)
266 {
267         struct console_pvt *pvt = data;
268         char buf[NUM_SAMPLES * sizeof(int16_t)];
269         PaError res;
270         struct ast_frame f = {
271                 .frametype = AST_FRAME_VOICE,
272                 .subclass = AST_FORMAT_SLINEAR16,
273                 .src = "console_stream_monitor",
274                 .data = buf,
275                 .datalen = sizeof(buf),
276                 .samples = sizeof(buf) / sizeof(int16_t),
277         };
278
279         for (;;) {
280                 pthread_testcancel();
281                 res = Pa_ReadStream(pvt->stream, buf, sizeof(buf) / sizeof(int16_t));
282                 pthread_testcancel();
283
284                 if (res == paNoError)
285                         ast_queue_frame(pvt->owner, &f);
286         }
287
288         return NULL;
289 }
290
291 static int open_stream(struct console_pvt *pvt)
292 {
293         int res = paInternalError;
294
295         if (!strcasecmp(pvt->input_device, "default") && 
296                 !strcasecmp(pvt->output_device, "default")) {
297                 res = Pa_OpenDefaultStream(&pvt->stream, INPUT_CHANNELS, OUTPUT_CHANNELS, 
298                         paInt16, SAMPLE_RATE, NUM_SAMPLES, NULL, NULL);
299         } else {
300                 PaStreamParameters input_params = { 
301                         .channelCount = 1,
302                         .sampleFormat = paInt16,
303                         .suggestedLatency = (1.0 / 50.0), /* 20 ms */
304                         .device = paNoDevice,
305                 };
306                 PaStreamParameters output_params = { 
307                         .channelCount = 1, 
308                         .sampleFormat = paInt16,
309                         .suggestedLatency = (1.0 / 50.0), /* 20 ms */
310                         .device = paNoDevice,
311                 };
312                 PaDeviceIndex index, num_devices, def_input, def_output;
313
314                 if (!(num_devices = Pa_GetDeviceCount()))
315                         return res;
316
317                 def_input = Pa_GetDefaultInputDevice();
318                 def_output = Pa_GetDefaultOutputDevice();
319
320                 for (index = 0; 
321                         index < num_devices && (input_params.device == paNoDevice 
322                                 || output_params.device == paNoDevice); 
323                         index++) 
324                 {
325                         const PaDeviceInfo *dev = Pa_GetDeviceInfo(index);
326
327                         if (dev->maxInputChannels) {
328                                 if ( (index == def_input && !strcasecmp(pvt->input_device, "default")) ||
329                                         !strcasecmp(pvt->input_device, dev->name) )
330                                         input_params.device = index;
331                         }
332
333                         if (dev->maxOutputChannels) {
334                                 if ( (index == def_output && !strcasecmp(pvt->output_device, "default")) ||
335                                         !strcasecmp(pvt->output_device, dev->name) )
336                                         output_params.device = index;
337                         }
338                 }
339
340                 if (input_params.device == paNoDevice)
341                         ast_log(LOG_ERROR, "No input device found for console device '%s'\n", pvt->name);
342                 if (output_params.device == paNoDevice)
343                         ast_log(LOG_ERROR, "No output device found for console device '%s'\n", pvt->name);
344
345                 res = Pa_OpenStream(&pvt->stream, &input_params, &output_params,
346                         SAMPLE_RATE, NUM_SAMPLES, paNoFlag, NULL, NULL);
347         }
348
349         return res;
350 }
351
352 static int start_stream(struct console_pvt *pvt)
353 {
354         PaError res;
355         int ret_val = 0;
356
357         console_pvt_lock(pvt);
358
359         if (pvt->streamstate)
360                 goto return_unlock;
361
362         pvt->streamstate = 1;
363         ast_debug(1, "Starting stream\n");
364
365         res = open_stream(pvt);
366         if (res != paNoError) {
367                 ast_log(LOG_WARNING, "Failed to open stream - (%d) %s\n",
368                         res, Pa_GetErrorText(res));
369                 ret_val = -1;
370                 goto return_unlock;
371         }
372
373         res = Pa_StartStream(pvt->stream);
374         if (res != paNoError) {
375                 ast_log(LOG_WARNING, "Failed to start stream - (%d) %s\n",
376                         res, Pa_GetErrorText(res));
377                 ret_val = -1;
378                 goto return_unlock;
379         }
380
381         if (ast_pthread_create_background(&pvt->thread, NULL, stream_monitor, pvt)) {
382                 ast_log(LOG_ERROR, "Failed to start stream monitor thread\n");
383                 ret_val = -1;
384         }
385
386 return_unlock:
387         console_pvt_unlock(pvt);
388
389         return ret_val;
390 }
391
392 static int stop_stream(struct console_pvt *pvt)
393 {
394         if (!pvt->streamstate)
395                 return 0;
396
397         pthread_cancel(pvt->thread);
398         pthread_kill(pvt->thread, SIGURG);
399         pthread_join(pvt->thread, NULL);
400
401         console_pvt_lock(pvt);
402         Pa_AbortStream(pvt->stream);
403         Pa_CloseStream(pvt->stream);
404         pvt->stream = NULL;
405         pvt->streamstate = 0;
406         console_pvt_unlock(pvt);
407
408         return 0;
409 }
410
411 /*!
412  * \note Called with the pvt struct locked
413  */
414 static struct ast_channel *console_new(struct console_pvt *pvt, const char *ext, const char *ctx, int state)
415 {
416         struct ast_channel *chan;
417
418         if (!(chan = ast_channel_alloc(1, state, pvt->cid_num, pvt->cid_name, NULL, 
419                 ext, ctx, 0, "Console/%s", pvt->name))) {
420                 return NULL;
421         }
422
423         chan->tech = &console_tech;
424         chan->nativeformats = AST_FORMAT_SLINEAR16;
425         chan->readformat = AST_FORMAT_SLINEAR16;
426         chan->writeformat = AST_FORMAT_SLINEAR16;
427         chan->tech_pvt = ref_pvt(pvt);
428
429         pvt->owner = chan;
430
431         if (!ast_strlen_zero(pvt->language))
432                 ast_string_field_set(chan, language, pvt->language);
433
434         ast_jb_configure(chan, &global_jbconf);
435
436         if (state != AST_STATE_DOWN) {
437                 if (ast_pbx_start(chan)) {
438                         chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
439                         ast_hangup(chan);
440                         chan = NULL;
441                 } else
442                         start_stream(pvt);
443         }
444
445         return chan;
446 }
447
448 static struct ast_channel *console_request(const char *type, int format, void *data, int *cause)
449 {
450         int oldformat = format;
451         struct ast_channel *chan = NULL;
452         struct console_pvt *pvt;
453
454         if (!(pvt = find_pvt(data))) {
455                 ast_log(LOG_ERROR, "Console device '%s' not found\n", (char *) data);
456                 return NULL;
457         }
458
459         format &= SUPPORTED_FORMATS;
460         if (!format) {
461                 ast_log(LOG_NOTICE, "Channel requested with unsupported format(s): '%d'\n", oldformat);
462                 goto return_unref;
463         }
464
465         if (pvt->owner) {
466                 ast_log(LOG_NOTICE, "Console channel already active!\n");
467                 *cause = AST_CAUSE_BUSY;
468                 goto return_unref;
469         }
470
471         console_pvt_lock(pvt);
472         chan = console_new(pvt, NULL, NULL, AST_STATE_DOWN);
473         console_pvt_unlock(pvt);
474
475         if (!chan)
476                 ast_log(LOG_WARNING, "Unable to create new Console channel!\n");
477
478 return_unref:
479         unref_pvt(pvt);
480
481         return chan;
482 }
483
484 static int console_digit_begin(struct ast_channel *c, char digit)
485 {
486         ast_verb(1, V_BEGIN "Console Received Beginning of Digit %c" V_END, digit);
487
488         return -1; /* non-zero to request inband audio */
489 }
490
491 static int console_digit_end(struct ast_channel *c, char digit, unsigned int duration)
492 {
493         ast_verb(1, V_BEGIN "Console Received End of Digit %c (duration %u)" V_END, 
494                 digit, duration);
495
496         return -1; /* non-zero to request inband audio */
497 }
498
499 static int console_text(struct ast_channel *c, const char *text)
500 {
501         ast_verb(1, V_BEGIN "Console Received Text '%s'" V_END, text);
502
503         return 0;
504 }
505
506 static int console_hangup(struct ast_channel *c)
507 {
508         struct console_pvt *pvt = c->tech_pvt;
509
510         ast_verb(1, V_BEGIN "Hangup on Console" V_END);
511
512         pvt->hookstate = 0;
513         pvt->owner = NULL;
514         stop_stream(pvt);
515
516         c->tech_pvt = unref_pvt(pvt);
517
518         return 0;
519 }
520
521 static int console_answer(struct ast_channel *c)
522 {
523         struct console_pvt *pvt = c->tech_pvt;
524
525         ast_verb(1, V_BEGIN "Call from Console has been Answered" V_END);
526
527         ast_setstate(c, AST_STATE_UP);
528
529         return start_stream(pvt);
530 }
531
532 /*
533  * \brief Implementation of the ast_channel_tech read() callback
534  *
535  * Calling this function is harmless.  However, if it does get called, it
536  * is an indication that something weird happened that really shouldn't
537  * have and is worth looking into.
538  * 
539  * Why should this function not get called?  Well, let me explain.  There are
540  * a couple of ways to pass on audio that has come from this channel.  The way
541  * that this channel driver uses is that once the audio is available, it is
542  * wrapped in an ast_frame and queued onto the channel using ast_queue_frame().
543  *
544  * The other method would be signalling to the core that there is audio waiting,
545  * and that it needs to call the channel's read() callback to get it.  The way
546  * the channel gets signalled is that one or more file descriptors are placed
547  * in the fds array on the ast_channel which the core will poll() on.  When the
548  * fd indicates that input is available, the read() callback is called.  This
549  * is especially useful when there is a dedicated file descriptor where the
550  * audio is read from.  An example would be the socket for an RTP stream.
551  */
552 static struct ast_frame *console_read(struct ast_channel *chan)
553 {
554         ast_debug(1, "I should not be called ...\n");
555
556         return &ast_null_frame;
557 }
558
559 static int console_call(struct ast_channel *c, char *dest, int timeout)
560 {
561         struct ast_frame f = { 0, };
562         struct console_pvt *pvt = c->tech_pvt;
563
564         ast_verb(1, V_BEGIN "Call to device '%s' on console from '%s' <%s>" V_END,
565                 dest, c->cid.cid_name, c->cid.cid_num);
566
567         console_pvt_lock(pvt);
568
569         if (pvt->autoanswer) {
570                 pvt->hookstate = 1;
571                 console_pvt_unlock(pvt);
572                 ast_verb(1, V_BEGIN "Auto-answered" V_END);
573                 f.frametype = AST_FRAME_CONTROL;
574                 f.subclass = AST_CONTROL_ANSWER;
575         } else {
576                 console_pvt_unlock(pvt);
577                 ast_verb(1, V_BEGIN "Type 'console answer' to answer, or use the 'autoanswer' option "
578                                 "for future calls" V_END);
579                 f.frametype = AST_FRAME_CONTROL;
580                 f.subclass = AST_CONTROL_RINGING;
581                 ast_indicate(c, AST_CONTROL_RINGING);
582         }
583
584         ast_queue_frame(c, &f);
585
586         return start_stream(pvt);
587 }
588
589 static int console_write(struct ast_channel *chan, struct ast_frame *f)
590 {
591         struct console_pvt *pvt = chan->tech_pvt;
592
593         Pa_WriteStream(pvt->stream, f->data, f->samples);
594
595         return 0;
596 }
597
598 static int console_indicate(struct ast_channel *chan, int cond, const void *data, size_t datalen)
599 {
600         struct console_pvt *pvt = chan->tech_pvt;
601         int res = 0;
602
603         switch (cond) {
604         case AST_CONTROL_BUSY:
605         case AST_CONTROL_CONGESTION:
606         case AST_CONTROL_RINGING:
607         case -1:
608                 res = -1;  /* Ask for inband indications */
609                 break;
610         case AST_CONTROL_PROGRESS:
611         case AST_CONTROL_PROCEEDING:
612         case AST_CONTROL_VIDUPDATE:
613                 break;
614         case AST_CONTROL_HOLD:
615                 ast_verb(1, V_BEGIN "Console Has Been Placed on Hold" V_END);
616                 ast_moh_start(chan, data, pvt->mohinterpret);
617                 break;
618         case AST_CONTROL_UNHOLD:
619                 ast_verb(1, V_BEGIN "Console Has Been Retrieved from Hold" V_END);
620                 ast_moh_stop(chan);
621                 break;
622         default:
623                 ast_log(LOG_WARNING, "Don't know how to display condition %d on %s\n", 
624                         cond, chan->name);
625                 /* The core will play inband indications for us if appropriate */
626                 res = -1;
627         }
628
629         return res;
630 }
631
632 static int console_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
633 {
634         struct console_pvt *pvt = newchan->tech_pvt;
635
636         pvt->owner = newchan;
637
638         return 0;
639 }
640
641 /*!
642  * split a string in extension-context, returns pointers to malloc'ed
643  * strings.
644  * If we do not have 'overridecontext' then the last @ is considered as
645  * a context separator, and the context is overridden.
646  * This is usually not very necessary as you can play with the dialplan,
647  * and it is nice not to need it because you have '@' in SIP addresses.
648  * Return value is the buffer address.
649  *
650  * \note came from chan_oss
651  */
652 static char *ast_ext_ctx(struct console_pvt *pvt, const char *src, char **ext, char **ctx)
653 {
654         if (ext == NULL || ctx == NULL)
655                 return NULL;                    /* error */
656
657         *ext = *ctx = NULL;
658
659         if (src && *src != '\0')
660                 *ext = ast_strdup(src);
661
662         if (*ext == NULL)
663                 return NULL;
664
665         if (!pvt->overridecontext) {
666                 /* parse from the right */
667                 *ctx = strrchr(*ext, '@');
668                 if (*ctx)
669                         *(*ctx)++ = '\0';
670         }
671
672         return *ext;
673 }
674
675 static struct console_pvt *get_active_pvt(void)
676 {
677         struct console_pvt *pvt;
678
679         ast_rwlock_rdlock(&active_lock);
680         pvt = ref_pvt(active_pvt);      
681         ast_rwlock_unlock(&active_lock);
682
683         return pvt;
684 }
685
686 static char *cli_console_autoanswer(struct ast_cli_entry *e, int cmd, 
687         struct ast_cli_args *a)
688 {
689         struct console_pvt *pvt = get_active_pvt();
690         char *res = CLI_SUCCESS;
691
692         switch (cmd) {
693         case CLI_INIT:
694                 e->command = "console set autoanswer [on|off]";
695                 e->usage =
696                         "Usage: console set autoanswer [on|off]\n"
697                         "       Enables or disables autoanswer feature.  If used without\n"
698                         "       argument, displays the current on/off status of autoanswer.\n"
699                         "       The default value of autoanswer is in 'oss.conf'.\n";
700                 return NULL;
701
702         case CLI_GENERATE:
703                 return NULL;
704         }
705
706         if (!pvt) {
707                 ast_cli(a->fd, "No console device is set as active.\n");
708                 return CLI_FAILURE;
709         }
710
711         if (a->argc == e->args - 1) {
712                 ast_cli(a->fd, "Auto answer is %s.\n", pvt->autoanswer ? "on" : "off");
713                 unref_pvt(pvt);
714                 return CLI_SUCCESS;
715         }
716
717         if (a->argc != e->args) {
718                 unref_pvt(pvt);
719                 return CLI_SHOWUSAGE;
720         }
721
722         if (!strcasecmp(a->argv[e->args-1], "on"))
723                 pvt->autoanswer = 1;
724         else if (!strcasecmp(a->argv[e->args - 1], "off"))
725                 pvt->autoanswer = 0;
726         else
727                 res = CLI_SHOWUSAGE;
728
729         unref_pvt(pvt);
730
731         return CLI_SUCCESS;
732 }
733
734 static char *cli_console_flash(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
735 {
736         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH };
737         struct console_pvt *pvt = get_active_pvt();
738
739         if (cmd == CLI_INIT) {
740                 e->command = "console flash";
741                 e->usage =
742                         "Usage: console flash\n"
743                         "       Flashes the call currently placed on the console.\n";
744                 return NULL;
745         } else if (cmd == CLI_GENERATE)
746                 return NULL;
747
748         if (!pvt) {
749                 ast_cli(a->fd, "No console device is set as active\n");
750                 return CLI_FAILURE;
751         }
752
753         if (a->argc != e->args)
754                 return CLI_SHOWUSAGE;
755
756         if (!pvt->owner) {
757                 ast_cli(a->fd, "No call to flash\n");
758                 unref_pvt(pvt);
759                 return CLI_FAILURE;
760         }
761
762         pvt->hookstate = 0;
763
764         ast_queue_frame(pvt->owner, &f);
765
766         unref_pvt(pvt);
767
768         return CLI_SUCCESS;
769 }
770
771 static char *cli_console_dial(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
772 {
773         char *s = NULL;
774         const char *mye = NULL, *myc = NULL; 
775         struct console_pvt *pvt = get_active_pvt();
776
777         if (cmd == CLI_INIT) {
778                 e->command = "console dial";
779                 e->usage =
780                         "Usage: console dial [extension[@context]]\n"
781                         "       Dials a given extension (and context if specified)\n";
782                 return NULL;
783         } else if (cmd == CLI_GENERATE)
784                 return NULL;
785
786         if (!pvt) {
787                 ast_cli(a->fd, "No console device is currently set as active\n");
788                 return CLI_FAILURE;
789         }
790         
791         if (a->argc > e->args + 1)
792                 return CLI_SHOWUSAGE;
793
794         if (pvt->owner) {       /* already in a call */
795                 int i;
796                 struct ast_frame f = { AST_FRAME_DTMF, 0 };
797
798                 if (a->argc == e->args) {       /* argument is mandatory here */
799                         ast_cli(a->fd, "Already in a call. You can only dial digits until you hangup.\n");
800                         unref_pvt(pvt);
801                         return CLI_FAILURE;
802                 }
803                 s = a->argv[e->args];
804                 /* send the string one char at a time */
805                 for (i = 0; i < strlen(s); i++) {
806                         f.subclass = s[i];
807                         ast_queue_frame(pvt->owner, &f);
808                 }
809                 unref_pvt(pvt);
810                 return CLI_SUCCESS;
811         }
812
813         /* if we have an argument split it into extension and context */
814         if (a->argc == e->args + 1) {
815                 char *ext = NULL, *con = NULL;
816                 s = ast_ext_ctx(pvt, a->argv[e->args], &ext, &con);
817                 ast_debug(1, "provided '%s', exten '%s' context '%s'\n", 
818                         a->argv[e->args], mye, myc);
819                 mye = ext;
820                 myc = con;
821         }
822
823         /* supply default values if needed */
824         if (ast_strlen_zero(mye))
825                 mye = pvt->exten;
826         if (ast_strlen_zero(myc))
827                 myc = pvt->context;
828
829         if (ast_exists_extension(NULL, myc, mye, 1, NULL)) {
830                 console_pvt_lock(pvt);
831                 pvt->hookstate = 1;
832                 console_new(pvt, mye, myc, AST_STATE_RINGING);
833                 console_pvt_unlock(pvt);
834         } else
835                 ast_cli(a->fd, "No such extension '%s' in context '%s'\n", mye, myc);
836
837         if (s)
838                 free(s);
839
840         unref_pvt(pvt);
841
842         return CLI_SUCCESS;
843 }
844
845 static char *cli_console_hangup(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
846 {
847         struct console_pvt *pvt = get_active_pvt();
848
849         if (cmd == CLI_INIT) {
850                 e->command = "console hangup";
851                 e->usage =
852                         "Usage: console hangup\n"
853                         "       Hangs up any call currently placed on the console.\n";
854                 return NULL;
855         } else if (cmd == CLI_GENERATE)
856                 return NULL;
857
858         if (!pvt) {
859                 ast_cli(a->fd, "No console device is set as active\n");
860                 return CLI_FAILURE;
861         }
862         
863         if (a->argc != e->args)
864                 return CLI_SHOWUSAGE;
865
866         if (!pvt->owner && !pvt->hookstate) {
867                 ast_cli(a->fd, "No call to hang up\n");
868                 unref_pvt(pvt);
869                 return CLI_FAILURE;
870         }
871
872         pvt->hookstate = 0;
873         if (pvt->owner)
874                 ast_queue_hangup(pvt->owner);
875
876         unref_pvt(pvt);
877
878         return CLI_SUCCESS;
879 }
880
881 static char *cli_console_mute(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
882 {
883         char *s;
884         struct console_pvt *pvt = get_active_pvt();
885         char *res = CLI_SUCCESS;
886
887         if (cmd == CLI_INIT) {
888                 e->command = "console {mute|unmute}";
889                 e->usage =
890                         "Usage: console {mute|unmute}\n"
891                         "       Mute/unmute the microphone.\n";
892                 return NULL;
893         } else if (cmd == CLI_GENERATE)
894                 return NULL;
895
896         if (!pvt) {
897                 ast_cli(a->fd, "No console device is set as active\n");
898                 return CLI_FAILURE;
899         }
900
901         if (a->argc != e->args)
902                 return CLI_SHOWUSAGE;
903
904         s = a->argv[e->args-1];
905         if (!strcasecmp(s, "mute"))
906                 pvt->muted = 1;
907         else if (!strcasecmp(s, "unmute"))
908                 pvt->muted = 0;
909         else
910                 res = CLI_SHOWUSAGE;
911
912         ast_verb(1, V_BEGIN "The Console is now %s" V_END, 
913                 pvt->muted ? "Muted" : "Unmuted");
914
915         unref_pvt(pvt);
916
917         return res;
918 }
919
920 static char *cli_list_available(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
921 {
922         PaDeviceIndex index, num, def_input, def_output;
923
924         if (cmd == CLI_INIT) {
925                 e->command = "console list available";
926                 e->usage =
927                         "Usage: console list available\n"
928                         "       List all available devices.\n";
929                 return NULL;
930         } else if (cmd == CLI_GENERATE)
931                 return NULL;
932
933         if (a->argc != e->args)
934                 return CLI_SHOWUSAGE;
935
936         ast_cli(a->fd, "\n"
937                     "=============================================================\n"
938                     "=== Available Devices =======================================\n"
939                     "=============================================================\n"
940                     "===\n");
941
942         num = Pa_GetDeviceCount();
943         if (!num) {
944                 ast_cli(a->fd, "(None)\n");
945                 return CLI_SUCCESS;
946         }
947
948         def_input = Pa_GetDefaultInputDevice();
949         def_output = Pa_GetDefaultOutputDevice();
950         for (index = 0; index < num; index++) {
951                 const PaDeviceInfo *dev = Pa_GetDeviceInfo(index);
952                 if (!dev)
953                         continue;
954                 ast_cli(a->fd, "=== ---------------------------------------------------------\n"
955                                "=== Device Name: %s\n", dev->name);
956                 if (dev->maxInputChannels)
957                         ast_cli(a->fd, "=== ---> %sInput Device\n", (index == def_input) ? "Default " : "");
958                 if (dev->maxOutputChannels)
959                         ast_cli(a->fd, "=== ---> %sOutput Device\n", (index == def_output) ? "Default " : "");
960                 ast_cli(a->fd, "=== ---------------------------------------------------------\n===\n");
961         }
962
963         ast_cli(a->fd, "=============================================================\n\n");
964
965         return CLI_SUCCESS;
966 }
967
968 static char *cli_list_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
969 {
970         struct ao2_iterator i;
971         struct console_pvt *pvt;
972
973         if (cmd == CLI_INIT) {
974                 e->command = "console list devices";
975                 e->usage =
976                         "Usage: console list devices\n"
977                         "       List all configured devices.\n";
978                 return NULL;
979         } else if (cmd == CLI_GENERATE)
980                 return NULL;
981
982         if (a->argc != e->args)
983                 return CLI_SHOWUSAGE;
984
985         ast_cli(a->fd, "\n"
986                     "=============================================================\n"
987                     "=== Configured Devices ======================================\n"
988                     "=============================================================\n"
989                     "===\n");
990
991         i = ao2_iterator_init(pvts, 0);
992         while ((pvt = ao2_iterator_next(&i))) {
993                 console_pvt_lock(pvt);
994
995                 ast_cli(a->fd, "=== ---------------------------------------------------------\n"
996                                "=== Device Name: %s\n"
997                                "=== ---> Active:           %s\n"
998                                "=== ---> Input Device:     %s\n"
999                                "=== ---> Output Device:    %s\n"
1000                                "=== ---> Context:          %s\n"
1001                                "=== ---> Extension:        %s\n"
1002                                "=== ---> CallerID Num:     %s\n"
1003                                "=== ---> CallerID Name:    %s\n"
1004                                "=== ---> MOH Interpret:    %s\n"
1005                                "=== ---> Language:         %s\n"
1006                                "=== ---> Muted:            %s\n"
1007                                "=== ---> Auto-Answer:      %s\n"
1008                                "=== ---> Override Context: %s\n"
1009                                "=== ---------------------------------------------------------\n===\n",
1010                         pvt->name, (pvt == active_pvt) ? "Yes" : "No",
1011                         pvt->input_device, pvt->output_device, pvt->context,
1012                         pvt->exten, pvt->cid_num, pvt->cid_name, pvt->mohinterpret,
1013                         pvt->language, pvt->muted ? "Yes" : "No", pvt->autoanswer ? "Yes" : "No",
1014                         pvt->overridecontext ? "Yes" : "No");
1015
1016                 console_pvt_unlock(pvt);
1017                 unref_pvt(pvt);
1018         }
1019
1020         ast_cli(a->fd, "=============================================================\n\n");
1021
1022         return CLI_SUCCESS;
1023 }
1024 /*!
1025  * \brief answer command from the console
1026  */
1027 static char *cli_console_answer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1028 {
1029         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_ANSWER };
1030         struct console_pvt *pvt = get_active_pvt();
1031
1032         switch (cmd) {
1033         case CLI_INIT:
1034                 e->command = "console answer";
1035                 e->usage =
1036                         "Usage: console answer\n"
1037                         "       Answers an incoming call on the console channel.\n";
1038                 return NULL;
1039
1040         case CLI_GENERATE:
1041                 return NULL;    /* no completion */
1042         }
1043
1044         if (!pvt) {
1045                 ast_cli(a->fd, "No console device is set as active\n");
1046                 return CLI_FAILURE;
1047         }
1048
1049         if (a->argc != e->args) {
1050                 unref_pvt(pvt);
1051                 return CLI_SHOWUSAGE;
1052         }
1053
1054         if (!pvt->owner) {
1055                 ast_cli(a->fd, "No one is calling us\n");
1056                 unref_pvt(pvt);
1057                 return CLI_FAILURE;
1058         }
1059
1060         pvt->hookstate = 1;
1061
1062         ast_indicate(pvt->owner, -1);
1063
1064         ast_queue_frame(pvt->owner, &f);
1065
1066         unref_pvt(pvt);
1067
1068         return CLI_SUCCESS;
1069 }
1070
1071 /*!
1072  * \brief Console send text CLI command
1073  *
1074  * \note concatenate all arguments into a single string. argv is NULL-terminated
1075  * so we can use it right away
1076  */
1077 static char *cli_console_sendtext(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1078 {
1079         char buf[TEXT_SIZE];
1080         struct console_pvt *pvt = get_active_pvt();
1081         struct ast_frame f = {
1082                 .frametype = AST_FRAME_TEXT,
1083                 .data = buf,
1084                 .src = "console_send_text",
1085         };
1086         int len;
1087
1088         if (cmd == CLI_INIT) {
1089                 e->command = "console send text";
1090                 e->usage =
1091                         "Usage: console send text <message>\n"
1092                         "       Sends a text message for display on the remote terminal.\n";
1093                 return NULL;
1094         } else if (cmd == CLI_GENERATE)
1095                 return NULL;
1096
1097         if (!pvt) {
1098                 ast_cli(a->fd, "No console device is set as active\n");
1099                 return CLI_FAILURE;
1100         }
1101
1102         if (a->argc < e->args + 1) {
1103                 unref_pvt(pvt);
1104                 return CLI_SHOWUSAGE;
1105         }
1106
1107         if (!pvt->owner) {
1108                 ast_cli(a->fd, "Not in a call\n");
1109                 unref_pvt(pvt);
1110                 return CLI_FAILURE;
1111         }
1112
1113         ast_join(buf, sizeof(buf) - 1, a->argv + e->args);
1114         if (ast_strlen_zero(buf)) {
1115                 unref_pvt(pvt);
1116                 return CLI_SHOWUSAGE;
1117         }
1118
1119         len = strlen(buf);
1120         buf[len] = '\n';
1121         f.datalen = len + 1;
1122
1123         ast_queue_frame(pvt->owner, &f);
1124
1125         unref_pvt(pvt);
1126
1127         return CLI_SUCCESS;
1128 }
1129
1130 static void set_active(struct console_pvt *pvt, const char *value)
1131 {
1132         if (pvt == &globals) {
1133                 ast_log(LOG_ERROR, "active is only valid as a per-device setting\n");
1134                 return;
1135         }
1136
1137         if (!ast_true(value))
1138                 return;
1139
1140         ast_rwlock_wrlock(&active_lock);
1141         if (active_pvt)
1142                 unref_pvt(active_pvt);
1143         active_pvt = ref_pvt(pvt);
1144         ast_rwlock_unlock(&active_lock);
1145 }
1146
1147 static char *cli_console_active(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1148 {
1149         struct console_pvt *pvt;
1150
1151         switch (cmd) {
1152         case CLI_INIT:
1153                 e->command = "console active";
1154                 e->usage =
1155                         "Usage: console active [device]\n"
1156                         "       If no device is specified.  The active console device will be shown.\n"
1157                         "Otherwise, the specified device will become the console device active for\n"
1158                         "the Asterisk CLI.\n";
1159                 return NULL;
1160         case CLI_GENERATE:
1161                 if (a->pos == e->args) {
1162                         struct ao2_iterator i;
1163                         int x = 0;
1164                         char *res = NULL;
1165                         i = ao2_iterator_init(pvts, 0);
1166                         while ((pvt = ao2_iterator_next(&i))) {
1167                                 if (++x > a->n && !strncasecmp(pvt->name, a->word, strlen(a->word)))
1168                                         res = ast_strdup(pvt->name);
1169                                 unref_pvt(pvt);
1170                                 if (res)
1171                                         return res;
1172                         }
1173                 }
1174                 return NULL;
1175         }
1176
1177         if (a->argc < e->args)
1178                 return CLI_SHOWUSAGE;
1179
1180         if (a->argc == e->args) {
1181                 pvt = get_active_pvt();
1182
1183                 if (!pvt)
1184                         ast_cli(a->fd, "No device is currently set as the active console device.\n");
1185                 else {
1186                         console_pvt_lock(pvt);
1187                         ast_cli(a->fd, "The active console device is '%s'.\n", pvt->name);
1188                         console_pvt_unlock(pvt);
1189                         pvt = unref_pvt(pvt);
1190                 }
1191
1192                 return CLI_SUCCESS;
1193         }
1194
1195         if (!(pvt = find_pvt(a->argv[e->args]))) {
1196                 ast_cli(a->fd, "Could not find a device called '%s'.\n", a->argv[e->args]);
1197                 return CLI_FAILURE;
1198         }
1199
1200         set_active(pvt, "yes");
1201
1202         console_pvt_lock(pvt);
1203         ast_cli(a->fd, "The active console device has been set to '%s'\n", pvt->name);
1204         console_pvt_unlock(pvt);
1205
1206         unref_pvt(pvt);
1207
1208         return CLI_SUCCESS;
1209 }
1210
1211 static struct ast_cli_entry cli_console[] = {
1212         AST_CLI_DEFINE(cli_console_dial,       "Dial an extension from the console"),
1213         AST_CLI_DEFINE(cli_console_hangup,     "Hangup a call on the console"),
1214         AST_CLI_DEFINE(cli_console_mute,       "Disable/Enable mic input"),
1215         AST_CLI_DEFINE(cli_console_answer,     "Answer an incoming console call"),
1216         AST_CLI_DEFINE(cli_console_sendtext,   "Send text to a connected party"),
1217         AST_CLI_DEFINE(cli_console_flash,      "Send a flash to the connected party"),
1218         AST_CLI_DEFINE(cli_console_autoanswer, "Turn autoanswer on or off"),
1219         AST_CLI_DEFINE(cli_list_available,     "List available devices"),
1220         AST_CLI_DEFINE(cli_list_devices,       "List configured devices"),
1221         AST_CLI_DEFINE(cli_console_active,     "View or Set the active console device"),
1222 };
1223
1224 /*!
1225  * \brief Set default values for a pvt struct
1226  *
1227  * \note This function expects the pvt lock to be held.
1228  */
1229 static void set_pvt_defaults(struct console_pvt *pvt)
1230 {
1231         if (pvt == &globals) {
1232                 ast_string_field_set(pvt, mohinterpret, "default");
1233                 ast_string_field_set(pvt, context, "default");
1234                 ast_string_field_set(pvt, exten, "s");
1235                 ast_string_field_set(pvt, language, "");
1236                 ast_string_field_set(pvt, cid_num, "");
1237                 ast_string_field_set(pvt, cid_name, "");
1238         
1239                 pvt->overridecontext = 0;
1240                 pvt->autoanswer = 0;
1241         } else {
1242                 ast_mutex_lock(&globals_lock);
1243
1244                 ast_string_field_set(pvt, mohinterpret, globals.mohinterpret);
1245                 ast_string_field_set(pvt, context, globals.context);
1246                 ast_string_field_set(pvt, exten, globals.exten);
1247                 ast_string_field_set(pvt, language, globals.language);
1248                 ast_string_field_set(pvt, cid_num, globals.cid_num);
1249                 ast_string_field_set(pvt, cid_name, globals.cid_name);
1250
1251                 pvt->overridecontext = globals.overridecontext;
1252                 pvt->autoanswer = globals.autoanswer;
1253
1254                 ast_mutex_unlock(&globals_lock);
1255         }
1256 }
1257
1258 static void store_callerid(struct console_pvt *pvt, const char *value)
1259 {
1260         char cid_name[256];
1261         char cid_num[256];
1262
1263         ast_callerid_split(value, cid_name, sizeof(cid_name), 
1264                 cid_num, sizeof(cid_num));
1265
1266         ast_string_field_set(pvt, cid_name, cid_name);
1267         ast_string_field_set(pvt, cid_num, cid_num);
1268 }
1269
1270 /*!
1271  * \brief Store a configuration parameter in a pvt struct
1272  *
1273  * \note This function expects the pvt lock to be held.
1274  */
1275 static void store_config_core(struct console_pvt *pvt, const char *var, const char *value)
1276 {
1277         if (pvt == &globals && !ast_jb_read_conf(&global_jbconf, var, value))
1278                 return;
1279
1280         CV_START(var, value);
1281
1282         CV_STRFIELD("context", pvt, context);
1283         CV_STRFIELD("extension", pvt, exten);
1284         CV_STRFIELD("mohinterpret", pvt, mohinterpret);
1285         CV_STRFIELD("language", pvt, language);
1286         CV_F("callerid", store_callerid(pvt, value));
1287         CV_BOOL("overridecontext", pvt->overridecontext);
1288         CV_BOOL("autoanswer", pvt->autoanswer);
1289
1290         if (pvt != &globals) {
1291                 CV_F("active", set_active(pvt, value))
1292                 CV_STRFIELD("input_device", pvt, input_device);
1293                 CV_STRFIELD("output_device", pvt, output_device);
1294         }
1295
1296         ast_log(LOG_WARNING, "Unknown option '%s'\n", var);
1297
1298         CV_END;
1299 }
1300
1301 static void pvt_destructor(void *obj)
1302 {
1303         struct console_pvt *pvt = obj;
1304
1305         ast_string_field_free_memory(pvt);
1306 }
1307
1308 static int init_pvt(struct console_pvt *pvt, const char *name)
1309 {
1310         pvt->thread = AST_PTHREADT_NULL;
1311
1312         if (ast_string_field_init(pvt, 32))
1313                 return -1;
1314
1315         ast_string_field_set(pvt, name, S_OR(name, ""));
1316
1317         return 0;
1318 }
1319
1320 static void build_device(struct ast_config *cfg, const char *name)
1321 {
1322         struct ast_variable *v;
1323         struct console_pvt *pvt;
1324         int new = 0;
1325
1326         if ((pvt = find_pvt(name))) {
1327                 console_pvt_lock(pvt);
1328                 set_pvt_defaults(pvt);
1329                 pvt->destroy = 0;
1330         } else {
1331                 if (!(pvt = ao2_alloc(sizeof(*pvt), pvt_destructor)))
1332                         return;
1333                 init_pvt(pvt, name);
1334                 set_pvt_defaults(pvt);
1335                 new = 1;
1336         }
1337
1338         for (v = ast_variable_browse(cfg, name); v; v = v->next)
1339                 store_config_core(pvt, v->name, v->value);
1340
1341         if (new)
1342                 ao2_link(pvts, pvt);
1343         else
1344                 console_pvt_unlock(pvt);
1345         
1346         unref_pvt(pvt);
1347 }
1348
1349 static int pvt_mark_destroy_cb(void *obj, void *arg, int flags)
1350 {
1351         struct console_pvt *pvt = obj;
1352         pvt->destroy = 1;
1353         return 0;
1354 }
1355
1356 static void destroy_pvts(void)
1357 {
1358         struct ao2_iterator i;
1359         struct console_pvt *pvt;
1360
1361         i = ao2_iterator_init(pvts, 0);
1362         while ((pvt = ao2_iterator_next(&i))) {
1363                 if (pvt->destroy) {
1364                         ao2_unlink(pvts, pvt);
1365                         ast_rwlock_wrlock(&active_lock);
1366                         if (active_pvt == pvt)
1367                                 active_pvt = unref_pvt(pvt);
1368                         ast_rwlock_unlock(&active_lock);
1369                 }
1370                 unref_pvt(pvt);
1371         }
1372 }
1373
1374 /*!
1375  * \brief Load the configuration
1376  * \param reload if this was called due to a reload
1377  * \retval 0 succcess
1378  * \retval -1 failure
1379  */
1380 static int load_config(int reload)
1381 {
1382         struct ast_config *cfg;
1383         struct ast_variable *v;
1384         struct ast_flags config_flags = { 0 };
1385         char *context = NULL;
1386
1387         /* default values */
1388         memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
1389         ast_mutex_lock(&globals_lock);
1390         set_pvt_defaults(&globals);
1391         ast_mutex_unlock(&globals_lock);
1392
1393         if (!(cfg = ast_config_load(config_file, config_flags))) {
1394                 ast_log(LOG_NOTICE, "Unable to open configuration file %s!\n", config_file);
1395                 return -1;
1396         }
1397         
1398         ao2_callback(pvts, 0, pvt_mark_destroy_cb, NULL);
1399
1400         ast_mutex_lock(&globals_lock);
1401         for (v = ast_variable_browse(cfg, "general"); v; v = v->next)
1402                 store_config_core(&globals, v->name, v->value);
1403         ast_mutex_unlock(&globals_lock);
1404
1405         while ((context = ast_category_browse(cfg, context))) {
1406                 if (strcasecmp(context, "general"))
1407                         build_device(cfg, context);
1408         }
1409
1410         ast_config_destroy(cfg);
1411
1412         destroy_pvts();
1413
1414         return 0;
1415 }
1416
1417 static int pvt_hash_cb(const void *obj, const int flags)
1418 {
1419         const struct console_pvt *pvt = obj;
1420
1421         return ast_str_hash(pvt->name);
1422 }
1423
1424 static int pvt_cmp_cb(void *obj, void *arg, int flags)
1425 {
1426         struct console_pvt *pvt = obj, *pvt2 = arg;
1427
1428         return !strcasecmp(pvt->name, pvt2->name) ? CMP_MATCH : 0;
1429 }
1430
1431 static void stop_streams(void)
1432 {
1433         struct console_pvt *pvt;
1434         struct ao2_iterator i;
1435
1436         i = ao2_iterator_init(pvts, 0);
1437         while ((pvt = ao2_iterator_next(&i))) {
1438                 if (pvt->hookstate)
1439                         stop_stream(pvt);
1440                 unref_pvt(pvt);
1441         }
1442 }
1443
1444 static int unload_module(void)
1445 {
1446         ast_channel_unregister(&console_tech);
1447         ast_cli_unregister_multiple(cli_console, ARRAY_LEN(cli_console));
1448
1449         stop_streams();
1450
1451         Pa_Terminate();
1452
1453         /* Will unref all the pvts so they will get destroyed, too */
1454         ao2_ref(pvts, -1);
1455
1456         pvt_destructor(&globals);
1457
1458         return 0;
1459 }
1460
1461 static int load_module(void)
1462 {
1463         PaError res;
1464
1465         init_pvt(&globals, NULL);
1466
1467         if (!(pvts = ao2_container_alloc(NUM_PVT_BUCKETS, pvt_hash_cb, pvt_cmp_cb)))
1468                 goto return_error;
1469
1470         if (load_config(0))
1471                 goto return_error;
1472
1473         res = Pa_Initialize();
1474         if (res != paNoError) {
1475                 ast_log(LOG_WARNING, "Failed to initialize audio system - (%d) %s\n",
1476                         res, Pa_GetErrorText(res));
1477                 goto return_error_pa_init;
1478         }
1479
1480         if (ast_channel_register(&console_tech)) {
1481                 ast_log(LOG_ERROR, "Unable to register channel type 'Console'\n");
1482                 goto return_error_chan_reg;
1483         }
1484
1485         if (ast_cli_register_multiple(cli_console, ARRAY_LEN(cli_console)))
1486                 goto return_error_cli_reg;
1487
1488         return AST_MODULE_LOAD_SUCCESS;
1489
1490 return_error_cli_reg:
1491         ast_cli_unregister_multiple(cli_console, ARRAY_LEN(cli_console));
1492 return_error_chan_reg:
1493         ast_channel_unregister(&console_tech);
1494 return_error_pa_init:
1495         Pa_Terminate();
1496 return_error:
1497         if (pvts)
1498                 ao2_ref(pvts, -1);
1499         pvt_destructor(&globals);
1500
1501         return AST_MODULE_LOAD_DECLINE;
1502 }
1503
1504 static int reload(void)
1505 {
1506         return load_config(1);
1507 }
1508
1509 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Console Channel Driver",
1510                 .load = load_module,
1511                 .unload = unload_module,
1512                 .reload = reload,
1513 );