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