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