Change channel state on local channels for busy,answer,ring.
[asterisk/asterisk.git] / channels / chan_local.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \author Mark Spencer <markster@digium.com>
22  *
23  * \brief Local Proxy Channel
24  * 
25  * \ingroup channel_drivers
26  */
27
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include <fcntl.h>
33 #include <sys/signal.h>
34
35 #include "asterisk/lock.h"
36 #include "asterisk/channel.h"
37 #include "asterisk/config.h"
38 #include "asterisk/module.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/sched.h"
41 #include "asterisk/io.h"
42 #include "asterisk/acl.h"
43 #include "asterisk/callerid.h"
44 #include "asterisk/file.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/app.h"
47 #include "asterisk/musiconhold.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/stringfields.h"
50 #include "asterisk/devicestate.h"
51
52 static const char tdesc[] = "Local Proxy Channel Driver";
53
54 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
55
56 static struct ast_jb_conf g_jb_conf = {
57         .flags = 0,
58         .max_size = -1,
59         .resync_threshold = -1,
60         .impl = "",
61 };
62
63 static struct ast_channel *local_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
64 static int local_digit_begin(struct ast_channel *ast, char digit);
65 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
66 static int local_call(struct ast_channel *ast, char *dest, int timeout);
67 static int local_hangup(struct ast_channel *ast);
68 static int local_answer(struct ast_channel *ast);
69 static struct ast_frame *local_read(struct ast_channel *ast);
70 static int local_write(struct ast_channel *ast, struct ast_frame *f);
71 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
72 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
73 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
74 static int local_sendtext(struct ast_channel *ast, const char *text);
75 static int local_devicestate(void *data);
76 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge);
77
78 /* PBX interface structure for channel registration */
79 static const struct ast_channel_tech local_tech = {
80         .type = "Local",
81         .description = tdesc,
82         .capabilities = -1,
83         .requester = local_request,
84         .send_digit_begin = local_digit_begin,
85         .send_digit_end = local_digit_end,
86         .call = local_call,
87         .hangup = local_hangup,
88         .answer = local_answer,
89         .read = local_read,
90         .write = local_write,
91         .write_video = local_write,
92         .exception = local_read,
93         .indicate = local_indicate,
94         .fixup = local_fixup,
95         .send_html = local_sendhtml,
96         .send_text = local_sendtext,
97         .devicestate = local_devicestate,
98         .bridged_channel = local_bridgedchannel,
99 };
100
101 /*! \brief the local pvt structure for all channels
102
103         The local channel pvt has two ast_chan objects - the "owner" and the "next channel", the outbound channel
104
105         ast_chan owner -> local_pvt -> ast_chan chan -> yet-another-pvt-depending-on-channel-type
106
107 */
108 struct local_pvt {
109         ast_mutex_t lock;                       /*!< Channel private lock */
110         unsigned int flags;                     /*!< Private flags */
111         char context[AST_MAX_CONTEXT];          /*!< Context to call */
112         char exten[AST_MAX_EXTENSION];          /*!< Extension to call */
113         int reqformat;                          /*!< Requested format */
114         struct ast_jb_conf jb_conf;             /*!< jitterbuffer configuration for this local channel */
115         struct ast_channel *owner;              /*!< Master Channel - Bridging happens here */
116         struct ast_channel *chan;               /*!< Outbound channel - PBX is run here */
117         struct ast_module_user *u_owner;        /*!< reference to keep the module loaded while in use */
118         struct ast_module_user *u_chan;         /*!< reference to keep the module loaded while in use */
119         AST_LIST_ENTRY(local_pvt) list;         /*!< Next entity */
120 };
121
122 #define LOCAL_GLARE_DETECT    (1 << 0) /*!< Detect glare on hangup */
123 #define LOCAL_CANCEL_QUEUE    (1 << 1) /*!< Cancel queue */
124 #define LOCAL_ALREADY_MASQED  (1 << 2) /*!< Already masqueraded */
125 #define LOCAL_LAUNCHED_PBX    (1 << 3) /*!< PBX was launched */
126 #define LOCAL_NO_OPTIMIZATION (1 << 4) /*!< Do not optimize using masquerading */
127 #define LOCAL_BRIDGE          (1 << 5) /*!< Report back the "true" channel as being bridged to */
128 #define LOCAL_MOH_PASSTHRU    (1 << 6) /*!< Pass through music on hold start/stop frames */
129
130 static AST_LIST_HEAD_STATIC(locals, local_pvt);
131
132 /*! \brief Adds devicestate to local channels */
133 static int local_devicestate(void *data)
134 {
135         char *exten = ast_strdupa(data);
136         char *context = NULL, *opts = NULL;
137         int res;
138         struct local_pvt *lp;
139
140         if (!(context = strchr(exten, '@'))) {
141                 ast_log(LOG_WARNING, "Someone used Local/%s somewhere without a @context. This is bad.\n", exten);
142                 return AST_DEVICE_INVALID;      
143         }
144
145         *context++ = '\0';
146
147         /* Strip options if they exist */
148         if ((opts = strchr(context, '/')))
149                 *opts = '\0';
150
151         ast_debug(3, "Checking if extension %s@%s exists (devicestate)\n", exten, context);
152
153         res = ast_exists_extension(NULL, context, exten, 1, NULL);
154         if (!res)               
155                 return AST_DEVICE_INVALID;
156         
157         res = AST_DEVICE_NOT_INUSE;
158         AST_LIST_LOCK(&locals);
159         AST_LIST_TRAVERSE(&locals, lp, list) {
160                 if (!strcmp(exten, lp->exten) && !strcmp(context, lp->context) && lp->owner) {
161                         res = AST_DEVICE_INUSE;
162                         break;
163                 }
164         }
165         AST_LIST_UNLOCK(&locals);
166
167         return res;
168 }
169
170 /*!
171  * \note Assumes the pvt is no longer in the pvts list
172  */
173 static struct local_pvt *local_pvt_destroy(struct local_pvt *pvt)
174 {
175         ast_mutex_destroy(&pvt->lock);
176         ast_free(pvt);
177         return NULL;
178 }
179
180 /*! \brief Return the bridged channel of a Local channel */
181 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge)
182 {
183         struct local_pvt *p = bridge->tech_pvt;
184         struct ast_channel *bridged = bridge;
185
186         if (!p) {
187                 ast_debug(1, "Asked for bridged channel on '%s'/'%s', returning <none>\n",
188                         chan->name, bridge->name);
189                 return NULL;
190         }
191
192         ast_mutex_lock(&p->lock);
193
194         if (ast_test_flag(p, LOCAL_BRIDGE)) {
195                 /* Find the opposite channel */
196                 bridged = (bridge == p->owner ? p->chan : p->owner);
197                 
198                 /* Now see if the opposite channel is bridged to anything */
199                 if (!bridged) {
200                         bridged = bridge;
201                 } else if (bridged->_bridge) {
202                         bridged = bridged->_bridge;
203                 }
204         }
205
206         ast_mutex_unlock(&p->lock);
207
208         return bridged;
209 }
210
211 static int local_queue_frame(struct local_pvt *p, int isoutbound, struct ast_frame *f, 
212         struct ast_channel *us, int us_locked)
213 {
214         struct ast_channel *other = NULL;
215
216         /* Recalculate outbound channel */
217         other = isoutbound ? p->owner : p->chan;
218
219         if (!other) {
220                 return 0;
221         }
222
223         /* do not queue frame if generator is on both local channels */
224         if (us && us->generator && other->generator) {
225                 return 0;
226         }
227
228         /* Set glare detection */
229         ast_set_flag(p, LOCAL_GLARE_DETECT);
230
231         /* Ensure that we have both channels locked */
232         while (other && ast_channel_trylock(other)) {
233                 ast_mutex_unlock(&p->lock);
234                 if (us && us_locked) {
235                         do {
236                                 CHANNEL_DEADLOCK_AVOIDANCE(us);
237                         } while (ast_mutex_trylock(&p->lock));
238                 } else {
239                         usleep(1);
240                         ast_mutex_lock(&p->lock);
241                 }
242                 other = isoutbound ? p->owner : p->chan;
243         }
244
245         /* Since glare detection only occurs within this function, and because
246          * a pvt flag cannot be set without having the pvt lock, this is the only
247          * location where we could detect a cancelling of the queue. */
248         if (ast_test_flag(p, LOCAL_CANCEL_QUEUE)) {
249                 /* We had a glare on the hangup.  Forget all this business,
250                 return and destroy p.  */
251                 ast_mutex_unlock(&p->lock);
252                 p = local_pvt_destroy(p);
253                 if (other) {
254                         ast_channel_unlock(other);
255                 }
256                 return -1;
257         }
258
259         if (other) {
260                 if (f->frametype == AST_FRAME_CONTROL) {
261                         switch (f->subclass.integer) {
262                         case AST_CONTROL_RINGING:
263                                 ast_setstate(other, AST_STATE_RINGING);
264                                 break;
265                         case AST_CONTROL_ANSWER:
266                                 ast_setstate(other, AST_STATE_UP);
267                                 break;
268                         case AST_CONTROL_BUSY:
269                                 ast_setstate(other, AST_STATE_BUSY);
270                                 break;
271
272                         /* not going to handle these */
273                         case AST_CONTROL_HANGUP:
274                         case AST_CONTROL_RING:
275                         case AST_CONTROL_TAKEOFFHOOK:
276                         case AST_CONTROL_OFFHOOK:
277                         case AST_CONTROL_CONGESTION:
278                         case AST_CONTROL_FLASH:
279                         case AST_CONTROL_WINK:
280                         case AST_CONTROL_OPTION:
281                         case AST_CONTROL_RADIO_KEY:
282                         case AST_CONTROL_RADIO_UNKEY:
283                         case AST_CONTROL_PROGRESS:
284                         case AST_CONTROL_PROCEEDING:
285                         case AST_CONTROL_HOLD:
286                         case AST_CONTROL_UNHOLD:
287                         case AST_CONTROL_VIDUPDATE:
288                         case AST_CONTROL_SRCUPDATE:
289                         case AST_CONTROL_TRANSFER:
290                         case AST_CONTROL_CONNECTED_LINE:
291                         case AST_CONTROL_REDIRECTING:
292                         case AST_CONTROL_T38_PARAMETERS:
293                                 break;
294                         default:
295                                 /* since we're switching on an int, we can't rely on the compiler */
296                                 ast_log(LOG_WARNING, "New unhandled control frame added!!!\n");
297                         }
298                 }
299                 ast_queue_frame(other, f);
300                 ast_channel_unlock(other);
301         }
302
303         ast_clear_flag(p, LOCAL_GLARE_DETECT);
304
305         return 0;
306 }
307
308 static int local_answer(struct ast_channel *ast)
309 {
310         struct local_pvt *p = ast->tech_pvt;
311         int isoutbound;
312         int res = -1;
313
314         if (!p)
315                 return -1;
316
317         ast_mutex_lock(&p->lock);
318         isoutbound = IS_OUTBOUND(ast, p);
319         if (isoutbound) {
320                 /* Pass along answer since somebody answered us */
321                 struct ast_frame answer = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
322                 res = local_queue_frame(p, isoutbound, &answer, ast, 1);
323         } else
324                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
325         if (!res)
326                 ast_mutex_unlock(&p->lock);
327         return res;
328 }
329
330 static void check_bridge(struct local_pvt *p, int isoutbound)
331 {
332         struct ast_channel_monitor *tmp;
333         if (ast_test_flag(p, LOCAL_ALREADY_MASQED) || ast_test_flag(p, LOCAL_NO_OPTIMIZATION) || !p->chan || !p->owner || (p->chan->_bridge != ast_bridged_channel(p->chan)))
334                 return;
335
336         /* only do the masquerade if we are being called on the outbound channel,
337            if it has been bridged to another channel and if there are no pending
338            frames on the owner channel (because they would be transferred to the
339            outbound channel during the masquerade)
340         */
341         if (isoutbound && p->chan->_bridge /* Not ast_bridged_channel!  Only go one step! */ && AST_LIST_EMPTY(&p->owner->readq)) {
342                 /* Masquerade bridged channel into owner */
343                 /* Lock everything we need, one by one, and give up if
344                    we can't get everything.  Remember, we'll get another
345                    chance in just a little bit */
346                 if (!ast_channel_trylock(p->chan->_bridge)) {
347                         if (!ast_check_hangup(p->chan->_bridge)) {
348                                 if (!ast_channel_trylock(p->owner)) {
349                                         if (!ast_check_hangup(p->owner)) {
350                                                 if (p->owner->monitor && !p->chan->_bridge->monitor) {
351                                                         /* If a local channel is being monitored, we don't want a masquerade
352                                                          * to cause the monitor to go away. Since the masquerade swaps the monitors,
353                                                          * pre-swapping the monitors before the masquerade will ensure that the monitor
354                                                          * ends up where it is expected.
355                                                          */
356                                                         tmp = p->owner->monitor;
357                                                         p->owner->monitor = p->chan->_bridge->monitor;
358                                                         p->chan->_bridge->monitor = tmp;
359                                                 }
360                                                 if (p->chan->audiohooks) {
361                                                         struct ast_audiohook_list *audiohooks_swapper;
362                                                         audiohooks_swapper = p->chan->audiohooks;
363                                                         p->chan->audiohooks = p->owner->audiohooks;
364                                                         p->owner->audiohooks = audiohooks_swapper;
365                                                 }
366                                                 ast_app_group_update(p->chan, p->owner);
367                                                 ast_channel_masquerade(p->owner, p->chan->_bridge);
368                                                 ast_set_flag(p, LOCAL_ALREADY_MASQED);
369                                         }
370                                         ast_channel_unlock(p->owner);
371                                 }
372                                 ast_channel_unlock(p->chan->_bridge);
373                         }
374                 }
375         /* We only allow masquerading in one 'direction'... it's important to preserve the state
376            (group variables, etc.) that live on p->chan->_bridge (and were put there by the dialplan)
377            when the local channels go away.
378         */
379 #if 0
380         } else if (!isoutbound && p->owner && p->owner->_bridge && p->chan && AST_LIST_EMPTY(&p->chan->readq)) {
381                 /* Masquerade bridged channel into chan */
382                 if (!ast_mutex_trylock(&(p->owner->_bridge)->lock)) {
383                         if (!ast_check_hangup(p->owner->_bridge)) {
384                                 if (!ast_mutex_trylock(&p->chan->lock)) {
385                                         if (!ast_check_hangup(p->chan)) {
386                                                 ast_channel_masquerade(p->chan, p->owner->_bridge);
387                                                 ast_set_flag(p, LOCAL_ALREADY_MASQED);
388                                         }
389                                         ast_mutex_unlock(&p->chan->lock);
390                                 }
391                         }
392                         ast_mutex_unlock(&(p->owner->_bridge)->lock);
393                 }
394 #endif
395         }
396 }
397
398 static struct ast_frame  *local_read(struct ast_channel *ast)
399 {
400         return &ast_null_frame;
401 }
402
403 static int local_write(struct ast_channel *ast, struct ast_frame *f)
404 {
405         struct local_pvt *p = ast->tech_pvt;
406         int res = -1;
407         int isoutbound;
408
409         if (!p)
410                 return -1;
411
412         /* Just queue for delivery to the other side */
413         ast_mutex_lock(&p->lock);
414         isoutbound = IS_OUTBOUND(ast, p);
415         if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO))
416                 check_bridge(p, isoutbound);
417         if (!ast_test_flag(p, LOCAL_ALREADY_MASQED))
418                 res = local_queue_frame(p, isoutbound, f, ast, 1);
419         else {
420                 ast_debug(1, "Not posting to queue since already masked on '%s'\n", ast->name);
421                 res = 0;
422         }
423         if (!res)
424                 ast_mutex_unlock(&p->lock);
425         return res;
426 }
427
428 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
429 {
430         struct local_pvt *p = newchan->tech_pvt;
431
432         if (!p)
433                 return -1;
434
435         ast_mutex_lock(&p->lock);
436
437         if ((p->owner != oldchan) && (p->chan != oldchan)) {
438                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
439                 ast_mutex_unlock(&p->lock);
440                 return -1;
441         }
442         if (p->owner == oldchan)
443                 p->owner = newchan;
444         else
445                 p->chan = newchan;
446         ast_mutex_unlock(&p->lock);
447         return 0;
448 }
449
450 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
451 {
452         struct local_pvt *p = ast->tech_pvt;
453         int res = 0;
454         struct ast_frame f = { AST_FRAME_CONTROL, };
455         int isoutbound;
456
457         if (!p)
458                 return -1;
459
460         /* If this is an MOH hold or unhold, do it on the Local channel versus real channel */
461         if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_HOLD) {
462                 ast_moh_start(ast, data, NULL);
463         } else if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_UNHOLD) {
464                 ast_moh_stop(ast);
465         } else if (condition == AST_CONTROL_CONNECTED_LINE || condition == AST_CONTROL_REDIRECTING) {
466                 struct ast_channel *this_channel;
467                 struct ast_channel *the_other_channel;
468                 /* A connected line update frame may only contain a partial amount of data, such
469                  * as just a source, or just a ton, and not the full amount of information. However,
470                  * the collected information is all stored in the outgoing channel's connectedline
471                  * structure, so when receiving a connected line update on an outgoing local channel,
472                  * we need to transmit the collected connected line information instead of whatever
473                  * happens to be in this control frame. The same applies for redirecting information, which
474                  * is why it is handled here as well.*/
475                 ast_mutex_lock(&p->lock);
476                 isoutbound = IS_OUTBOUND(ast, p);
477                 if (isoutbound) {
478                         this_channel = p->chan;
479                         the_other_channel = p->owner;
480                 } else {
481                         this_channel = p->owner;
482                         the_other_channel = p->chan;
483                 }
484                 if (the_other_channel) {
485                         unsigned char frame_data[1024];
486                         if (condition == AST_CONTROL_CONNECTED_LINE) {
487                                 f.datalen = ast_connected_line_build_data(frame_data, sizeof(frame_data), &this_channel->connected);
488                         } else {
489                                 f.datalen = ast_redirecting_build_data(frame_data, sizeof(frame_data), &this_channel->redirecting);
490                         }
491                         f.subclass.integer = condition;
492                         f.data.ptr = frame_data;
493                         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 1))) {
494                                 ast_mutex_unlock(&p->lock);
495                         }
496                 } else {
497                         ast_mutex_unlock(&p->lock);
498                 }
499         } else {
500                 /* Queue up a frame representing the indication as a control frame */
501                 ast_mutex_lock(&p->lock);
502                 isoutbound = IS_OUTBOUND(ast, p);
503                 f.subclass.integer = condition;
504                 f.data.ptr = (void*)data;
505                 f.datalen = datalen;
506                 if (!(res = local_queue_frame(p, isoutbound, &f, ast, 1)))
507                         ast_mutex_unlock(&p->lock);
508         }
509
510         return res;
511 }
512
513 static int local_digit_begin(struct ast_channel *ast, char digit)
514 {
515         struct local_pvt *p = ast->tech_pvt;
516         int res = -1;
517         struct ast_frame f = { AST_FRAME_DTMF_BEGIN, };
518         int isoutbound;
519
520         if (!p)
521                 return -1;
522
523         ast_mutex_lock(&p->lock);
524         isoutbound = IS_OUTBOUND(ast, p);
525         f.subclass.integer = digit;
526         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
527                 ast_mutex_unlock(&p->lock);
528
529         return res;
530 }
531
532 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
533 {
534         struct local_pvt *p = ast->tech_pvt;
535         int res = -1;
536         struct ast_frame f = { AST_FRAME_DTMF_END, };
537         int isoutbound;
538
539         if (!p)
540                 return -1;
541
542         ast_mutex_lock(&p->lock);
543         isoutbound = IS_OUTBOUND(ast, p);
544         f.subclass.integer = digit;
545         f.len = duration;
546         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
547                 ast_mutex_unlock(&p->lock);
548
549         return res;
550 }
551
552 static int local_sendtext(struct ast_channel *ast, const char *text)
553 {
554         struct local_pvt *p = ast->tech_pvt;
555         int res = -1;
556         struct ast_frame f = { AST_FRAME_TEXT, };
557         int isoutbound;
558
559         if (!p)
560                 return -1;
561
562         ast_mutex_lock(&p->lock);
563         isoutbound = IS_OUTBOUND(ast, p);
564         f.data.ptr = (char *) text;
565         f.datalen = strlen(text) + 1;
566         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
567                 ast_mutex_unlock(&p->lock);
568         return res;
569 }
570
571 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
572 {
573         struct local_pvt *p = ast->tech_pvt;
574         int res = -1;
575         struct ast_frame f = { AST_FRAME_HTML, };
576         int isoutbound;
577
578         if (!p)
579                 return -1;
580         
581         ast_mutex_lock(&p->lock);
582         isoutbound = IS_OUTBOUND(ast, p);
583         f.subclass.integer = subclass;
584         f.data.ptr = (char *)data;
585         f.datalen = datalen;
586         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
587                 ast_mutex_unlock(&p->lock);
588         return res;
589 }
590
591 /*! \brief Initiate new call, part of PBX interface 
592  *      dest is the dial string */
593 static int local_call(struct ast_channel *ast, char *dest, int timeout)
594 {
595         struct local_pvt *p = ast->tech_pvt;
596         int res;
597         struct ast_var_t *varptr = NULL, *new;
598         size_t len, namelen;
599
600         if (!p)
601                 return -1;
602
603         /* If you value your sanity, please don't look at this code */
604 start_over:
605         while (ast_channel_trylock(p->chan)) {
606                 ast_channel_unlock(p->owner);
607                 usleep(1);
608                 ast_channel_lock(p->owner);
609         }
610
611         /* p->owner and p->chan are locked now. Let's get p locked */
612         if (ast_mutex_trylock(&p->lock)) {
613                 /* @#$&$@ */
614                 ast_channel_unlock(p->chan);
615                 ast_channel_unlock(p->owner);
616                 usleep(1);
617                 ast_channel_lock(p->owner);
618                 goto start_over;
619         }
620
621         /*
622          * Note that cid_num and cid_name aren't passed in the ast_channel_alloc
623          * call, so it's done here instead.
624          *
625          * All these failure points just return -1. The individual strings will
626          * be cleared when we destroy the channel.
627          */
628         if (p->owner->cid.cid_rdnis) {
629                 if (!(p->chan->cid.cid_rdnis = ast_strdup(p->owner->cid.cid_rdnis))) {
630                         ast_mutex_unlock(&p->lock);
631                         ast_channel_unlock(p->chan);
632                         return -1;
633                 }
634         }
635         ast_party_redirecting_copy(&p->chan->redirecting, &p->owner->redirecting);
636
637         if (p->owner->cid.cid_dnid) {
638                 if (!(p->chan->cid.cid_dnid = ast_strdup(p->owner->cid.cid_dnid))) {
639                         ast_mutex_unlock(&p->lock);
640                         ast_channel_unlock(p->chan);
641                         return -1;
642                 }
643         }
644         p->chan->cid.cid_tns = p->owner->cid.cid_tns;
645
646         ast_connected_line_copy_to_caller(&p->chan->cid, &p->owner->connected);
647         ast_connected_line_copy_from_caller(&p->chan->connected, &p->owner->cid);
648
649         ast_string_field_set(p->chan, language, p->owner->language);
650         ast_string_field_set(p->chan, accountcode, p->owner->accountcode);
651         ast_string_field_set(p->chan, musicclass, p->owner->musicclass);
652         ast_cdr_update(p->chan);
653         p->chan->cdrflags = p->owner->cdrflags;
654
655         if (!ast_exists_extension(NULL, p->chan->context, p->chan->exten, 1, p->owner->cid.cid_num)) {
656                 ast_log(LOG_NOTICE, "No such extension/context %s@%s while calling Local channel\n", p->chan->exten, p->chan->context);
657                 ast_mutex_unlock(&p->lock);
658                 ast_channel_unlock(p->chan);
659                 return -1;
660         }
661
662         /* Make sure we inherit the ANSWERED_ELSEWHERE flag if it's set on the queue/dial call request in the dialplan */
663         if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
664                 ast_set_flag(p->chan, AST_FLAG_ANSWERED_ELSEWHERE);
665         }
666
667         /* copy the channel variables from the incoming channel to the outgoing channel */
668         /* Note that due to certain assumptions, they MUST be in the same order */
669         AST_LIST_TRAVERSE(&p->owner->varshead, varptr, entries) {
670                 namelen = strlen(varptr->name);
671                 len = sizeof(struct ast_var_t) + namelen + strlen(varptr->value) + 2;
672                 if ((new = ast_calloc(1, len))) {
673                         memcpy(new, varptr, len);
674                         new->value = &(new->name[0]) + namelen + 1;
675                         AST_LIST_INSERT_TAIL(&p->chan->varshead, new, entries);
676                 }
677         }
678         ast_channel_datastore_inherit(p->owner, p->chan);
679
680         /* Start switch on sub channel */
681         if (!(res = ast_pbx_start(p->chan)))
682                 ast_set_flag(p, LOCAL_LAUNCHED_PBX);
683
684         ast_mutex_unlock(&p->lock);
685         ast_channel_unlock(p->chan);
686         return res;
687 }
688
689 /*! \brief Hangup a call through the local proxy channel */
690 static int local_hangup(struct ast_channel *ast)
691 {
692         struct local_pvt *p = ast->tech_pvt;
693         int isoutbound;
694         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = ast->hangupcause };
695         struct ast_channel *ochan = NULL;
696         int glaredetect = 0, res = 0;
697
698         if (!p)
699                 return -1;
700
701         ast_mutex_lock(&p->lock);
702
703         isoutbound = IS_OUTBOUND(ast, p);
704
705         if (p->chan && ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
706                 ast_set_flag(p->chan, AST_FLAG_ANSWERED_ELSEWHERE);
707                 ast_debug(2, "This local call has the ANSWERED_ELSEWHERE flag set.\n");
708         }
709
710         if (isoutbound) {
711                 const char *status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
712                 if ((status) && (p->owner)) {
713                         /* Deadlock avoidance */
714                         while (p->owner && ast_channel_trylock(p->owner)) {
715                                 ast_mutex_unlock(&p->lock);
716                                 if (ast) {
717                                         ast_channel_unlock(ast);
718                                 }
719                                 usleep(1);
720                                 if (ast) {
721                                         ast_channel_lock(ast);
722                                 }
723                                 ast_mutex_lock(&p->lock);
724                         }
725                         if (p->owner) {
726                                 pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
727                                 ast_channel_unlock(p->owner);
728                         }
729                 }
730                 p->chan = NULL;
731                 ast_clear_flag(p, LOCAL_LAUNCHED_PBX);
732                 ast_module_user_remove(p->u_chan);
733         } else {
734                 ast_module_user_remove(p->u_owner);
735                 while (p->chan && ast_channel_trylock(p->chan)) {
736                         DEADLOCK_AVOIDANCE(&p->lock);
737                 }
738                 p->owner = NULL;
739                 if (p->chan) {
740                         ast_queue_hangup(p->chan);
741                         ast_channel_unlock(p->chan);
742                 }
743         }
744         
745         ast->tech_pvt = NULL;
746         
747         if (!p->owner && !p->chan) {
748                 /* Okay, done with the private part now, too. */
749                 glaredetect = ast_test_flag(p, LOCAL_GLARE_DETECT);
750                 /* If we have a queue holding, don't actually destroy p yet, but
751                    let local_queue do it. */
752                 if (glaredetect)
753                         ast_set_flag(p, LOCAL_CANCEL_QUEUE);
754                 /* Remove from list */
755                 AST_LIST_LOCK(&locals);
756                 AST_LIST_REMOVE(&locals, p, list);
757                 AST_LIST_UNLOCK(&locals);
758                 ast_mutex_unlock(&p->lock);
759                 /* And destroy */
760                 if (!glaredetect) {
761                         p = local_pvt_destroy(p);
762                 }
763                 return 0;
764         }
765         if (p->chan && !ast_test_flag(p, LOCAL_LAUNCHED_PBX))
766                 /* Need to actually hangup since there is no PBX */
767                 ochan = p->chan;
768         else
769                 res = local_queue_frame(p, isoutbound, &f, NULL, 1);
770         if (!res)
771                 ast_mutex_unlock(&p->lock);
772         if (ochan)
773                 ast_hangup(ochan);
774         return 0;
775 }
776
777 /*! \brief Create a call structure */
778 static struct local_pvt *local_alloc(const char *data, int format)
779 {
780         struct local_pvt *tmp = NULL;
781         char *c = NULL, *opts = NULL;
782
783         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
784                 return NULL;
785
786         /* Initialize private structure information */
787         ast_mutex_init(&tmp->lock);
788         ast_copy_string(tmp->exten, data, sizeof(tmp->exten));
789
790         memcpy(&tmp->jb_conf, &g_jb_conf, sizeof(tmp->jb_conf));
791
792         /* Look for options */
793         if ((opts = strchr(tmp->exten, '/'))) {
794                 *opts++ = '\0';
795                 if (strchr(opts, 'n'))
796                         ast_set_flag(tmp, LOCAL_NO_OPTIMIZATION);
797                 if (strchr(opts, 'j')) {
798                         if (ast_test_flag(tmp, LOCAL_NO_OPTIMIZATION))
799                                 ast_set_flag(&tmp->jb_conf, AST_JB_ENABLED);
800                         else {
801                                 ast_log(LOG_ERROR, "You must use the 'n' option for chan_local "
802                                         "to use the 'j' option to enable the jitterbuffer\n");
803                         }
804                 }
805                 if (strchr(opts, 'b')) {
806                         ast_set_flag(tmp, LOCAL_BRIDGE);
807                 }
808                 if (strchr(opts, 'm')) {
809                         ast_set_flag(tmp, LOCAL_MOH_PASSTHRU);
810                 }
811         }
812
813         /* Look for a context */
814         if ((c = strchr(tmp->exten, '@')))
815                 *c++ = '\0';
816
817         ast_copy_string(tmp->context, c ? c : "default", sizeof(tmp->context));
818
819         tmp->reqformat = format;
820
821 #if 0
822         /* We can't do this check here, because we don't know the CallerID yet, and
823          * the CallerID could potentially affect what step is actually taken (or
824          * even if that step exists). */
825         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
826                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
827                 tmp = local_pvt_destroy(tmp);
828         } else {
829 #endif
830                 /* Add to list */
831                 AST_LIST_LOCK(&locals);
832                 AST_LIST_INSERT_HEAD(&locals, tmp, list);
833                 AST_LIST_UNLOCK(&locals);
834 #if 0
835         }
836 #endif
837         
838         return tmp;
839 }
840
841 /*! \brief Start new local channel */
842 static struct ast_channel *local_new(struct local_pvt *p, int state, const char *linkedid)
843 {
844         struct ast_channel *tmp = NULL, *tmp2 = NULL;
845         int randnum = ast_random() & 0xffff, fmt = 0;
846         const char *t;
847         int ama;
848
849         /* Allocate two new Asterisk channels */
850         /* safe accountcode */
851         if (p->owner && p->owner->accountcode)
852                 t = p->owner->accountcode;
853         else
854                 t = "";
855
856         if (p->owner)
857                 ama = p->owner->amaflags;
858         else
859                 ama = 0;
860         if (!(tmp = ast_channel_alloc(1, state, 0, 0, t, p->exten, p->context, linkedid, ama, "Local/%s@%s-%04x;1", p->exten, p->context, randnum)) 
861                 || !(tmp2 = ast_channel_alloc(1, AST_STATE_RING, 0, 0, t, p->exten, p->context, linkedid, ama, "Local/%s@%s-%04x;2", p->exten, p->context, randnum))) {
862                 if (tmp) {
863                         tmp = ast_channel_release(tmp);
864                 }
865                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
866                 return NULL;
867         }
868
869         tmp2->tech = tmp->tech = &local_tech;
870
871         tmp->nativeformats = p->reqformat;
872         tmp2->nativeformats = p->reqformat;
873
874         /* Determine our read/write format and set it on each channel */
875         fmt = ast_best_codec(p->reqformat);
876         tmp->writeformat = fmt;
877         tmp2->writeformat = fmt;
878         tmp->rawwriteformat = fmt;
879         tmp2->rawwriteformat = fmt;
880         tmp->readformat = fmt;
881         tmp2->readformat = fmt;
882         tmp->rawreadformat = fmt;
883         tmp2->rawreadformat = fmt;
884
885         tmp->tech_pvt = p;
886         tmp2->tech_pvt = p;
887
888         p->owner = tmp;
889         p->chan = tmp2;
890         p->u_owner = ast_module_user_add(p->owner);
891         p->u_chan = ast_module_user_add(p->chan);
892
893         ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
894         ast_copy_string(tmp2->context, p->context, sizeof(tmp2->context));
895         ast_copy_string(tmp2->exten, p->exten, sizeof(tmp->exten));
896         tmp->priority = 1;
897         tmp2->priority = 1;
898
899         ast_jb_configure(tmp, &p->jb_conf);
900
901         return tmp;
902 }
903
904 /*! \brief Part of PBX interface */
905 static struct ast_channel *local_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
906 {
907         struct local_pvt *p = NULL;
908         struct ast_channel *chan = NULL;
909
910         /* Allocate a new private structure and then Asterisk channel */
911         if ((p = local_alloc(data, format))) {
912                 if (!(chan = local_new(p, AST_STATE_DOWN, requestor ? requestor->linkedid : NULL))) {
913                         AST_LIST_LOCK(&locals);
914                         AST_LIST_REMOVE(&locals, p, list);
915                         AST_LIST_UNLOCK(&locals);
916                         p = local_pvt_destroy(p);
917                 }
918         }
919
920         return chan;
921 }
922
923 /*! \brief CLI command "local show channels" */
924 static char *locals_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
925 {
926         struct local_pvt *p = NULL;
927
928         switch (cmd) {
929         case CLI_INIT:
930                 e->command = "local show channels";
931                 e->usage =
932                         "Usage: local show channels\n"
933                         "       Provides summary information on active local proxy channels.\n";
934                 return NULL;
935         case CLI_GENERATE:
936                 return NULL;
937         }
938
939         if (a->argc != 3)
940                 return CLI_SHOWUSAGE;
941
942         AST_LIST_LOCK(&locals);
943         if (!AST_LIST_EMPTY(&locals)) {
944                 AST_LIST_TRAVERSE(&locals, p, list) {
945                         ast_mutex_lock(&p->lock);
946                         ast_cli(a->fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
947                         ast_mutex_unlock(&p->lock);
948                 }
949         } else
950                 ast_cli(a->fd, "No local channels in use\n");
951         AST_LIST_UNLOCK(&locals);
952
953         return CLI_SUCCESS;
954 }
955
956 static struct ast_cli_entry cli_local[] = {
957         AST_CLI_DEFINE(locals_show, "List status of local channels"),
958 };
959
960 /*! \brief Load module into PBX, register channel */
961 static int load_module(void)
962 {
963         /* Make sure we can register our channel type */
964         if (ast_channel_register(&local_tech)) {
965                 ast_log(LOG_ERROR, "Unable to register channel class 'Local'\n");
966                 return AST_MODULE_LOAD_FAILURE;
967         }
968         ast_cli_register_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
969         return AST_MODULE_LOAD_SUCCESS;
970 }
971
972 /*! \brief Unload the local proxy channel from Asterisk */
973 static int unload_module(void)
974 {
975         struct local_pvt *p = NULL;
976
977         /* First, take us out of the channel loop */
978         ast_cli_unregister_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
979         ast_channel_unregister(&local_tech);
980         if (!AST_LIST_LOCK(&locals)) {
981                 /* Hangup all interfaces if they have an owner */
982                 AST_LIST_TRAVERSE(&locals, p, list) {
983                         if (p->owner)
984                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
985                 }
986                 AST_LIST_UNLOCK(&locals);
987         } else {
988                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
989                 return -1;
990         }               
991         return 0;
992 }
993
994 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Local Proxy Channel (Note: used internally by other modules)");