Merged revisions 288748 via svnmerge from
[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 /*** DOCUMENTATION
53         <manager name="LocalOptimizeAway" language="en_US">
54                 <synopsis>
55                         Optimize away a local channel when possible.
56                 </synopsis>
57                 <syntax>
58                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
59                         <parameter name="Channel" required="true">
60                                 <para>The channel name to optimize away.</para>
61                         </parameter>
62                 </syntax>
63                 <description>
64                         <para>A local channel created with "/n" will not automatically optimize away.
65                         Calling this command on the local channel will clear that flag and allow
66                         it to optimize away if it's bridged or when it becomes bridged.</para>
67                 </description>
68         </manager>
69  ***/
70
71 static const char tdesc[] = "Local Proxy Channel Driver";
72
73 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
74
75 static struct ast_jb_conf g_jb_conf = {
76         .flags = 0,
77         .max_size = -1,
78         .resync_threshold = -1,
79         .impl = "",
80         .target_extra = -1,
81 };
82
83 static struct ast_channel *local_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
84 static int local_digit_begin(struct ast_channel *ast, char digit);
85 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
86 static int local_call(struct ast_channel *ast, char *dest, int timeout);
87 static int local_hangup(struct ast_channel *ast);
88 static int local_answer(struct ast_channel *ast);
89 static struct ast_frame *local_read(struct ast_channel *ast);
90 static int local_write(struct ast_channel *ast, struct ast_frame *f);
91 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
92 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
93 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
94 static int local_sendtext(struct ast_channel *ast, const char *text);
95 static int local_devicestate(void *data);
96 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge);
97 static int local_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
98 static int local_setoption(struct ast_channel *chan, int option, void *data, int datalen);
99
100 /* PBX interface structure for channel registration */
101 static const struct ast_channel_tech local_tech = {
102         .type = "Local",
103         .description = tdesc,
104         .capabilities = -1,
105         .requester = local_request,
106         .send_digit_begin = local_digit_begin,
107         .send_digit_end = local_digit_end,
108         .call = local_call,
109         .hangup = local_hangup,
110         .answer = local_answer,
111         .read = local_read,
112         .write = local_write,
113         .write_video = local_write,
114         .exception = local_read,
115         .indicate = local_indicate,
116         .fixup = local_fixup,
117         .send_html = local_sendhtml,
118         .send_text = local_sendtext,
119         .devicestate = local_devicestate,
120         .bridged_channel = local_bridgedchannel,
121         .queryoption = local_queryoption,
122         .setoption = local_setoption,
123 };
124
125 /*! \brief the local pvt structure for all channels
126
127         The local channel pvt has two ast_chan objects - the "owner" and the "next channel", the outbound channel
128
129         ast_chan owner -> local_pvt -> ast_chan chan -> yet-another-pvt-depending-on-channel-type
130
131 */
132 struct local_pvt {
133         ast_mutex_t lock;                       /*!< Channel private lock */
134         unsigned int flags;                     /*!< Private flags */
135         char context[AST_MAX_CONTEXT];          /*!< Context to call */
136         char exten[AST_MAX_EXTENSION];          /*!< Extension to call */
137         int reqformat;                          /*!< Requested format */
138         struct ast_jb_conf jb_conf;             /*!< jitterbuffer configuration for this local channel */
139         struct ast_channel *owner;              /*!< Master Channel - Bridging happens here */
140         struct ast_channel *chan;               /*!< Outbound channel - PBX is run here */
141         struct ast_module_user *u_owner;        /*!< reference to keep the module loaded while in use */
142         struct ast_module_user *u_chan;         /*!< reference to keep the module loaded while in use */
143         AST_LIST_ENTRY(local_pvt) list;         /*!< Next entity */
144 };
145
146 #define LOCAL_GLARE_DETECT    (1 << 0) /*!< Detect glare on hangup */
147 #define LOCAL_CANCEL_QUEUE    (1 << 1) /*!< Cancel queue */
148 #define LOCAL_ALREADY_MASQED  (1 << 2) /*!< Already masqueraded */
149 #define LOCAL_LAUNCHED_PBX    (1 << 3) /*!< PBX was launched */
150 #define LOCAL_NO_OPTIMIZATION (1 << 4) /*!< Do not optimize using masquerading */
151 #define LOCAL_BRIDGE          (1 << 5) /*!< Report back the "true" channel as being bridged to */
152 #define LOCAL_MOH_PASSTHRU    (1 << 6) /*!< Pass through music on hold start/stop frames */
153
154 static AST_LIST_HEAD_STATIC(locals, local_pvt);
155
156 static int local_setoption(struct ast_channel *chan, int option, void * data, int datalen)
157 {
158         int res;
159         struct local_pvt *p;
160         struct ast_channel *otherchan;
161         ast_chan_write_info_t *write_info;
162
163         if (option != AST_OPTION_CHANNEL_WRITE) {
164                 return -1;
165         }
166
167         write_info = data;
168
169         if (write_info->version != AST_CHAN_WRITE_INFO_T_VERSION) {
170                 ast_log(LOG_ERROR, "The chan_write_info_t type has changed, and this channel hasn't been updated!\n");
171                 return -1;
172         }
173
174
175 startover:
176         ast_channel_lock(chan);
177
178         p = chan->tech_pvt;
179         if (!p) {
180                 ast_channel_unlock(chan);
181                 ast_log(LOG_WARNING, "Could not update other side of %s, local_pvt went away.\n", chan->name);
182                 return -1;
183         }
184
185         while (ast_mutex_trylock(&p->lock)) {
186                 ast_channel_unlock(chan);
187                 sched_yield();
188                 ast_channel_lock(chan);
189                 p = chan->tech_pvt;
190                 if (!p) {
191                         ast_channel_unlock(chan);
192                         ast_log(LOG_WARNING, "Could not update other side of %s, local_pvt went away.\n", chan->name);
193                         return -1;
194                 }
195         }
196
197         otherchan = (write_info->chan == p->owner) ? p->chan : p->owner;
198
199         if (!otherchan || otherchan == write_info->chan) {
200                 ast_mutex_unlock(&p->lock);
201                 ast_channel_unlock(chan);
202                 ast_log(LOG_WARNING, "Could not update other side of %s, other side went away.\n", chan->name);
203                 return 0;
204         }
205
206         if (ast_channel_trylock(otherchan)) {
207                 ast_mutex_unlock(&p->lock);
208                 ast_channel_unlock(chan);
209                 goto startover;
210         }
211
212         res = write_info->write_fn(otherchan, write_info->function, write_info->data, write_info->value);
213
214         ast_channel_unlock(otherchan);
215         ast_mutex_unlock(&p->lock);
216         ast_channel_unlock(chan);
217
218         return res;
219 }
220
221 /*! \brief Adds devicestate to local channels */
222 static int local_devicestate(void *data)
223 {
224         char *exten = ast_strdupa(data);
225         char *context = NULL, *opts = NULL;
226         int res;
227         struct local_pvt *lp;
228
229         if (!(context = strchr(exten, '@'))) {
230                 ast_log(LOG_WARNING, "Someone used Local/%s somewhere without a @context. This is bad.\n", exten);
231                 return AST_DEVICE_INVALID;      
232         }
233
234         *context++ = '\0';
235
236         /* Strip options if they exist */
237         if ((opts = strchr(context, '/')))
238                 *opts = '\0';
239
240         ast_debug(3, "Checking if extension %s@%s exists (devicestate)\n", exten, context);
241
242         res = ast_exists_extension(NULL, context, exten, 1, NULL);
243         if (!res)               
244                 return AST_DEVICE_INVALID;
245         
246         res = AST_DEVICE_NOT_INUSE;
247         AST_LIST_LOCK(&locals);
248         AST_LIST_TRAVERSE(&locals, lp, list) {
249                 if (!strcmp(exten, lp->exten) && !strcmp(context, lp->context) && lp->owner) {
250                         res = AST_DEVICE_INUSE;
251                         break;
252                 }
253         }
254         AST_LIST_UNLOCK(&locals);
255
256         return res;
257 }
258
259 /*!
260  * \note Assumes the pvt is no longer in the pvts list
261  */
262 static struct local_pvt *local_pvt_destroy(struct local_pvt *pvt)
263 {
264         ast_mutex_destroy(&pvt->lock);
265         ast_free(pvt);
266         return NULL;
267 }
268
269 /*! \brief Return the bridged channel of a Local channel */
270 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge)
271 {
272         struct local_pvt *p = bridge->tech_pvt;
273         struct ast_channel *bridged = bridge;
274
275         if (!p) {
276                 ast_debug(1, "Asked for bridged channel on '%s'/'%s', returning <none>\n",
277                         chan->name, bridge->name);
278                 return NULL;
279         }
280
281         ast_mutex_lock(&p->lock);
282
283         if (ast_test_flag(p, LOCAL_BRIDGE)) {
284                 /* Find the opposite channel */
285                 bridged = (bridge == p->owner ? p->chan : p->owner);
286                 
287                 /* Now see if the opposite channel is bridged to anything */
288                 if (!bridged) {
289                         bridged = bridge;
290                 } else if (bridged->_bridge) {
291                         bridged = bridged->_bridge;
292                 }
293         }
294
295         ast_mutex_unlock(&p->lock);
296
297         return bridged;
298 }
299
300 static int local_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
301 {
302         struct local_pvt *p = ast->tech_pvt;
303         struct ast_channel *chan, *bridged;
304         int res;
305
306         if (!p) {
307                 return -1;
308         }
309
310         if (option != AST_OPTION_T38_STATE) {
311                 /* AST_OPTION_T38_STATE is the only supported option at this time */
312                 return -1;
313         }
314
315         ast_mutex_lock(&p->lock);
316         chan = IS_OUTBOUND(ast, p) ? p->owner : p->chan;
317
318 try_again:
319         if (!chan) {
320                 ast_mutex_unlock(&p->lock);
321                 return -1;
322         }
323
324         if (ast_channel_trylock(chan)) {
325                 DEADLOCK_AVOIDANCE(&p->lock);
326                 chan = IS_OUTBOUND(ast, p) ? p->owner : p->chan;
327                 goto try_again;
328         }
329
330         bridged = ast_bridged_channel(chan);
331         if (!bridged) {
332                 /* can't query channel unless we are bridged */
333                 ast_mutex_unlock(&p->lock);
334                 ast_channel_unlock(chan);
335                 return -1;
336         }
337
338         if (ast_channel_trylock(bridged)) {
339                 ast_channel_unlock(chan);
340                 DEADLOCK_AVOIDANCE(&p->lock);
341                 chan = IS_OUTBOUND(ast, p) ? p->owner : p->chan;
342                 goto try_again;
343         }
344
345         res = ast_channel_queryoption(bridged, option, data, datalen, 0);
346         ast_mutex_unlock(&p->lock);
347         ast_channel_unlock(chan);
348         ast_channel_unlock(bridged);
349         return res;
350 }
351
352 static int local_queue_frame(struct local_pvt *p, int isoutbound, struct ast_frame *f, 
353         struct ast_channel *us, int us_locked)
354 {
355         struct ast_channel *other = NULL;
356
357         /* Recalculate outbound channel */
358         other = isoutbound ? p->owner : p->chan;
359
360         if (!other) {
361                 return 0;
362         }
363
364         /* do not queue frame if generator is on both local channels */
365         if (us && us->generator && other->generator) {
366                 return 0;
367         }
368
369         /* Set glare detection */
370         ast_set_flag(p, LOCAL_GLARE_DETECT);
371
372         /* Ensure that we have both channels locked */
373         while (other && ast_channel_trylock(other)) {
374                 int res;
375                 if ((res = ast_mutex_unlock(&p->lock))) {
376                         ast_log(LOG_ERROR, "chan_local bug! '&p->lock' was not locked when entering local_queue_frame! (%s)\n", strerror(res));
377                         return -1;
378                 }
379                 if (us && us_locked) {
380                         do {
381                                 CHANNEL_DEADLOCK_AVOIDANCE(us);
382                         } while (ast_mutex_trylock(&p->lock));
383                 } else {
384                         usleep(1);
385                         ast_mutex_lock(&p->lock);
386                 }
387                 other = isoutbound ? p->owner : p->chan;
388         }
389
390         /* Since glare detection only occurs within this function, and because
391          * a pvt flag cannot be set without having the pvt lock, this is the only
392          * location where we could detect a cancelling of the queue. */
393         if (ast_test_flag(p, LOCAL_CANCEL_QUEUE)) {
394                 /* We had a glare on the hangup.  Forget all this business,
395                 return and destroy p.  */
396                 ast_mutex_unlock(&p->lock);
397                 p = local_pvt_destroy(p);
398                 if (other) {
399                         ast_channel_unlock(other);
400                 }
401                 return -1;
402         }
403
404         if (other) {
405                 if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_RINGING) {
406                         ast_setstate(other, AST_STATE_RINGING);
407                 }
408                 ast_queue_frame(other, f);
409                 ast_channel_unlock(other);
410         }
411
412         ast_clear_flag(p, LOCAL_GLARE_DETECT);
413
414         return 0;
415 }
416
417 static int local_answer(struct ast_channel *ast)
418 {
419         struct local_pvt *p = ast->tech_pvt;
420         int isoutbound;
421         int res = -1;
422
423         if (!p)
424                 return -1;
425
426         ast_mutex_lock(&p->lock);
427         isoutbound = IS_OUTBOUND(ast, p);
428         if (isoutbound) {
429                 /* Pass along answer since somebody answered us */
430                 struct ast_frame answer = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
431                 res = local_queue_frame(p, isoutbound, &answer, ast, 1);
432         } else
433                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
434         if (!res)
435                 ast_mutex_unlock(&p->lock);
436         return res;
437 }
438
439 /*!
440  * \internal
441  * \note This function assumes that we're only called from the "outbound" local channel side
442  */
443 static void check_bridge(struct local_pvt *p)
444 {
445         struct ast_channel_monitor *tmp;
446         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)))
447                 return;
448
449         /* only do the masquerade if we are being called on the outbound channel,
450            if it has been bridged to another channel and if there are no pending
451            frames on the owner channel (because they would be transferred to the
452            outbound channel during the masquerade)
453         */
454         if (p->chan->_bridge /* Not ast_bridged_channel!  Only go one step! */ && AST_LIST_EMPTY(&p->owner->readq)) {
455                 /* Masquerade bridged channel into owner */
456                 /* Lock everything we need, one by one, and give up if
457                    we can't get everything.  Remember, we'll get another
458                    chance in just a little bit */
459                 if (!ast_channel_trylock(p->chan->_bridge)) {
460                         if (!ast_check_hangup(p->chan->_bridge)) {
461                                 if (!ast_channel_trylock(p->owner)) {
462                                         if (!ast_check_hangup(p->owner)) {
463                                                 if (p->owner->monitor && !p->chan->_bridge->monitor) {
464                                                         /* If a local channel is being monitored, we don't want a masquerade
465                                                          * to cause the monitor to go away. Since the masquerade swaps the monitors,
466                                                          * pre-swapping the monitors before the masquerade will ensure that the monitor
467                                                          * ends up where it is expected.
468                                                          */
469                                                         tmp = p->owner->monitor;
470                                                         p->owner->monitor = p->chan->_bridge->monitor;
471                                                         p->chan->_bridge->monitor = tmp;
472                                                 }
473                                                 if (p->chan->audiohooks) {
474                                                         struct ast_audiohook_list *audiohooks_swapper;
475                                                         audiohooks_swapper = p->chan->audiohooks;
476                                                         p->chan->audiohooks = p->owner->audiohooks;
477                                                         p->owner->audiohooks = audiohooks_swapper;
478                                                 }
479
480                                                 /* If any Caller ID was set, preserve it after masquerade like above. We must check
481                                                  * to see if Caller ID was set because otherwise we'll mistakingly copy info not
482                                                  * set from the dialplan and will overwrite the real channel Caller ID. The reason
483                                                  * for this whole preswapping action is because the Caller ID is set on the channel
484                                                  * thread (which is the to be masqueraded away local channel) before both local
485                                                  * channels are optimized away.
486                                                  */
487                                                 if (p->owner->caller.id.name.valid || p->owner->caller.id.number.valid
488                                                         || p->owner->caller.id.subaddress.valid || p->owner->caller.ani.name.valid
489                                                         || p->owner->caller.ani.number.valid || p->owner->caller.ani.subaddress.valid) {
490                                                         struct ast_party_caller tmp;
491                                                         tmp = p->owner->caller;
492                                                         p->owner->caller = p->chan->_bridge->caller;
493                                                         p->chan->_bridge->caller = tmp;
494                                                 }
495                                                 if (p->owner->redirecting.from.name.valid || p->owner->redirecting.from.number.valid
496                                                         || p->owner->redirecting.from.subaddress.valid || p->owner->redirecting.to.name.valid
497                                                         || p->owner->redirecting.to.number.valid || p->owner->redirecting.to.subaddress.valid) {
498                                                         struct ast_party_redirecting tmp;
499                                                         tmp = p->owner->redirecting;
500                                                         p->owner->redirecting = p->chan->_bridge->redirecting;
501                                                         p->chan->_bridge->redirecting = tmp;
502                                                 }
503                                                 if (p->owner->dialed.number.str || p->owner->dialed.subaddress.valid) {
504                                                         struct ast_party_dialed tmp;
505                                                         tmp = p->owner->dialed;
506                                                         p->owner->dialed = p->chan->_bridge->dialed;
507                                                         p->chan->_bridge->dialed = tmp;
508                                                 }
509
510
511                                                 ast_app_group_update(p->chan, p->owner);
512                                                 ast_channel_masquerade(p->owner, p->chan->_bridge);
513                                                 ast_set_flag(p, LOCAL_ALREADY_MASQED);
514                                         }
515                                         ast_channel_unlock(p->owner);
516                                 }
517                                 ast_channel_unlock(p->chan->_bridge);
518                         }
519                 }
520         }
521 }
522
523 static struct ast_frame  *local_read(struct ast_channel *ast)
524 {
525         return &ast_null_frame;
526 }
527
528 static int local_write(struct ast_channel *ast, struct ast_frame *f)
529 {
530         struct local_pvt *p = ast->tech_pvt;
531         int res = -1;
532         int isoutbound;
533
534         if (!p)
535                 return -1;
536
537         /* Just queue for delivery to the other side */
538         ast_mutex_lock(&p->lock);
539         isoutbound = IS_OUTBOUND(ast, p);
540         if (isoutbound && f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO))
541                 check_bridge(p);
542         if (!ast_test_flag(p, LOCAL_ALREADY_MASQED))
543                 res = local_queue_frame(p, isoutbound, f, ast, 1);
544         else {
545                 ast_debug(1, "Not posting to queue since already masked on '%s'\n", ast->name);
546                 res = 0;
547         }
548         if (!res)
549                 ast_mutex_unlock(&p->lock);
550         return res;
551 }
552
553 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
554 {
555         struct local_pvt *p = newchan->tech_pvt;
556
557         if (!p)
558                 return -1;
559
560         ast_mutex_lock(&p->lock);
561
562         if ((p->owner != oldchan) && (p->chan != oldchan)) {
563                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
564                 ast_mutex_unlock(&p->lock);
565                 return -1;
566         }
567         if (p->owner == oldchan)
568                 p->owner = newchan;
569         else
570                 p->chan = newchan;
571
572         /* Do not let a masquerade cause a Local channel to be bridged to itself! */
573         if (!ast_check_hangup(newchan) && (p->owner->_bridge == p->chan || p->chan->_bridge == p->owner)) {
574                 ast_log(LOG_WARNING, "You can not bridge a Local channel to itself!\n");
575                 ast_mutex_unlock(&p->lock);
576                 ast_queue_hangup(newchan);
577                 return -1;
578         }
579
580         ast_mutex_unlock(&p->lock);
581         return 0;
582 }
583
584 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
585 {
586         struct local_pvt *p = ast->tech_pvt;
587         int res = 0;
588         struct ast_frame f = { AST_FRAME_CONTROL, };
589         int isoutbound;
590
591         if (!p)
592                 return -1;
593
594         /* If this is an MOH hold or unhold, do it on the Local channel versus real channel */
595         if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_HOLD) {
596                 ast_moh_start(ast, data, NULL);
597         } else if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_UNHOLD) {
598                 ast_moh_stop(ast);
599         } else if (condition == AST_CONTROL_CONNECTED_LINE || condition == AST_CONTROL_REDIRECTING) {
600                 struct ast_channel *this_channel;
601                 struct ast_channel *the_other_channel;
602                 /* A connected line update frame may only contain a partial amount of data, such
603                  * as just a source, or just a ton, and not the full amount of information. However,
604                  * the collected information is all stored in the outgoing channel's connectedline
605                  * structure, so when receiving a connected line update on an outgoing local channel,
606                  * we need to transmit the collected connected line information instead of whatever
607                  * happens to be in this control frame. The same applies for redirecting information, which
608                  * is why it is handled here as well.*/
609                 ast_mutex_lock(&p->lock);
610                 isoutbound = IS_OUTBOUND(ast, p);
611                 if (isoutbound) {
612                         this_channel = p->chan;
613                         the_other_channel = p->owner;
614                 } else {
615                         this_channel = p->owner;
616                         the_other_channel = p->chan;
617                 }
618                 if (the_other_channel) {
619                         unsigned char frame_data[1024];
620                         if (condition == AST_CONTROL_CONNECTED_LINE) {
621                                 if (isoutbound) {
622                                         ast_connected_line_copy_to_caller(&the_other_channel->caller, &this_channel->connected);
623                                 }
624                                 f.datalen = ast_connected_line_build_data(frame_data, sizeof(frame_data), &this_channel->connected, NULL);
625                         } else {
626                                 f.datalen = ast_redirecting_build_data(frame_data, sizeof(frame_data), &this_channel->redirecting, NULL);
627                         }
628                         f.subclass.integer = condition;
629                         f.data.ptr = frame_data;
630                         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 1))) {
631                                 ast_mutex_unlock(&p->lock);
632                         }
633                 } else {
634                         ast_mutex_unlock(&p->lock);
635                 }
636         } else {
637                 /* Queue up a frame representing the indication as a control frame */
638                 ast_mutex_lock(&p->lock);
639                 isoutbound = IS_OUTBOUND(ast, p);
640                 f.subclass.integer = condition;
641                 f.data.ptr = (void*)data;
642                 f.datalen = datalen;
643                 if (!(res = local_queue_frame(p, isoutbound, &f, ast, 1)))
644                         ast_mutex_unlock(&p->lock);
645         }
646
647         return res;
648 }
649
650 static int local_digit_begin(struct ast_channel *ast, char digit)
651 {
652         struct local_pvt *p = ast->tech_pvt;
653         int res = -1;
654         struct ast_frame f = { AST_FRAME_DTMF_BEGIN, };
655         int isoutbound;
656
657         if (!p)
658                 return -1;
659
660         ast_mutex_lock(&p->lock);
661         isoutbound = IS_OUTBOUND(ast, p);
662         f.subclass.integer = digit;
663         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
664                 ast_mutex_unlock(&p->lock);
665
666         return res;
667 }
668
669 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
670 {
671         struct local_pvt *p = ast->tech_pvt;
672         int res = -1;
673         struct ast_frame f = { AST_FRAME_DTMF_END, };
674         int isoutbound;
675
676         if (!p)
677                 return -1;
678
679         ast_mutex_lock(&p->lock);
680         isoutbound = IS_OUTBOUND(ast, p);
681         f.subclass.integer = digit;
682         f.len = duration;
683         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
684                 ast_mutex_unlock(&p->lock);
685
686         return res;
687 }
688
689 static int local_sendtext(struct ast_channel *ast, const char *text)
690 {
691         struct local_pvt *p = ast->tech_pvt;
692         int res = -1;
693         struct ast_frame f = { AST_FRAME_TEXT, };
694         int isoutbound;
695
696         if (!p)
697                 return -1;
698
699         ast_mutex_lock(&p->lock);
700         isoutbound = IS_OUTBOUND(ast, p);
701         f.data.ptr = (char *) text;
702         f.datalen = strlen(text) + 1;
703         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
704                 ast_mutex_unlock(&p->lock);
705         return res;
706 }
707
708 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
709 {
710         struct local_pvt *p = ast->tech_pvt;
711         int res = -1;
712         struct ast_frame f = { AST_FRAME_HTML, };
713         int isoutbound;
714
715         if (!p)
716                 return -1;
717         
718         ast_mutex_lock(&p->lock);
719         isoutbound = IS_OUTBOUND(ast, p);
720         f.subclass.integer = subclass;
721         f.data.ptr = (char *)data;
722         f.datalen = datalen;
723         if (!(res = local_queue_frame(p, isoutbound, &f, ast, 0)))
724                 ast_mutex_unlock(&p->lock);
725         return res;
726 }
727
728 /*! \brief Initiate new call, part of PBX interface 
729  *      dest is the dial string */
730 static int local_call(struct ast_channel *ast, char *dest, int timeout)
731 {
732         struct local_pvt *p = ast->tech_pvt;
733         int res;
734         struct ast_var_t *varptr = NULL, *new;
735         size_t len, namelen;
736         char *reduced_dest = ast_strdupa(dest);
737         char *slash;
738
739         if (!p)
740                 return -1;
741
742         /* If you value your sanity, please don't look at this code */
743 start_over:
744         while (ast_channel_trylock(p->chan)) {
745                 ast_channel_unlock(p->owner);
746                 usleep(1);
747                 ast_channel_lock(p->owner);
748         }
749
750         /* p->owner and p->chan are locked now. Let's get p locked */
751         if (ast_mutex_trylock(&p->lock)) {
752                 /* @#$&$@ */
753                 ast_channel_unlock(p->chan);
754                 ast_channel_unlock(p->owner);
755                 usleep(1);
756                 ast_channel_lock(p->owner);
757                 goto start_over;
758         }
759
760         /*
761          * Note that cid_num and cid_name aren't passed in the ast_channel_alloc
762          * call, so it's done here instead.
763          *
764          * All these failure points just return -1. The individual strings will
765          * be cleared when we destroy the channel.
766          */
767         ast_party_redirecting_copy(&p->chan->redirecting, &p->owner->redirecting);
768
769         ast_party_dialed_copy(&p->chan->dialed, &p->owner->dialed);
770
771         ast_connected_line_copy_to_caller(&p->chan->caller, &p->owner->connected);
772         ast_connected_line_copy_from_caller(&p->chan->connected, &p->owner->caller);
773
774         ast_string_field_set(p->chan, language, p->owner->language);
775         ast_string_field_set(p->chan, accountcode, p->owner->accountcode);
776         ast_string_field_set(p->chan, musicclass, p->owner->musicclass);
777         ast_cdr_update(p->chan);
778
779         ast_channel_cc_params_init(p->chan, ast_channel_get_cc_config_params(p->owner));
780
781         if (!ast_exists_extension(NULL, p->chan->context, p->chan->exten, 1,
782                 S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
783                 ast_log(LOG_NOTICE, "No such extension/context %s@%s while calling Local channel\n", p->chan->exten, p->chan->context);
784                 ast_mutex_unlock(&p->lock);
785                 ast_channel_unlock(p->chan);
786                 return -1;
787         }
788
789         /* Make sure we inherit the ANSWERED_ELSEWHERE flag if it's set on the queue/dial call request in the dialplan */
790         if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
791                 ast_set_flag(p->chan, AST_FLAG_ANSWERED_ELSEWHERE);
792         }
793
794         /* copy the channel variables from the incoming channel to the outgoing channel */
795         /* Note that due to certain assumptions, they MUST be in the same order */
796         AST_LIST_TRAVERSE(&p->owner->varshead, varptr, entries) {
797                 namelen = strlen(varptr->name);
798                 len = sizeof(struct ast_var_t) + namelen + strlen(varptr->value) + 2;
799                 if ((new = ast_calloc(1, len))) {
800                         memcpy(new, varptr, len);
801                         new->value = &(new->name[0]) + namelen + 1;
802                         AST_LIST_INSERT_TAIL(&p->chan->varshead, new, entries);
803                 }
804         }
805         ast_channel_datastore_inherit(p->owner, p->chan);
806         /* If the local channel has /n or /b on the end of it,
807          * we need to lop that off for our argument to setting
808          * up the CC_INTERFACES variable
809          */
810         if ((slash = strrchr(reduced_dest, '/'))) {
811                 *slash = '\0';
812         }
813         ast_set_cc_interfaces_chanvar(p->chan, reduced_dest);
814
815         /* Start switch on sub channel */
816         if (!(res = ast_pbx_start(p->chan)))
817                 ast_set_flag(p, LOCAL_LAUNCHED_PBX);
818
819         ast_mutex_unlock(&p->lock);
820         ast_channel_unlock(p->chan);
821         return res;
822 }
823
824 /*! \brief Hangup a call through the local proxy channel */
825 static int local_hangup(struct ast_channel *ast)
826 {
827         struct local_pvt *p = ast->tech_pvt;
828         int isoutbound;
829         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = ast->hangupcause };
830         struct ast_channel *ochan = NULL;
831         int glaredetect = 0, res = 0;
832
833         if (!p)
834                 return -1;
835
836         ast_mutex_lock(&p->lock);
837
838         isoutbound = IS_OUTBOUND(ast, p);
839
840         if (p->chan && ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
841                 ast_set_flag(p->chan, AST_FLAG_ANSWERED_ELSEWHERE);
842                 ast_debug(2, "This local call has the ANSWERED_ELSEWHERE flag set.\n");
843         }
844
845         if (isoutbound) {
846                 const char *status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
847                 if ((status) && (p->owner)) {
848                         /* Deadlock avoidance */
849                         while (p->owner && ast_channel_trylock(p->owner)) {
850                                 ast_mutex_unlock(&p->lock);
851                                 if (p->chan) {
852                                         ast_channel_unlock(p->chan);
853                                 }
854                                 usleep(1);
855                                 if (p->chan) {
856                                         ast_channel_lock(p->chan);
857                                 }
858                                 ast_mutex_lock(&p->lock);
859                         }
860                         if (p->owner) {
861                                 pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
862                                 ast_channel_unlock(p->owner);
863                         }
864                 }
865                 p->chan = NULL;
866                 ast_clear_flag(p, LOCAL_LAUNCHED_PBX);
867                 ast_module_user_remove(p->u_chan);
868         } else {
869                 ast_module_user_remove(p->u_owner);
870                 while (p->chan && ast_channel_trylock(p->chan)) {
871                                 ast_mutex_unlock(&p->lock);
872                                 if (p->owner) {
873                                         ast_channel_unlock(p->owner);
874                                 }
875                                 usleep(1);
876                                 if (p->owner) {
877                                         ast_channel_lock(p->owner);
878                                 }
879                                 ast_mutex_lock(&p->lock);
880                 }
881
882                 p->owner = NULL;
883                 if (p->chan) {
884                         ast_queue_hangup(p->chan);
885                         ast_channel_unlock(p->chan);
886                 }
887         }
888         
889         ast->tech_pvt = NULL;
890         
891         if (!p->owner && !p->chan) {
892                 /* Okay, done with the private part now, too. */
893                 glaredetect = ast_test_flag(p, LOCAL_GLARE_DETECT);
894                 /* If we have a queue holding, don't actually destroy p yet, but
895                    let local_queue do it. */
896                 if (glaredetect)
897                         ast_set_flag(p, LOCAL_CANCEL_QUEUE);
898                 /* Remove from list */
899                 AST_LIST_LOCK(&locals);
900                 AST_LIST_REMOVE(&locals, p, list);
901                 AST_LIST_UNLOCK(&locals);
902                 ast_mutex_unlock(&p->lock);
903                 /* And destroy */
904                 if (!glaredetect) {
905                         p = local_pvt_destroy(p);
906                 }
907                 return 0;
908         }
909         if (p->chan && !ast_test_flag(p, LOCAL_LAUNCHED_PBX))
910                 /* Need to actually hangup since there is no PBX */
911                 ochan = p->chan;
912         else
913                 res = local_queue_frame(p, isoutbound, &f, NULL, 1);
914         if (!res)
915                 ast_mutex_unlock(&p->lock);
916         if (ochan)
917                 ast_hangup(ochan);
918         return 0;
919 }
920
921 /*! \brief Create a call structure */
922 static struct local_pvt *local_alloc(const char *data, int format)
923 {
924         struct local_pvt *tmp = NULL;
925         char *c = NULL, *opts = NULL;
926
927         if (!(tmp = ast_calloc(1, sizeof(*tmp))))
928                 return NULL;
929
930         /* Initialize private structure information */
931         ast_mutex_init(&tmp->lock);
932         ast_copy_string(tmp->exten, data, sizeof(tmp->exten));
933
934         memcpy(&tmp->jb_conf, &g_jb_conf, sizeof(tmp->jb_conf));
935
936         /* Look for options */
937         if ((opts = strchr(tmp->exten, '/'))) {
938                 *opts++ = '\0';
939                 if (strchr(opts, 'n'))
940                         ast_set_flag(tmp, LOCAL_NO_OPTIMIZATION);
941                 if (strchr(opts, 'j')) {
942                         if (ast_test_flag(tmp, LOCAL_NO_OPTIMIZATION))
943                                 ast_set_flag(&tmp->jb_conf, AST_JB_ENABLED);
944                         else {
945                                 ast_log(LOG_ERROR, "You must use the 'n' option for chan_local "
946                                         "to use the 'j' option to enable the jitterbuffer\n");
947                         }
948                 }
949                 if (strchr(opts, 'b')) {
950                         ast_set_flag(tmp, LOCAL_BRIDGE);
951                 }
952                 if (strchr(opts, 'm')) {
953                         ast_set_flag(tmp, LOCAL_MOH_PASSTHRU);
954                 }
955         }
956
957         /* Look for a context */
958         if ((c = strchr(tmp->exten, '@')))
959                 *c++ = '\0';
960
961         ast_copy_string(tmp->context, c ? c : "default", sizeof(tmp->context));
962
963         tmp->reqformat = format;
964
965 #if 0
966         /* We can't do this check here, because we don't know the CallerID yet, and
967          * the CallerID could potentially affect what step is actually taken (or
968          * even if that step exists). */
969         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
970                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
971                 tmp = local_pvt_destroy(tmp);
972         } else {
973 #endif
974                 /* Add to list */
975                 AST_LIST_LOCK(&locals);
976                 AST_LIST_INSERT_HEAD(&locals, tmp, list);
977                 AST_LIST_UNLOCK(&locals);
978 #if 0
979         }
980 #endif
981         
982         return tmp;
983 }
984
985 /*! \brief Start new local channel */
986 static struct ast_channel *local_new(struct local_pvt *p, int state, const char *linkedid)
987 {
988         struct ast_channel *tmp = NULL, *tmp2 = NULL;
989         int randnum = ast_random() & 0xffff, fmt = 0;
990         const char *t;
991         int ama;
992
993         /* Allocate two new Asterisk channels */
994         /* safe accountcode */
995         if (p->owner && p->owner->accountcode)
996                 t = p->owner->accountcode;
997         else
998                 t = "";
999
1000         if (p->owner)
1001                 ama = p->owner->amaflags;
1002         else
1003                 ama = 0;
1004         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)) 
1005                 || !(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))) {
1006                 if (tmp) {
1007                         tmp = ast_channel_release(tmp);
1008                 }
1009                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
1010                 return NULL;
1011         }
1012
1013         tmp2->tech = tmp->tech = &local_tech;
1014
1015         tmp->nativeformats = p->reqformat;
1016         tmp2->nativeformats = p->reqformat;
1017
1018         /* Determine our read/write format and set it on each channel */
1019         fmt = ast_best_codec(p->reqformat);
1020         tmp->writeformat = fmt;
1021         tmp2->writeformat = fmt;
1022         tmp->rawwriteformat = fmt;
1023         tmp2->rawwriteformat = fmt;
1024         tmp->readformat = fmt;
1025         tmp2->readformat = fmt;
1026         tmp->rawreadformat = fmt;
1027         tmp2->rawreadformat = fmt;
1028
1029         tmp->tech_pvt = p;
1030         tmp2->tech_pvt = p;
1031
1032         p->owner = tmp;
1033         p->chan = tmp2;
1034         p->u_owner = ast_module_user_add(p->owner);
1035         p->u_chan = ast_module_user_add(p->chan);
1036
1037         ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
1038         ast_copy_string(tmp2->context, p->context, sizeof(tmp2->context));
1039         ast_copy_string(tmp2->exten, p->exten, sizeof(tmp->exten));
1040         tmp->priority = 1;
1041         tmp2->priority = 1;
1042
1043         ast_jb_configure(tmp, &p->jb_conf);
1044
1045         return tmp;
1046 }
1047
1048 /*! \brief Part of PBX interface */
1049 static struct ast_channel *local_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
1050 {
1051         struct local_pvt *p = NULL;
1052         struct ast_channel *chan = NULL;
1053
1054         /* Allocate a new private structure and then Asterisk channel */
1055         if ((p = local_alloc(data, format))) {
1056                 if (!(chan = local_new(p, AST_STATE_DOWN, requestor ? requestor->linkedid : NULL))) {
1057                         AST_LIST_LOCK(&locals);
1058                         AST_LIST_REMOVE(&locals, p, list);
1059                         AST_LIST_UNLOCK(&locals);
1060                         p = local_pvt_destroy(p);
1061                 }
1062                 if (chan && ast_channel_cc_params_init(chan, requestor ? ast_channel_get_cc_config_params((struct ast_channel *)requestor) : NULL)) {
1063                         chan = ast_channel_release(chan);
1064                         p = local_pvt_destroy(p);
1065                 }
1066         }
1067
1068         return chan;
1069 }
1070
1071 /*! \brief CLI command "local show channels" */
1072 static char *locals_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1073 {
1074         struct local_pvt *p = NULL;
1075
1076         switch (cmd) {
1077         case CLI_INIT:
1078                 e->command = "local show channels";
1079                 e->usage =
1080                         "Usage: local show channels\n"
1081                         "       Provides summary information on active local proxy channels.\n";
1082                 return NULL;
1083         case CLI_GENERATE:
1084                 return NULL;
1085         }
1086
1087         if (a->argc != 3)
1088                 return CLI_SHOWUSAGE;
1089
1090         AST_LIST_LOCK(&locals);
1091         if (!AST_LIST_EMPTY(&locals)) {
1092                 AST_LIST_TRAVERSE(&locals, p, list) {
1093                         ast_mutex_lock(&p->lock);
1094                         ast_cli(a->fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
1095                         ast_mutex_unlock(&p->lock);
1096                 }
1097         } else
1098                 ast_cli(a->fd, "No local channels in use\n");
1099         AST_LIST_UNLOCK(&locals);
1100
1101         return CLI_SUCCESS;
1102 }
1103
1104 static struct ast_cli_entry cli_local[] = {
1105         AST_CLI_DEFINE(locals_show, "List status of local channels"),
1106 };
1107
1108 static int manager_optimize_away(struct mansession *s, const struct message *m)
1109 {
1110         const char *channel;
1111         struct local_pvt *p, *tmp = NULL;
1112         struct ast_channel *c;
1113         int found = 0;
1114
1115         channel = astman_get_header(m, "Channel");
1116
1117         if (ast_strlen_zero(channel)) {
1118                 astman_send_error(s, m, "'Channel' not specified.");
1119                 return 0;
1120         }
1121
1122         c = ast_channel_get_by_name(channel);
1123         if (!c) {
1124                 astman_send_error(s, m, "Channel does not exist.");
1125                 return 0;
1126         }
1127
1128         p = c->tech_pvt;
1129         ast_channel_unref(c);
1130         c = NULL;
1131
1132         if (AST_LIST_LOCK(&locals)) {
1133                 astman_send_error(s, m, "Unable to lock the monitor");
1134                 return 0;
1135         }
1136
1137
1138         AST_LIST_TRAVERSE(&locals, tmp, list) {
1139                 if (tmp == p) {
1140                         ast_mutex_lock(&tmp->lock);
1141                         found = 1;
1142                         ast_clear_flag(tmp, LOCAL_NO_OPTIMIZATION);
1143                         ast_mutex_unlock(&tmp->lock);
1144                         break;
1145                 }
1146         }
1147         AST_LIST_UNLOCK(&locals);
1148
1149         if (found) {
1150                 astman_send_ack(s, m, "Queued channel to be optimized away");
1151         } else {
1152                 astman_send_error(s, m, "Unable to find channel");
1153         }
1154
1155         return 0;
1156 }
1157
1158
1159 /*! \brief Load module into PBX, register channel */
1160 static int load_module(void)
1161 {
1162         /* Make sure we can register our channel type */
1163         if (ast_channel_register(&local_tech)) {
1164                 ast_log(LOG_ERROR, "Unable to register channel class 'Local'\n");
1165                 return AST_MODULE_LOAD_FAILURE;
1166         }
1167         ast_cli_register_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1168         ast_manager_register_xml("LocalOptimizeAway", EVENT_FLAG_SYSTEM|EVENT_FLAG_CALL, manager_optimize_away);
1169
1170         return AST_MODULE_LOAD_SUCCESS;
1171 }
1172
1173 /*! \brief Unload the local proxy channel from Asterisk */
1174 static int unload_module(void)
1175 {
1176         struct local_pvt *p = NULL;
1177
1178         /* First, take us out of the channel loop */
1179         ast_cli_unregister_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1180         ast_manager_unregister("LocalOptimizeAway");
1181         ast_channel_unregister(&local_tech);
1182         if (!AST_LIST_LOCK(&locals)) {
1183                 /* Hangup all interfaces if they have an owner */
1184                 AST_LIST_TRAVERSE(&locals, p, list) {
1185                         if (p->owner)
1186                                 ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1187                 }
1188                 AST_LIST_UNLOCK(&locals);
1189         } else {
1190                 ast_log(LOG_WARNING, "Unable to lock the monitor\n");
1191                 return -1;
1192         }               
1193         return 0;
1194 }
1195
1196 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Local Proxy Channel (Note: used internally by other modules)",
1197                 .load = load_module,
1198                 .unload = unload_module,
1199                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1200         );