chan_local: Misc lock and ref tweaks.
[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 /*** MODULEINFO
29         <support_level>core</support_level>
30  ***/
31
32 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #include <fcntl.h>
37 #include <sys/signal.h>
38
39 #include "asterisk/lock.h"
40 #include "asterisk/causes.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/config.h"
43 #include "asterisk/module.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/sched.h"
46 #include "asterisk/io.h"
47 #include "asterisk/acl.h"
48 #include "asterisk/callerid.h"
49 #include "asterisk/file.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/app.h"
52 #include "asterisk/musiconhold.h"
53 #include "asterisk/manager.h"
54 #include "asterisk/stringfields.h"
55 #include "asterisk/devicestate.h"
56 #include "asterisk/astobj2.h"
57
58 /*** DOCUMENTATION
59         <manager name="LocalOptimizeAway" language="en_US">
60                 <synopsis>
61                         Optimize away a local channel when possible.
62                 </synopsis>
63                 <syntax>
64                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
65                         <parameter name="Channel" required="true">
66                                 <para>The channel name to optimize away.</para>
67                         </parameter>
68                 </syntax>
69                 <description>
70                         <para>A local channel created with "/n" will not automatically optimize away.
71                         Calling this command on the local channel will clear that flag and allow
72                         it to optimize away if it's bridged or when it becomes bridged.</para>
73                 </description>
74         </manager>
75  ***/
76
77 static const char tdesc[] = "Local Proxy Channel Driver";
78
79 #define IS_OUTBOUND(a,b) (a == b->chan ? 1 : 0)
80
81 /* right now we are treating the locals astobj2 container as a
82  * list.  If there is ever a reason to make this more efficient
83  * increasing the bucket size would help. */
84 static const int BUCKET_SIZE = 1;
85
86 static struct ao2_container *locals;
87
88 static unsigned int name_sequence = 0;
89
90 static struct ast_jb_conf g_jb_conf = {
91         .flags = 0,
92         .max_size = -1,
93         .resync_threshold = -1,
94         .impl = "",
95         .target_extra = -1,
96 };
97
98 static struct ast_channel *local_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
99 static int local_digit_begin(struct ast_channel *ast, char digit);
100 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
101 static int local_call(struct ast_channel *ast, const char *dest, int timeout);
102 static int local_hangup(struct ast_channel *ast);
103 static int local_answer(struct ast_channel *ast);
104 static struct ast_frame *local_read(struct ast_channel *ast);
105 static int local_write(struct ast_channel *ast, struct ast_frame *f);
106 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
107 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
108 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
109 static int local_sendtext(struct ast_channel *ast, const char *text);
110 static int local_devicestate(const char *data);
111 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge);
112 static int local_queryoption(struct ast_channel *ast, int option, void *data, int *datalen);
113 static int local_setoption(struct ast_channel *chan, int option, void *data, int datalen);
114
115 /* PBX interface structure for channel registration */
116 static struct ast_channel_tech local_tech = {
117         .type = "Local",
118         .description = tdesc,
119         .requester = local_request,
120         .send_digit_begin = local_digit_begin,
121         .send_digit_end = local_digit_end,
122         .call = local_call,
123         .hangup = local_hangup,
124         .answer = local_answer,
125         .read = local_read,
126         .write = local_write,
127         .write_video = local_write,
128         .exception = local_read,
129         .indicate = local_indicate,
130         .fixup = local_fixup,
131         .send_html = local_sendhtml,
132         .send_text = local_sendtext,
133         .devicestate = local_devicestate,
134         .bridged_channel = local_bridgedchannel,
135         .queryoption = local_queryoption,
136         .setoption = local_setoption,
137 };
138
139 /*! \brief the local pvt structure for all channels
140
141         The local channel pvt has two ast_chan objects - the "owner" and the "next channel", the outbound channel
142
143         ast_chan owner -> local_pvt -> ast_chan chan -> yet-another-pvt-depending-on-channel-type
144
145 */
146 struct local_pvt {
147         unsigned int flags;             /*!< Private flags */
148         char context[AST_MAX_CONTEXT];  /*!< Context to call */
149         char exten[AST_MAX_EXTENSION];  /*!< Extension to call */
150         struct ast_format_cap *reqcap;  /*!< Requested format capabilities */
151         struct ast_jb_conf jb_conf;     /*!< jitterbuffer configuration for this local channel */
152         struct ast_channel *owner;      /*!< Master Channel - Bridging happens here */
153         struct ast_channel *chan;       /*!< Outbound channel - PBX is run here */
154         struct ast_module_user *u_owner;/*!< reference to keep the module loaded while in use */
155         struct ast_module_user *u_chan; /*!< reference to keep the module loaded while in use */
156 };
157
158 #define LOCAL_ALREADY_MASQED  (1 << 0) /*!< Already masqueraded */
159 #define LOCAL_LAUNCHED_PBX    (1 << 1) /*!< PBX was launched */
160 #define LOCAL_NO_OPTIMIZATION (1 << 2) /*!< Do not optimize using masquerading */
161 #define LOCAL_BRIDGE          (1 << 3) /*!< Report back the "true" channel as being bridged to */
162 #define LOCAL_MOH_PASSTHRU    (1 << 4) /*!< Pass through music on hold start/stop frames */
163
164 /*!
165  * \brief Send a pvt in with no locks held and get all locks
166  *
167  * \note NO locks should be held prior to calling this function
168  * \note The pvt must have a ref held before calling this function
169  * \note if outchan or outowner is set != NULL after calling this function
170  *       those channels are locked and reffed.
171  * \note Batman.
172  */
173 static void awesome_locking(struct local_pvt *p, struct ast_channel **outchan, struct ast_channel **outowner)
174 {
175         struct ast_channel *chan = NULL;
176         struct ast_channel *owner = NULL;
177
178         ao2_lock(p);
179         for (;;) {
180                 if (p->chan) {
181                         chan = p->chan;
182                         ast_channel_ref(chan);
183                 }
184                 if (p->owner) {
185                         owner = p->owner;
186                         ast_channel_ref(owner);
187                 }
188                 ao2_unlock(p);
189
190                 /* if we don't have both channels, then this is very easy */
191                 if (!owner || !chan) {
192                         if (owner) {
193                                 ast_channel_lock(owner);
194                         } else if(chan) {
195                                 ast_channel_lock(chan);
196                         }
197                 } else {
198                         /* lock both channels first, then get the pvt lock */
199                         ast_channel_lock_both(chan, owner);
200                 }
201                 ao2_lock(p);
202
203                 /* Now that we have all the locks, validate that nothing changed */
204                 if (p->owner != owner || p->chan != chan) {
205                         if (owner) {
206                                 ast_channel_unlock(owner);
207                                 owner = ast_channel_unref(owner);
208                         }
209                         if (chan) {
210                                 ast_channel_unlock(chan);
211                                 chan = ast_channel_unref(chan);
212                         }
213                         continue;
214                 }
215
216                 break;
217         }
218         *outowner = p->owner;
219         *outchan = p->chan;
220 }
221
222 /* Called with ast locked */
223 static int local_setoption(struct ast_channel *ast, int option, void * data, int datalen)
224 {
225         int res = 0;
226         struct local_pvt *p;
227         struct ast_channel *otherchan = NULL;
228         ast_chan_write_info_t *write_info;
229
230         if (option != AST_OPTION_CHANNEL_WRITE) {
231                 return -1;
232         }
233
234         write_info = data;
235
236         if (write_info->version != AST_CHAN_WRITE_INFO_T_VERSION) {
237                 ast_log(LOG_ERROR, "The chan_write_info_t type has changed, and this channel hasn't been updated!\n");
238                 return -1;
239         }
240
241         if (!strcmp(write_info->function, "CHANNEL")
242                 && !strncasecmp(write_info->data, "hangup_handler_", 15)) {
243                 /* Block CHANNEL(hangup_handler_xxx) writes to the other local channel. */
244                 return 0;
245         }
246
247         /* get the tech pvt */
248         if (!(p = ast_channel_tech_pvt(ast))) {
249                 return -1;
250         }
251         ao2_ref(p, 1);
252         ast_channel_unlock(ast); /* Held when called, unlock before locking another channel */
253
254         /* get the channel we are supposed to write to */
255         ao2_lock(p);
256         otherchan = (write_info->chan == p->owner) ? p->chan : p->owner;
257         if (!otherchan || otherchan == write_info->chan) {
258                 res = -1;
259                 otherchan = NULL;
260                 ao2_unlock(p);
261                 goto setoption_cleanup;
262         }
263         ast_channel_ref(otherchan);
264
265         /* clear the pvt lock before grabbing the channel */
266         ao2_unlock(p);
267
268         ast_channel_lock(otherchan);
269         res = write_info->write_fn(otherchan, write_info->function, write_info->data, write_info->value);
270         ast_channel_unlock(otherchan);
271
272 setoption_cleanup:
273         ao2_ref(p, -1);
274         if (otherchan) {
275                 ast_channel_unref(otherchan);
276         }
277         ast_channel_lock(ast); /* Lock back before we leave */
278         return res;
279 }
280
281 /*! \brief Adds devicestate to local channels */
282 static int local_devicestate(const char *data)
283 {
284         char *exten = ast_strdupa(data);
285         char *context = NULL, *opts = NULL;
286         int res;
287         struct local_pvt *lp;
288         struct ao2_iterator it;
289
290         if (!(context = strchr(exten, '@'))) {
291                 ast_log(LOG_WARNING, "Someone used Local/%s somewhere without a @context. This is bad.\n", exten);
292                 return AST_DEVICE_INVALID;
293         }
294
295         *context++ = '\0';
296
297         /* Strip options if they exist */
298         if ((opts = strchr(context, '/')))
299                 *opts = '\0';
300
301         ast_debug(3, "Checking if extension %s@%s exists (devicestate)\n", exten, context);
302
303         res = ast_exists_extension(NULL, context, exten, 1, NULL);
304         if (!res)
305                 return AST_DEVICE_INVALID;
306
307         res = AST_DEVICE_NOT_INUSE;
308
309         it = ao2_iterator_init(locals, 0);
310         for (; (lp = ao2_iterator_next(&it)); ao2_ref(lp, -1)) {
311                 int is_inuse;
312
313                 ao2_lock(lp);
314                 is_inuse = !strcmp(exten, lp->exten)
315                         && !strcmp(context, lp->context)
316                         && lp->owner
317                         && ast_test_flag(lp, LOCAL_LAUNCHED_PBX);
318                 ao2_unlock(lp);
319                 if (is_inuse) {
320                         res = AST_DEVICE_INUSE;
321                         ao2_ref(lp, -1);
322                         break;
323                 }
324         }
325         ao2_iterator_destroy(&it);
326
327         return res;
328 }
329
330 /*! \brief Return the bridged channel of a Local channel */
331 static struct ast_channel *local_bridgedchannel(struct ast_channel *chan, struct ast_channel *bridge)
332 {
333         struct local_pvt *p = ast_channel_tech_pvt(bridge);
334         struct ast_channel *bridged = bridge;
335
336         if (!p) {
337                 ast_debug(1, "Asked for bridged channel on '%s'/'%s', returning <none>\n",
338                         ast_channel_name(chan), ast_channel_name(bridge));
339                 return NULL;
340         }
341
342         ao2_lock(p);
343
344         if (ast_test_flag(p, LOCAL_BRIDGE)) {
345                 /* Find the opposite channel */
346                 bridged = (bridge == p->owner ? p->chan : p->owner);
347
348                 /* Now see if the opposite channel is bridged to anything */
349                 if (!bridged) {
350                         bridged = bridge;
351                 } else if (ast_channel_internal_bridged_channel(bridged)) {
352                         bridged = ast_channel_internal_bridged_channel(bridged);
353                 }
354         }
355
356         ao2_unlock(p);
357
358         return bridged;
359 }
360
361 /* Called with ast locked */
362 static int local_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
363 {
364         struct local_pvt *p;
365         struct ast_channel *bridged = NULL;
366         struct ast_channel *tmp = NULL;
367         int res = 0;
368
369         if (option != AST_OPTION_T38_STATE) {
370                 /* AST_OPTION_T38_STATE is the only supported option at this time */
371                 return -1;
372         }
373
374         /* for some reason the channel is not locked in channel.c when this function is called */
375         if (!(p = ast_channel_tech_pvt(ast))) {
376                 return -1;
377         }
378
379         ao2_lock(p);
380         if (!(tmp = IS_OUTBOUND(ast, p) ? p->owner : p->chan)) {
381                 ao2_unlock(p);
382                 return -1;
383         }
384         ast_channel_ref(tmp);
385         ao2_unlock(p);
386         ast_channel_unlock(ast); /* Held when called, unlock before locking another channel */
387
388         ast_channel_lock(tmp);
389         if (!(bridged = ast_bridged_channel(tmp))) {
390                 res = -1;
391                 ast_channel_unlock(tmp);
392                 goto query_cleanup;
393         }
394         ast_channel_ref(bridged);
395         ast_channel_unlock(tmp);
396
397 query_cleanup:
398         if (bridged) {
399                 res = ast_channel_queryoption(bridged, option, data, datalen, 0);
400                 bridged = ast_channel_unref(bridged);
401         }
402         if (tmp) {
403                 tmp = ast_channel_unref(tmp);
404         }
405         ast_channel_lock(ast); /* Lock back before we leave */
406
407         return res;
408 }
409
410 /*! \brief queue a frame on a to either the p->owner or p->chan
411  *
412  * \note the local_pvt MUST have it's ref count bumped before entering this function and
413  * decremented after this function is called.  This is a side effect of the deadlock
414  * avoidance that is necessary to lock 2 channels and a tech_pvt.  Without a ref counted
415  * local_pvt, it is impossible to guarantee it will not be destroyed by another thread
416  * during deadlock avoidance.
417  */
418 static int local_queue_frame(struct local_pvt *p, int isoutbound, struct ast_frame *f,
419         struct ast_channel *us, int us_locked)
420 {
421         struct ast_channel *other = NULL;
422
423         /* Recalculate outbound channel */
424         other = isoutbound ? p->owner : p->chan;
425
426         if (!other) {
427                 return 0;
428         }
429
430         /* do not queue frame if generator is on both local channels */
431         if (us && ast_channel_generator(us) && ast_channel_generator(other)) {
432                 return 0;
433         }
434
435         /* grab a ref on the channel before unlocking the pvt,
436          * other can not go away from us now regardless of locking */
437         ast_channel_ref(other);
438         if (us && us_locked) {
439                 ast_channel_unlock(us);
440         }
441         ao2_unlock(p);
442
443         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_RINGING) {
444                 ast_setstate(other, AST_STATE_RINGING);
445         }
446         ast_queue_frame(other, f);
447
448         other = ast_channel_unref(other);
449         if (us && us_locked) {
450                 ast_channel_lock(us);
451         }
452         ao2_lock(p);
453
454         return 0;
455 }
456
457 static int local_answer(struct ast_channel *ast)
458 {
459         struct local_pvt *p = ast_channel_tech_pvt(ast);
460         int isoutbound;
461         int res = -1;
462
463         if (!p) {
464                 return -1;
465         }
466
467         ao2_ref(p, 1);
468         ao2_lock(p);
469         isoutbound = IS_OUTBOUND(ast, p);
470         if (isoutbound) {
471                 /* Pass along answer since somebody answered us */
472                 struct ast_frame answer = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
473                 res = local_queue_frame(p, isoutbound, &answer, ast, 1);
474         } else {
475                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
476         }
477         ao2_unlock(p);
478         ao2_ref(p, -1);
479         return res;
480 }
481
482 /*!
483  * \internal
484  * \note This function assumes that we're only called from the "outbound" local channel side
485  *
486  * \note it is assummed p is locked and reffed before entering this function
487  */
488 static void check_bridge(struct ast_channel *ast, struct local_pvt *p)
489 {
490         struct ast_channel *owner;
491         struct ast_channel *chan;
492         struct ast_channel *bridged_chan;
493         struct ast_frame *f;
494
495         /* Do a few conditional checks early on just to see if this optimization is possible */
496         if (ast_test_flag(p, LOCAL_NO_OPTIMIZATION | LOCAL_ALREADY_MASQED)
497                 || !p->chan || !p->owner) {
498                 return;
499         }
500
501         /* Safely get the channel bridged to p->chan */
502         chan = ast_channel_ref(p->chan);
503
504         ao2_unlock(p); /* don't call bridged channel with the pvt locked */
505         bridged_chan = ast_bridged_channel(chan);
506         ao2_lock(p);
507
508         chan = ast_channel_unref(chan);
509
510         /* since we had to unlock p to get the bridged chan, validate our
511          * data once again and verify the bridged channel is what we expect
512          * it to be in order to perform this optimization */
513         if (ast_test_flag(p, LOCAL_NO_OPTIMIZATION | LOCAL_ALREADY_MASQED)
514                 || !p->chan || !p->owner
515                 || (ast_channel_internal_bridged_channel(p->chan) != bridged_chan)) {
516                 return;
517         }
518
519         /* only do the masquerade if we are being called on the outbound channel,
520            if it has been bridged to another channel and if there are no pending
521            frames on the owner channel (because they would be transferred to the
522            outbound channel during the masquerade)
523         */
524         if (!ast_channel_internal_bridged_channel(p->chan) /* Not ast_bridged_channel!  Only go one step! */
525                 || !AST_LIST_EMPTY(ast_channel_readq(p->owner))
526                 || ast != p->chan /* Sanity check (should always be false) */) {
527                 return;
528         }
529
530         /* Masquerade bridged channel into owner */
531         /* Lock everything we need, one by one, and give up if
532            we can't get everything.  Remember, we'll get another
533            chance in just a little bit */
534         if (ast_channel_trylock(ast_channel_internal_bridged_channel(p->chan))) {
535                 return;
536         }
537         if (ast_check_hangup(ast_channel_internal_bridged_channel(p->chan))
538                 || ast_channel_trylock(p->owner)) {
539                 ast_channel_unlock(ast_channel_internal_bridged_channel(p->chan));
540                 return;
541         }
542
543         /*
544          * At this point we have 4 locks:
545          * p, p->chan (same as ast), p->chan->_bridge, p->owner
546          *
547          * Flush a voice or video frame on the outbound channel to make
548          * the queue empty faster so we can get optimized out.
549          */
550         f = AST_LIST_FIRST(ast_channel_readq(p->chan));
551         if (f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
552                 AST_LIST_REMOVE_HEAD(ast_channel_readq(p->chan), frame_list);
553                 ast_frfree(f);
554                 f = AST_LIST_FIRST(ast_channel_readq(p->chan));
555         }
556
557         if (f
558                 || ast_check_hangup(p->owner)
559                 || ast_channel_masquerade(p->owner, ast_channel_internal_bridged_channel(p->chan))) {
560                 ast_channel_unlock(p->owner);
561                 ast_channel_unlock(ast_channel_internal_bridged_channel(p->chan));
562                 return;
563         }
564
565         /* Masquerade got setup. */
566         ast_debug(4, "Masquerading %s <- %s\n",
567                 ast_channel_name(p->owner),
568                 ast_channel_name(ast_channel_internal_bridged_channel(p->chan)));
569         if (ast_channel_monitor(p->owner)
570                 && !ast_channel_monitor(ast_channel_internal_bridged_channel(p->chan))) {
571                 struct ast_channel_monitor *tmp;
572
573                 /* If a local channel is being monitored, we don't want a masquerade
574                  * to cause the monitor to go away. Since the masquerade swaps the monitors,
575                  * pre-swapping the monitors before the masquerade will ensure that the monitor
576                  * ends up where it is expected.
577                  */
578                 tmp = ast_channel_monitor(p->owner);
579                 ast_channel_monitor_set(p->owner, ast_channel_monitor(ast_channel_internal_bridged_channel(p->chan)));
580                 ast_channel_monitor_set(ast_channel_internal_bridged_channel(p->chan), tmp);
581         }
582         if (ast_channel_audiohooks(p->chan)) {
583                 struct ast_audiohook_list *audiohooks_swapper;
584
585                 audiohooks_swapper = ast_channel_audiohooks(p->chan);
586                 ast_channel_audiohooks_set(p->chan, ast_channel_audiohooks(p->owner));
587                 ast_channel_audiohooks_set(p->owner, audiohooks_swapper);
588         }
589
590         /* If any Caller ID was set, preserve it after masquerade like above. We must check
591          * to see if Caller ID was set because otherwise we'll mistakingly copy info not
592          * set from the dialplan and will overwrite the real channel Caller ID. The reason
593          * for this whole preswapping action is because the Caller ID is set on the channel
594          * thread (which is the to be masqueraded away local channel) before both local
595          * channels are optimized away.
596          */
597         if (ast_channel_caller(p->owner)->id.name.valid || ast_channel_caller(p->owner)->id.number.valid
598                 || ast_channel_caller(p->owner)->id.subaddress.valid || ast_channel_caller(p->owner)->ani.name.valid
599                 || ast_channel_caller(p->owner)->ani.number.valid || ast_channel_caller(p->owner)->ani.subaddress.valid) {
600                 SWAP(*ast_channel_caller(p->owner), *ast_channel_caller(ast_channel_internal_bridged_channel(p->chan)));
601         }
602         if (ast_channel_redirecting(p->owner)->from.name.valid || ast_channel_redirecting(p->owner)->from.number.valid
603                 || ast_channel_redirecting(p->owner)->from.subaddress.valid || ast_channel_redirecting(p->owner)->to.name.valid
604                 || ast_channel_redirecting(p->owner)->to.number.valid || ast_channel_redirecting(p->owner)->to.subaddress.valid) {
605                 SWAP(*ast_channel_redirecting(p->owner), *ast_channel_redirecting(ast_channel_internal_bridged_channel(p->chan)));
606         }
607         if (ast_channel_dialed(p->owner)->number.str || ast_channel_dialed(p->owner)->subaddress.valid) {
608                 SWAP(*ast_channel_dialed(p->owner), *ast_channel_dialed(ast_channel_internal_bridged_channel(p->chan)));
609         }
610         ast_app_group_update(p->chan, p->owner);
611         ast_set_flag(p, LOCAL_ALREADY_MASQED);
612
613         ast_channel_unlock(p->owner);
614         ast_channel_unlock(ast_channel_internal_bridged_channel(p->chan));
615
616         /* Do the masquerade now. */
617         owner = ast_channel_ref(p->owner);
618         ao2_unlock(p);
619         ast_channel_unlock(ast);
620         ast_do_masquerade(owner);
621         ast_channel_unref(owner);
622         ast_channel_lock(ast);
623         ao2_lock(p);
624 }
625
626 static struct ast_frame  *local_read(struct ast_channel *ast)
627 {
628         return &ast_null_frame;
629 }
630
631 static int local_write(struct ast_channel *ast, struct ast_frame *f)
632 {
633         struct local_pvt *p = ast_channel_tech_pvt(ast);
634         int res = -1;
635         int isoutbound;
636
637         if (!p) {
638                 return -1;
639         }
640
641         /* Just queue for delivery to the other side */
642         ao2_ref(p, 1); /* ref for local_queue_frame */
643         ao2_lock(p);
644         isoutbound = IS_OUTBOUND(ast, p);
645
646         if (isoutbound
647                 && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
648                 check_bridge(ast, p);
649         }
650
651         if (!ast_test_flag(p, LOCAL_ALREADY_MASQED)) {
652                 res = local_queue_frame(p, isoutbound, f, ast, 1);
653         } else {
654                 ast_debug(1, "Not posting to '%s' queue since already masqueraded out\n",
655                         ast_channel_name(ast));
656                 res = 0;
657         }
658         ao2_unlock(p);
659         ao2_ref(p, -1);
660
661         return res;
662 }
663
664 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
665 {
666         struct local_pvt *p = ast_channel_tech_pvt(newchan);
667
668         if (!p) {
669                 return -1;
670         }
671
672         ao2_lock(p);
673
674         if ((p->owner != oldchan) && (p->chan != oldchan)) {
675                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
676                 ao2_unlock(p);
677                 return -1;
678         }
679         if (p->owner == oldchan) {
680                 p->owner = newchan;
681         } else {
682                 p->chan = newchan;
683         }
684
685         /* Do not let a masquerade cause a Local channel to be bridged to itself! */
686         if (!ast_check_hangup(newchan) && ((p->owner && ast_channel_internal_bridged_channel(p->owner) == p->chan) || (p->chan && ast_channel_internal_bridged_channel(p->chan) == p->owner))) {
687                 ast_log(LOG_WARNING, "You can not bridge a Local channel to itself!\n");
688                 ao2_unlock(p);
689                 ast_queue_hangup(newchan);
690                 return -1;
691         }
692
693         ao2_unlock(p);
694         return 0;
695 }
696
697 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
698 {
699         struct local_pvt *p = ast_channel_tech_pvt(ast);
700         int res = 0;
701         struct ast_frame f = { AST_FRAME_CONTROL, };
702         int isoutbound;
703
704         if (!p) {
705                 return -1;
706         }
707
708         ao2_ref(p, 1); /* ref for local_queue_frame */
709
710         /* If this is an MOH hold or unhold, do it on the Local channel versus real channel */
711         if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_HOLD) {
712                 ast_moh_start(ast, data, NULL);
713         } else if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_UNHOLD) {
714                 ast_moh_stop(ast);
715         } else if (condition == AST_CONTROL_CONNECTED_LINE || condition == AST_CONTROL_REDIRECTING) {
716                 struct ast_channel *this_channel;
717                 struct ast_channel *the_other_channel;
718                 /* A connected line update frame may only contain a partial amount of data, such
719                  * as just a source, or just a ton, and not the full amount of information. However,
720                  * the collected information is all stored in the outgoing channel's connectedline
721                  * structure, so when receiving a connected line update on an outgoing local channel,
722                  * we need to transmit the collected connected line information instead of whatever
723                  * happens to be in this control frame. The same applies for redirecting information, which
724                  * is why it is handled here as well.*/
725                 ao2_lock(p);
726                 isoutbound = IS_OUTBOUND(ast, p);
727                 if (isoutbound) {
728                         this_channel = p->chan;
729                         the_other_channel = p->owner;
730                 } else {
731                         this_channel = p->owner;
732                         the_other_channel = p->chan;
733                 }
734                 if (the_other_channel) {
735                         unsigned char frame_data[1024];
736                         if (condition == AST_CONTROL_CONNECTED_LINE) {
737                                 if (isoutbound) {
738                                         ast_connected_line_copy_to_caller(ast_channel_caller(the_other_channel), ast_channel_connected(this_channel));
739                                 }
740                                 f.datalen = ast_connected_line_build_data(frame_data, sizeof(frame_data), ast_channel_connected(this_channel), NULL);
741                         } else {
742                                 f.datalen = ast_redirecting_build_data(frame_data, sizeof(frame_data), ast_channel_redirecting(this_channel), NULL);
743                         }
744                         f.subclass.integer = condition;
745                         f.data.ptr = frame_data;
746                         res = local_queue_frame(p, isoutbound, &f, ast, 1);
747                 }
748                 ao2_unlock(p);
749         } else {
750                 /* Queue up a frame representing the indication as a control frame */
751                 ao2_lock(p);
752                 /*
753                  * Block -1 stop tones events if we are to be optimized out.  We
754                  * don't need a flurry of these events on a local channel chain
755                  * when initially connected to slow the optimization process.
756                  */
757                 if (0 <= condition || ast_test_flag(p, LOCAL_NO_OPTIMIZATION)) {
758                         isoutbound = IS_OUTBOUND(ast, p);
759                         f.subclass.integer = condition;
760                         f.data.ptr = (void *) data;
761                         f.datalen = datalen;
762                         res = local_queue_frame(p, isoutbound, &f, ast, 1);
763
764                         if (!res && (condition == AST_CONTROL_T38_PARAMETERS) &&
765                             (datalen == sizeof(struct ast_control_t38_parameters))) {
766                                 const struct ast_control_t38_parameters *parameters = data;
767                                 
768                                 if (parameters->request_response == AST_T38_REQUEST_PARMS) {
769                                         res = AST_T38_REQUEST_PARMS;
770                                 }
771                         }
772                 } else {
773                         ast_debug(4, "Blocked indication %d\n", condition);
774                 }
775                 ao2_unlock(p);
776         }
777
778         ao2_ref(p, -1);
779         return res;
780 }
781
782 static int local_digit_begin(struct ast_channel *ast, char digit)
783 {
784         struct local_pvt *p = ast_channel_tech_pvt(ast);
785         int res = -1;
786         struct ast_frame f = { AST_FRAME_DTMF_BEGIN, };
787         int isoutbound;
788
789         if (!p) {
790                 return -1;
791         }
792
793         ao2_ref(p, 1); /* ref for local_queue_frame */
794         ao2_lock(p);
795         isoutbound = IS_OUTBOUND(ast, p);
796         f.subclass.integer = digit;
797         res = local_queue_frame(p, isoutbound, &f, ast, 0);
798         ao2_unlock(p);
799         ao2_ref(p, -1);
800
801         return res;
802 }
803
804 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
805 {
806         struct local_pvt *p = ast_channel_tech_pvt(ast);
807         int res = -1;
808         struct ast_frame f = { AST_FRAME_DTMF_END, };
809         int isoutbound;
810
811         if (!p) {
812                 return -1;
813         }
814
815         ao2_ref(p, 1); /* ref for local_queue_frame */
816         ao2_lock(p);
817         isoutbound = IS_OUTBOUND(ast, p);
818         f.subclass.integer = digit;
819         f.len = duration;
820         res = local_queue_frame(p, isoutbound, &f, ast, 0);
821         ao2_unlock(p);
822         ao2_ref(p, -1);
823
824         return res;
825 }
826
827 static int local_sendtext(struct ast_channel *ast, const char *text)
828 {
829         struct local_pvt *p = ast_channel_tech_pvt(ast);
830         int res = -1;
831         struct ast_frame f = { AST_FRAME_TEXT, };
832         int isoutbound;
833
834         if (!p) {
835                 return -1;
836         }
837
838         ao2_ref(p, 1); /* ref for local_queue_frame */
839         ao2_lock(p);
840         isoutbound = IS_OUTBOUND(ast, p);
841         f.data.ptr = (char *) text;
842         f.datalen = strlen(text) + 1;
843         res = local_queue_frame(p, isoutbound, &f, ast, 0);
844         ao2_unlock(p);
845         ao2_ref(p, -1);
846         return res;
847 }
848
849 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
850 {
851         struct local_pvt *p = ast_channel_tech_pvt(ast);
852         int res = -1;
853         struct ast_frame f = { AST_FRAME_HTML, };
854         int isoutbound;
855
856         if (!p) {
857                 return -1;
858         }
859
860         ao2_ref(p, 1); /* ref for local_queue_frame */
861         ao2_lock(p);
862         isoutbound = IS_OUTBOUND(ast, p);
863         f.subclass.integer = subclass;
864         f.data.ptr = (char *)data;
865         f.datalen = datalen;
866         res = local_queue_frame(p, isoutbound, &f, ast, 0);
867         ao2_unlock(p);
868         ao2_ref(p, -1);
869
870         return res;
871 }
872
873 /*! \brief Initiate new call, part of PBX interface
874  *         dest is the dial string */
875 static int local_call(struct ast_channel *ast, const char *dest, int timeout)
876 {
877         struct local_pvt *p = ast_channel_tech_pvt(ast);
878         int pvt_locked = 0;
879
880         struct ast_channel *owner = NULL;
881         struct ast_channel *chan = NULL;
882         int res;
883         struct ast_var_t *varptr;
884         struct ast_var_t *clone_var;
885         char *reduced_dest = ast_strdupa(dest);
886         char *slash;
887         const char *exten;
888         const char *context;
889
890         if (!p) {
891                 return -1;
892         }
893
894         /* since we are letting go of channel locks that were locked coming into
895          * this function, then we need to give the tech pvt a ref */
896         ao2_ref(p, 1);
897         ast_channel_unlock(ast);
898
899         awesome_locking(p, &chan, &owner);
900         pvt_locked = 1;
901
902         if (owner != ast) {
903                 res = -1;
904                 goto return_cleanup;
905         }
906
907         if (!owner || !chan) {
908                 res = -1;
909                 goto return_cleanup;
910         }
911
912         /*
913          * Note that cid_num and cid_name aren't passed in the ast_channel_alloc
914          * call, so it's done here instead.
915          *
916          * All these failure points just return -1. The individual strings will
917          * be cleared when we destroy the channel.
918          */
919         ast_party_redirecting_copy(ast_channel_redirecting(chan), ast_channel_redirecting(owner));
920
921         ast_party_dialed_copy(ast_channel_dialed(chan), ast_channel_dialed(owner));
922
923         ast_connected_line_copy_to_caller(ast_channel_caller(chan), ast_channel_connected(owner));
924         ast_connected_line_copy_from_caller(ast_channel_connected(chan), ast_channel_caller(owner));
925
926         ast_channel_language_set(chan, ast_channel_language(owner));
927         ast_channel_accountcode_set(chan, ast_channel_accountcode(owner));
928         ast_channel_musicclass_set(chan, ast_channel_musicclass(owner));
929         ast_cdr_update(chan);
930
931         ast_channel_cc_params_init(chan, ast_channel_get_cc_config_params(owner));
932
933         /* Make sure we inherit the AST_CAUSE_ANSWERED_ELSEWHERE if it's set on the queue/dial call request in the dialplan */
934         if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
935                 ast_channel_hangupcause_set(chan, AST_CAUSE_ANSWERED_ELSEWHERE);
936         }
937
938         /* copy the channel variables from the incoming channel to the outgoing channel */
939         /* Note that due to certain assumptions, they MUST be in the same order */
940         AST_LIST_TRAVERSE(ast_channel_varshead(owner), varptr, entries) {
941                 clone_var = ast_var_assign(varptr->name, varptr->value);
942                 if (clone_var) {
943                         AST_LIST_INSERT_TAIL(ast_channel_varshead(chan), clone_var, entries);
944                 }
945         }
946         ast_channel_datastore_inherit(owner, chan);
947         /* If the local channel has /n or /b on the end of it,
948          * we need to lop that off for our argument to setting
949          * up the CC_INTERFACES variable
950          */
951         if ((slash = strrchr(reduced_dest, '/'))) {
952                 *slash = '\0';
953         }
954         ast_set_cc_interfaces_chanvar(chan, reduced_dest);
955
956         exten = ast_strdupa(ast_channel_exten(chan));
957         context = ast_strdupa(ast_channel_context(chan));
958
959         ao2_unlock(p);
960         pvt_locked = 0;
961
962         ast_channel_unlock(chan);
963
964         if (!ast_exists_extension(chan, context, exten, 1,
965                 S_COR(ast_channel_caller(owner)->id.number.valid, ast_channel_caller(owner)->id.number.str, NULL))) {
966                 ast_log(LOG_NOTICE, "No such extension/context %s@%s while calling Local channel\n", exten, context);
967                 res = -1;
968                 chan = ast_channel_unref(chan); /* we already unlocked it, so clear it hear so the cleanup label won't touch it. */
969                 goto return_cleanup;
970         }
971
972         /*** DOCUMENTATION
973                 <managerEventInstance>
974                         <synopsis>Raised when two halves of a Local Channel form a bridge.</synopsis>
975                         <syntax>
976                                 <parameter name="Channel1">
977                                         <para>The name of the Local Channel half that bridges to another channel.</para>
978                                 </parameter>
979                                 <parameter name="Channel2">
980                                         <para>The name of the Local Channel half that executes the dialplan.</para>
981                                 </parameter>
982                                 <parameter name="Context">
983                                         <para>The context in the dialplan that Channel2 starts in.</para>
984                                 </parameter>
985                                 <parameter name="Exten">
986                                         <para>The extension in the dialplan that Channel2 starts in.</para>
987                                 </parameter>
988                                 <parameter name="LocalOptimization">
989                                         <enumlist>
990                                                 <enum name="Yes"/>
991                                                 <enum name="No"/>
992                                         </enumlist>
993                                 </parameter>
994                         </syntax>
995                 </managerEventInstance>
996         ***/
997         manager_event(EVENT_FLAG_CALL, "LocalBridge",
998                       "Channel1: %s\r\n"
999                       "Channel2: %s\r\n"
1000                       "Uniqueid1: %s\r\n"
1001                       "Uniqueid2: %s\r\n"
1002                       "Context: %s\r\n"
1003                       "Exten: %s\r\n"
1004                       "LocalOptimization: %s\r\n",
1005                         ast_channel_name(p->owner), ast_channel_name(p->chan), ast_channel_uniqueid(p->owner), ast_channel_uniqueid(p->chan),
1006                         p->context, p->exten,
1007                         ast_test_flag(p, LOCAL_NO_OPTIMIZATION) ? "Yes" : "No");
1008
1009
1010         /* Start switch on sub channel */
1011         if (!(res = ast_pbx_start(chan))) {
1012                 ao2_lock(p);
1013                 ast_set_flag(p, LOCAL_LAUNCHED_PBX);
1014                 ao2_unlock(p);
1015         }
1016         chan = ast_channel_unref(chan); /* chan is already unlocked, clear it here so the cleanup lable won't touch it. */
1017
1018 return_cleanup:
1019         if (p) {
1020                 if (pvt_locked) {
1021                         ao2_unlock(p);
1022                 }
1023                 ao2_ref(p, -1);
1024         }
1025         if (chan) {
1026                 ast_channel_unlock(chan);
1027                 chan = ast_channel_unref(chan);
1028         }
1029
1030         /* owner is supposed to be == to ast,  if it
1031          * is, don't unlock it because ast must exit locked */
1032         if (owner) {
1033                 if (owner != ast) {
1034                         ast_channel_unlock(owner);
1035                         ast_channel_lock(ast);
1036                 }
1037                 owner = ast_channel_unref(owner);
1038         } else {
1039                 /* we have to exit with ast locked */
1040                 ast_channel_lock(ast);
1041         }
1042
1043         return res;
1044 }
1045
1046 /*! \brief Hangup a call through the local proxy channel */
1047 static int local_hangup(struct ast_channel *ast)
1048 {
1049         struct local_pvt *p = ast_channel_tech_pvt(ast);
1050         int isoutbound;
1051         int hangup_chan = 0;
1052         int res = 0;
1053         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = ast_channel_hangupcause(ast) };
1054         struct ast_channel *owner = NULL;
1055         struct ast_channel *chan = NULL;
1056
1057         if (!p) {
1058                 return -1;
1059         }
1060
1061         /* give the pvt a ref since we are unlocking the channel. */
1062         ao2_ref(p, 1);
1063
1064         /* the pvt isn't going anywhere, we gave it a ref */
1065         ast_channel_unlock(ast);
1066
1067         /* lock everything */
1068         awesome_locking(p, &chan, &owner);
1069
1070         if (ast != chan && ast != owner) {
1071                 res = -1;
1072                 goto local_hangup_cleanup;
1073         }
1074
1075         isoutbound = IS_OUTBOUND(ast, p); /* just comparing pointer of ast */
1076
1077         if (p->chan && ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
1078                 ast_channel_hangupcause_set(p->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
1079                 ast_debug(2, "This local call has AST_CAUSE_ANSWERED_ELSEWHERE set.\n");
1080         }
1081
1082         if (isoutbound) {
1083                 const char *status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
1084                 if ((status) && (p->owner)) {
1085                         ast_channel_hangupcause_set(p->owner, ast_channel_hangupcause(p->chan));
1086                         pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
1087                 }
1088
1089                 ast_clear_flag(p, LOCAL_LAUNCHED_PBX);
1090                 ast_module_user_remove(p->u_chan);
1091                 p->chan = NULL;
1092         } else {
1093                 ast_module_user_remove(p->u_owner);
1094                 if (p->chan) {
1095                         ast_queue_hangup(p->chan);
1096                 }
1097                 p->owner = NULL;
1098         }
1099
1100         ast_channel_tech_pvt_set(ast, NULL); /* this is one of our locked channels, doesn't matter which */
1101
1102         if (!p->owner && !p->chan) {
1103                 ao2_unlock(p);
1104                 /* Remove from list */
1105                 ao2_unlink(locals, p);
1106                 ao2_ref(p, -1);
1107                 p = NULL;
1108                 res = 0;
1109                 goto local_hangup_cleanup;
1110         }
1111         if (p->chan && !ast_test_flag(p, LOCAL_LAUNCHED_PBX)) {
1112                 /* Need to actually hangup since there is no PBX */
1113                 hangup_chan = 1;
1114         } else {
1115                 local_queue_frame(p, isoutbound, &f, NULL, 0);
1116         }
1117
1118 local_hangup_cleanup:
1119         if (p) {
1120                 ao2_unlock(p);
1121                 ao2_ref(p, -1);
1122         }
1123         if (chan) {
1124                 ast_channel_unlock(chan);
1125                 if (hangup_chan) {
1126                         ast_hangup(chan);
1127                 }
1128                 chan = ast_channel_unref(chan);
1129         }
1130         if (owner) {
1131                 ast_channel_unlock(owner);
1132                 owner = ast_channel_unref(owner);
1133         }
1134
1135         /* leave with the same stupid channel locked that came in */
1136         ast_channel_lock(ast);
1137         return res;
1138 }
1139
1140 static void local_destroy(void *obj)
1141 {
1142         struct local_pvt *pvt = obj;
1143         pvt->reqcap = ast_format_cap_destroy(pvt->reqcap);
1144 }
1145
1146 /*! \brief Create a call structure */
1147 static struct local_pvt *local_alloc(const char *data, struct ast_format_cap *cap)
1148 {
1149         struct local_pvt *tmp = NULL;
1150         char *c = NULL, *opts = NULL;
1151
1152         if (!(tmp = ao2_alloc(sizeof(*tmp), local_destroy))) {
1153                 return NULL;
1154         }
1155         if (!(tmp->reqcap = ast_format_cap_dup(cap))) {
1156                 ao2_ref(tmp, -1);
1157                 return NULL;
1158         }
1159
1160         /* Initialize private structure information */
1161         ast_copy_string(tmp->exten, data, sizeof(tmp->exten));
1162
1163         memcpy(&tmp->jb_conf, &g_jb_conf, sizeof(tmp->jb_conf));
1164
1165         /* Look for options */
1166         if ((opts = strchr(tmp->exten, '/'))) {
1167                 *opts++ = '\0';
1168                 if (strchr(opts, 'n'))
1169                         ast_set_flag(tmp, LOCAL_NO_OPTIMIZATION);
1170                 if (strchr(opts, 'j')) {
1171                         if (ast_test_flag(tmp, LOCAL_NO_OPTIMIZATION))
1172                                 ast_set_flag(&tmp->jb_conf, AST_JB_ENABLED);
1173                         else {
1174                                 ast_log(LOG_ERROR, "You must use the 'n' option for chan_local "
1175                                         "to use the 'j' option to enable the jitterbuffer\n");
1176                         }
1177                 }
1178                 if (strchr(opts, 'b')) {
1179                         ast_set_flag(tmp, LOCAL_BRIDGE);
1180                 }
1181                 if (strchr(opts, 'm')) {
1182                         ast_set_flag(tmp, LOCAL_MOH_PASSTHRU);
1183                 }
1184         }
1185
1186         /* Look for a context */
1187         if ((c = strchr(tmp->exten, '@')))
1188                 *c++ = '\0';
1189
1190         ast_copy_string(tmp->context, c ? c : "default", sizeof(tmp->context));
1191 #if 0
1192         /* We can't do this check here, because we don't know the CallerID yet, and
1193          * the CallerID could potentially affect what step is actually taken (or
1194          * even if that step exists). */
1195         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
1196                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
1197                 tmp = local_pvt_destroy(tmp);
1198         } else {
1199 #endif
1200                 /* Add to list */
1201                 ao2_link(locals, tmp);
1202 #if 0
1203         }
1204 #endif
1205         return tmp; /* this is returned with a ref */
1206 }
1207
1208 /*! \brief Start new local channel */
1209 static struct ast_channel *local_new(struct local_pvt *p, int state, const char *linkedid, struct ast_callid *callid)
1210 {
1211         struct ast_channel *tmp = NULL, *tmp2 = NULL;
1212         struct ast_format fmt;
1213         int generated_seqno = ast_atomic_fetchadd_int((int *)&name_sequence, +1);
1214         const char *t;
1215         int ama;
1216
1217         /* Allocate two new Asterisk channels */
1218         /* safe accountcode */
1219         if (p->owner && ast_channel_accountcode(p->owner))
1220                 t = ast_channel_accountcode(p->owner);
1221         else
1222                 t = "";
1223
1224         if (p->owner)
1225                 ama = ast_channel_amaflags(p->owner);
1226         else
1227                 ama = 0;
1228
1229         /* Make sure that the ;2 channel gets the same linkedid as ;1. You can't pass linkedid to both
1230          * allocations since if linkedid isn't set, then each channel will generate its own linkedid. */
1231         if (!(tmp = ast_channel_alloc(1, state, 0, 0, t, p->exten, p->context, linkedid, ama, "Local/%s@%s-%08x;1", p->exten, p->context, generated_seqno))
1232                 || !(tmp2 = ast_channel_alloc(1, AST_STATE_RING, 0, 0, t, p->exten, p->context, ast_channel_linkedid(tmp), ama, "Local/%s@%s-%08x;2", p->exten, p->context, generated_seqno))) {
1233                 if (tmp) {
1234                         tmp = ast_channel_release(tmp);
1235                 }
1236                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
1237                 return NULL;
1238         }
1239
1240         if (callid) {
1241                 ast_channel_callid_set(tmp, callid);
1242                 ast_channel_callid_set(tmp2, callid);
1243         }
1244
1245         ast_channel_tech_set(tmp, &local_tech);
1246         ast_channel_tech_set(tmp2, &local_tech);
1247
1248         ast_format_cap_copy(ast_channel_nativeformats(tmp), p->reqcap);
1249         ast_format_cap_copy(ast_channel_nativeformats(tmp2), p->reqcap);
1250
1251         /* Determine our read/write format and set it on each channel */
1252         ast_best_codec(p->reqcap, &fmt);
1253         ast_format_copy(ast_channel_writeformat(tmp), &fmt);
1254         ast_format_copy(ast_channel_writeformat(tmp2), &fmt);
1255         ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
1256         ast_format_copy(ast_channel_rawwriteformat(tmp2), &fmt);
1257         ast_format_copy(ast_channel_readformat(tmp), &fmt);
1258         ast_format_copy(ast_channel_readformat(tmp2), &fmt);
1259         ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
1260         ast_format_copy(ast_channel_rawreadformat(tmp2), &fmt);
1261
1262         ast_channel_tech_pvt_set(tmp, p);
1263         ast_channel_tech_pvt_set(tmp2, p);
1264
1265         p->owner = tmp;
1266         p->chan = tmp2;
1267         p->u_owner = ast_module_user_add(p->owner);
1268         p->u_chan = ast_module_user_add(p->chan);
1269
1270         ast_channel_context_set(tmp, p->context);
1271         ast_channel_context_set(tmp2, p->context);
1272         ast_channel_exten_set(tmp2, p->exten);
1273         ast_channel_priority_set(tmp, 1);
1274         ast_channel_priority_set(tmp2, 1);
1275
1276         ast_jb_configure(tmp, &p->jb_conf);
1277
1278         return tmp;
1279 }
1280
1281 /*! \brief Part of PBX interface */
1282 static struct ast_channel *local_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause)
1283 {
1284         struct local_pvt *p;
1285         struct ast_channel *chan;
1286         struct ast_callid *callid = ast_read_threadstorage_callid();
1287
1288         /* Allocate a new private structure and then Asterisk channel */
1289         p = local_alloc(data, cap);
1290         if (!p) {
1291                 chan = NULL;
1292                 goto local_request_end;
1293         }
1294         chan = local_new(p, AST_STATE_DOWN, requestor ? ast_channel_linkedid(requestor) : NULL, callid);
1295         if (!chan) {
1296                 ao2_unlink(locals, p);
1297         } else if (ast_channel_cc_params_init(chan, requestor ? ast_channel_get_cc_config_params((struct ast_channel *)requestor) : NULL)) {
1298                 ao2_unlink(locals, p);
1299                 p->owner = ast_channel_release(p->owner);
1300                 ast_module_user_remove(p->u_owner);
1301                 p->chan = ast_channel_release(p->chan);
1302                 ast_module_user_remove(p->u_chan);
1303                 chan = NULL;
1304         }
1305         ao2_ref(p, -1); /* kill the ref from the alloc */
1306
1307 local_request_end:
1308
1309         if (callid) {
1310                 ast_callid_unref(callid);
1311         }
1312
1313         return chan;
1314 }
1315
1316 /*! \brief CLI command "local show channels" */
1317 static char *locals_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1318 {
1319         struct local_pvt *p = NULL;
1320         struct ao2_iterator it;
1321
1322         switch (cmd) {
1323         case CLI_INIT:
1324                 e->command = "local show channels";
1325                 e->usage =
1326                         "Usage: local show channels\n"
1327                         "       Provides summary information on active local proxy channels.\n";
1328                 return NULL;
1329         case CLI_GENERATE:
1330                 return NULL;
1331         }
1332
1333         if (a->argc != 3) {
1334                 return CLI_SHOWUSAGE;
1335         }
1336
1337         if (ao2_container_count(locals) == 0) {
1338                 ast_cli(a->fd, "No local channels in use\n");
1339                 return RESULT_SUCCESS;
1340         }
1341
1342         it = ao2_iterator_init(locals, 0);
1343         while ((p = ao2_iterator_next(&it))) {
1344                 ao2_lock(p);
1345                 ast_cli(a->fd, "%s -- %s@%s\n", p->owner ? ast_channel_name(p->owner) : "<unowned>", p->exten, p->context);
1346                 ao2_unlock(p);
1347                 ao2_ref(p, -1);
1348         }
1349         ao2_iterator_destroy(&it);
1350
1351         return CLI_SUCCESS;
1352 }
1353
1354 static struct ast_cli_entry cli_local[] = {
1355         AST_CLI_DEFINE(locals_show, "List status of local channels"),
1356 };
1357
1358 static int manager_optimize_away(struct mansession *s, const struct message *m)
1359 {
1360         const char *channel;
1361         struct local_pvt *p, *tmp = NULL;
1362         struct ast_channel *c;
1363         int found = 0;
1364         struct ao2_iterator it;
1365
1366         channel = astman_get_header(m, "Channel");
1367
1368         if (ast_strlen_zero(channel)) {
1369                 astman_send_error(s, m, "'Channel' not specified.");
1370                 return 0;
1371         }
1372
1373         c = ast_channel_get_by_name(channel);
1374         if (!c) {
1375                 astman_send_error(s, m, "Channel does not exist.");
1376                 return 0;
1377         }
1378
1379         p = ast_channel_tech_pvt(c);
1380         ast_channel_unref(c);
1381         c = NULL;
1382
1383         it = ao2_iterator_init(locals, 0);
1384         while ((tmp = ao2_iterator_next(&it))) {
1385                 if (tmp == p) {
1386                         ao2_lock(tmp);
1387                         found = 1;
1388                         ast_clear_flag(tmp, LOCAL_NO_OPTIMIZATION);
1389                         ao2_unlock(tmp);
1390                         ao2_ref(tmp, -1);
1391                         break;
1392                 }
1393                 ao2_ref(tmp, -1);
1394         }
1395         ao2_iterator_destroy(&it);
1396
1397         if (found) {
1398                 astman_send_ack(s, m, "Queued channel to be optimized away");
1399         } else {
1400                 astman_send_error(s, m, "Unable to find channel");
1401         }
1402
1403         return 0;
1404 }
1405
1406
1407 static int locals_cmp_cb(void *obj, void *arg, int flags)
1408 {
1409         return (obj == arg) ? CMP_MATCH : 0;
1410 }
1411
1412 /*! \brief Load module into PBX, register channel */
1413 static int load_module(void)
1414 {
1415         if (!(local_tech.capabilities = ast_format_cap_alloc())) {
1416                 return AST_MODULE_LOAD_FAILURE;
1417         }
1418         ast_format_cap_add_all(local_tech.capabilities);
1419
1420         if (!(locals = ao2_container_alloc(BUCKET_SIZE, NULL, locals_cmp_cb))) {
1421                 ast_format_cap_destroy(local_tech.capabilities);
1422                 return AST_MODULE_LOAD_FAILURE;
1423         }
1424
1425         /* Make sure we can register our channel type */
1426         if (ast_channel_register(&local_tech)) {
1427                 ast_log(LOG_ERROR, "Unable to register channel class 'Local'\n");
1428                 ao2_ref(locals, -1);
1429                 ast_format_cap_destroy(local_tech.capabilities);
1430                 return AST_MODULE_LOAD_FAILURE;
1431         }
1432         ast_cli_register_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1433         ast_manager_register_xml("LocalOptimizeAway", EVENT_FLAG_SYSTEM|EVENT_FLAG_CALL, manager_optimize_away);
1434
1435         return AST_MODULE_LOAD_SUCCESS;
1436 }
1437
1438 /*! \brief Unload the local proxy channel from Asterisk */
1439 static int unload_module(void)
1440 {
1441         struct local_pvt *p = NULL;
1442         struct ao2_iterator it;
1443
1444         /* First, take us out of the channel loop */
1445         ast_cli_unregister_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1446         ast_manager_unregister("LocalOptimizeAway");
1447         ast_channel_unregister(&local_tech);
1448
1449         it = ao2_iterator_init(locals, 0);
1450         while ((p = ao2_iterator_next(&it))) {
1451                 if (p->owner) {
1452                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1453                 }
1454                 ao2_ref(p, -1);
1455         }
1456         ao2_iterator_destroy(&it);
1457         ao2_ref(locals, -1);
1458
1459         ast_format_cap_destroy(local_tech.capabilities);
1460         return 0;
1461 }
1462
1463 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Local Proxy Channel (Note: used internally by other modules)",
1464                 .load = load_module,
1465                 .unload = unload_module,
1466                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1467         );