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