becba86cb60ba0f99e4c1ca5e7214395101bf340
[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         ao2_lock(p);
458         ao2_ref(p, 1);
459         isoutbound = IS_OUTBOUND(ast, p);
460         if (isoutbound) {
461                 /* Pass along answer since somebody answered us */
462                 struct ast_frame answer = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
463                 res = local_queue_frame(p, isoutbound, &answer, ast, 1);
464         } else {
465                 ast_log(LOG_WARNING, "Huh?  Local is being asked to answer?\n");
466         }
467         ao2_unlock(p);
468         ao2_ref(p, -1);
469         return res;
470 }
471
472 /*!
473  * \internal
474  * \note This function assumes that we're only called from the "outbound" local channel side
475  *
476  * \note it is assummed p is locked and reffed before entering this function
477  */
478 static void check_bridge(struct local_pvt *p)
479 {
480         struct ast_channel_monitor *tmp;
481         struct ast_channel *chan = NULL;
482         struct ast_channel *bridged_chan = NULL;
483
484         /* Do a few conditional checks early on just to see if this optimization is possible */
485         if (ast_test_flag(p, LOCAL_NO_OPTIMIZATION)) {
486                 return;
487         }
488         if (ast_test_flag(p, LOCAL_ALREADY_MASQED) || !p->chan || !p->owner) {
489                 return;
490         }
491
492         /* Safely get the channel bridged to p->chan */
493         chan = ast_channel_ref(p->chan);
494
495         ao2_unlock(p); /* don't call bridged channel with the pvt locked */
496         bridged_chan = ast_bridged_channel(chan);
497         ao2_lock(p);
498
499         chan = ast_channel_unref(chan);
500
501         /* since we had to unlock p to get the bridged chan, validate our
502          * data once again and verify the bridged channel is what we expect
503          * it to be in order to perform this optimization */
504         if (ast_test_flag(p, LOCAL_ALREADY_MASQED) || !p->owner || !p->chan || (p->chan->_bridge != bridged_chan)) {
505                 return;
506         }
507
508         /* only do the masquerade if we are being called on the outbound channel,
509            if it has been bridged to another channel and if there are no pending
510            frames on the owner channel (because they would be transferred to the
511            outbound channel during the masquerade)
512         */
513         if (p->chan->_bridge /* Not ast_bridged_channel!  Only go one step! */ && AST_LIST_EMPTY(&p->owner->readq)) {
514                 /* Masquerade bridged channel into owner */
515                 /* Lock everything we need, one by one, and give up if
516                    we can't get everything.  Remember, we'll get another
517                    chance in just a little bit */
518                 if (!ast_channel_trylock(p->chan->_bridge)) {
519                         if (!ast_check_hangup(p->chan->_bridge)) {
520                                 if (!ast_channel_trylock(p->owner)) {
521                                         if (!ast_check_hangup(p->owner)) {
522                                                 if (p->owner->monitor && !p->chan->_bridge->monitor) {
523                                                         /* If a local channel is being monitored, we don't want a masquerade
524                                                          * to cause the monitor to go away. Since the masquerade swaps the monitors,
525                                                          * pre-swapping the monitors before the masquerade will ensure that the monitor
526                                                          * ends up where it is expected.
527                                                          */
528                                                         tmp = p->owner->monitor;
529                                                         p->owner->monitor = p->chan->_bridge->monitor;
530                                                         p->chan->_bridge->monitor = tmp;
531                                                 }
532                                                 if (p->chan->audiohooks) {
533                                                         struct ast_audiohook_list *audiohooks_swapper;
534                                                         audiohooks_swapper = p->chan->audiohooks;
535                                                         p->chan->audiohooks = p->owner->audiohooks;
536                                                         p->owner->audiohooks = audiohooks_swapper;
537                                                 }
538
539                                                 /* If any Caller ID was set, preserve it after masquerade like above. We must check
540                                                  * to see if Caller ID was set because otherwise we'll mistakingly copy info not
541                                                  * set from the dialplan and will overwrite the real channel Caller ID. The reason
542                                                  * for this whole preswapping action is because the Caller ID is set on the channel
543                                                  * thread (which is the to be masqueraded away local channel) before both local
544                                                  * channels are optimized away.
545                                                  */
546                                                 if (p->owner->caller.id.name.valid || p->owner->caller.id.number.valid
547                                                         || p->owner->caller.id.subaddress.valid || p->owner->caller.ani.name.valid
548                                                         || p->owner->caller.ani.number.valid || p->owner->caller.ani.subaddress.valid) {
549                                                         struct ast_party_caller tmp;
550                                                         tmp = p->owner->caller;
551                                                         p->owner->caller = p->chan->_bridge->caller;
552                                                         p->chan->_bridge->caller = tmp;
553                                                 }
554                                                 if (p->owner->redirecting.from.name.valid || p->owner->redirecting.from.number.valid
555                                                         || p->owner->redirecting.from.subaddress.valid || p->owner->redirecting.to.name.valid
556                                                         || p->owner->redirecting.to.number.valid || p->owner->redirecting.to.subaddress.valid) {
557                                                         struct ast_party_redirecting tmp;
558                                                         tmp = p->owner->redirecting;
559                                                         p->owner->redirecting = p->chan->_bridge->redirecting;
560                                                         p->chan->_bridge->redirecting = tmp;
561                                                 }
562                                                 if (p->owner->dialed.number.str || p->owner->dialed.subaddress.valid) {
563                                                         struct ast_party_dialed tmp;
564                                                         tmp = p->owner->dialed;
565                                                         p->owner->dialed = p->chan->_bridge->dialed;
566                                                         p->chan->_bridge->dialed = tmp;
567                                                 }
568
569
570                                                 ast_app_group_update(p->chan, p->owner);
571                                                 ast_channel_masquerade(p->owner, p->chan->_bridge);
572                                                 ast_set_flag(p, LOCAL_ALREADY_MASQED);
573                                         }
574                                         ast_channel_unlock(p->owner);
575                                 }
576                         }
577                         ast_channel_unlock(p->chan->_bridge);
578                 }
579         }
580 }
581
582 static struct ast_frame  *local_read(struct ast_channel *ast)
583 {
584         return &ast_null_frame;
585 }
586
587 static int local_write(struct ast_channel *ast, struct ast_frame *f)
588 {
589         struct local_pvt *p = ast->tech_pvt;
590         int res = -1;
591         int isoutbound;
592
593         if (!p) {
594                 return -1;
595         }
596
597         /* Just queue for delivery to the other side */
598         ao2_ref(p, 1); /* ref for local_queue_frame */
599         ao2_lock(p);
600         isoutbound = IS_OUTBOUND(ast, p);
601
602         if (isoutbound && f && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)) {
603                 check_bridge(p);
604         }
605
606         if (!ast_test_flag(p, LOCAL_ALREADY_MASQED)) {
607                 res = local_queue_frame(p, isoutbound, f, ast, 1);
608         } else {
609                 ast_debug(1, "Not posting to queue since already masked on '%s'\n", ast->name);
610                 res = 0;
611         }
612         ao2_unlock(p);
613         ao2_ref(p, -1);
614
615         return res;
616 }
617
618 static int local_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
619 {
620         struct local_pvt *p = newchan->tech_pvt;
621
622         if (!p)
623                 return -1;
624
625         ao2_lock(p);
626
627         if ((p->owner != oldchan) && (p->chan != oldchan)) {
628                 ast_log(LOG_WARNING, "Old channel wasn't %p but was %p/%p\n", oldchan, p->owner, p->chan);
629                 ao2_unlock(p);
630                 return -1;
631         }
632         if (p->owner == oldchan)
633                 p->owner = newchan;
634         else
635                 p->chan = newchan;
636
637         /* Do not let a masquerade cause a Local channel to be bridged to itself! */
638         if (!ast_check_hangup(newchan) && ((p->owner && p->owner->_bridge == p->chan) || (p->chan && p->chan->_bridge == p->owner))) {
639                 ast_log(LOG_WARNING, "You can not bridge a Local channel to itself!\n");
640                 ao2_unlock(p);
641                 ast_queue_hangup(newchan);
642                 return -1;
643         }
644
645         ao2_unlock(p);
646         return 0;
647 }
648
649 static int local_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
650 {
651         struct local_pvt *p = ast->tech_pvt;
652         int res = 0;
653         struct ast_frame f = { AST_FRAME_CONTROL, };
654         int isoutbound;
655
656         if (!p)
657                 return -1;
658
659         ao2_ref(p, 1); /* ref for local_queue_frame */
660
661         /* If this is an MOH hold or unhold, do it on the Local channel versus real channel */
662         if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_HOLD) {
663                 ast_moh_start(ast, data, NULL);
664         } else if (!ast_test_flag(p, LOCAL_MOH_PASSTHRU) && condition == AST_CONTROL_UNHOLD) {
665                 ast_moh_stop(ast);
666         } else if (condition == AST_CONTROL_CONNECTED_LINE || condition == AST_CONTROL_REDIRECTING) {
667                 struct ast_channel *this_channel;
668                 struct ast_channel *the_other_channel;
669                 /* A connected line update frame may only contain a partial amount of data, such
670                  * as just a source, or just a ton, and not the full amount of information. However,
671                  * the collected information is all stored in the outgoing channel's connectedline
672                  * structure, so when receiving a connected line update on an outgoing local channel,
673                  * we need to transmit the collected connected line information instead of whatever
674                  * happens to be in this control frame. The same applies for redirecting information, which
675                  * is why it is handled here as well.*/
676                 ao2_lock(p);
677                 isoutbound = IS_OUTBOUND(ast, p);
678                 if (isoutbound) {
679                         this_channel = p->chan;
680                         the_other_channel = p->owner;
681                 } else {
682                         this_channel = p->owner;
683                         the_other_channel = p->chan;
684                 }
685                 if (the_other_channel) {
686                         unsigned char frame_data[1024];
687                         if (condition == AST_CONTROL_CONNECTED_LINE) {
688                                 if (isoutbound) {
689                                         ast_connected_line_copy_to_caller(&the_other_channel->caller, &this_channel->connected);
690                                 }
691                                 f.datalen = ast_connected_line_build_data(frame_data, sizeof(frame_data), &this_channel->connected, NULL);
692                         } else {
693                                 f.datalen = ast_redirecting_build_data(frame_data, sizeof(frame_data), &this_channel->redirecting, NULL);
694                         }
695                         f.subclass.integer = condition;
696                         f.data.ptr = frame_data;
697                         res = local_queue_frame(p, isoutbound, &f, ast, 1);
698                 }
699                 ao2_unlock(p);
700         } else {
701                 /* Queue up a frame representing the indication as a control frame */
702                 ao2_lock(p);
703                 isoutbound = IS_OUTBOUND(ast, p);
704                 f.subclass.integer = condition;
705                 f.data.ptr = (void*)data;
706                 f.datalen = datalen;
707                 res = local_queue_frame(p, isoutbound, &f, ast, 1);
708                 ao2_unlock(p);
709         }
710
711         ao2_ref(p, -1);
712         return res;
713 }
714
715 static int local_digit_begin(struct ast_channel *ast, char digit)
716 {
717         struct local_pvt *p = ast->tech_pvt;
718         int res = -1;
719         struct ast_frame f = { AST_FRAME_DTMF_BEGIN, };
720         int isoutbound;
721
722         if (!p) {
723                 return -1;
724         }
725
726         ao2_ref(p, 1); /* ref for local_queue_frame */
727         ao2_lock(p);
728         isoutbound = IS_OUTBOUND(ast, p);
729         f.subclass.integer = digit;
730         res = local_queue_frame(p, isoutbound, &f, ast, 0);
731         ao2_unlock(p);
732         ao2_ref(p, -1);
733
734         return res;
735 }
736
737 static int local_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
738 {
739         struct local_pvt *p = ast->tech_pvt;
740         int res = -1;
741         struct ast_frame f = { AST_FRAME_DTMF_END, };
742         int isoutbound;
743
744         if (!p) {
745                 return -1;
746         }
747
748         ao2_ref(p, 1); /* ref for local_queue_frame */
749         ao2_lock(p);
750         isoutbound = IS_OUTBOUND(ast, p);
751         f.subclass.integer = digit;
752         f.len = duration;
753         res = local_queue_frame(p, isoutbound, &f, ast, 0);
754         ao2_unlock(p);
755         ao2_ref(p, -1);
756
757         return res;
758 }
759
760 static int local_sendtext(struct ast_channel *ast, const char *text)
761 {
762         struct local_pvt *p = ast->tech_pvt;
763         int res = -1;
764         struct ast_frame f = { AST_FRAME_TEXT, };
765         int isoutbound;
766
767         if (!p) {
768                 return -1;
769         }
770
771         ao2_lock(p);
772         ao2_ref(p, 1); /* ref for local_queue_frame */
773         isoutbound = IS_OUTBOUND(ast, p);
774         f.data.ptr = (char *) text;
775         f.datalen = strlen(text) + 1;
776         res = local_queue_frame(p, isoutbound, &f, ast, 0);
777         ao2_unlock(p);
778         ao2_ref(p, -1);
779         return res;
780 }
781
782 static int local_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
783 {
784         struct local_pvt *p = ast->tech_pvt;
785         int res = -1;
786         struct ast_frame f = { AST_FRAME_HTML, };
787         int isoutbound;
788
789         if (!p) {
790                 return -1;
791         }
792
793         ao2_lock(p);
794         ao2_ref(p, 1); /* ref for local_queue_frame */
795         isoutbound = IS_OUTBOUND(ast, p);
796         f.subclass.integer = subclass;
797         f.data.ptr = (char *)data;
798         f.datalen = datalen;
799         res = local_queue_frame(p, isoutbound, &f, ast, 0);
800         ao2_unlock(p);
801         ao2_ref(p, -1);
802
803         return res;
804 }
805
806 /*! \brief Initiate new call, part of PBX interface 
807  *      dest is the dial string */
808 static int local_call(struct ast_channel *ast, char *dest, int timeout)
809 {
810         struct local_pvt *p = ast->tech_pvt;
811         int pvt_locked = 0;
812
813         struct ast_channel *owner = NULL;
814         struct ast_channel *chan = NULL;
815         int res;
816         struct ast_var_t *varptr = NULL, *new;
817         size_t len, namelen;
818         char *reduced_dest = ast_strdupa(dest);
819         char *slash;
820         const char *exten;
821         const char *context;
822
823         if (!p) {
824                 return -1;
825         }
826
827         /* since we are letting go of channel locks that were locked coming into
828          * this function, then we need to give the tech pvt a ref */
829         ao2_ref(p, 1);
830         ast_channel_unlock(ast);
831
832         awesome_locking(p, &chan, &owner);
833         pvt_locked = 1;
834
835         if (owner != ast) {
836                 res = -1;
837                 goto return_cleanup;
838         }
839
840         if (!owner || !chan) {
841                 res = -1;
842                 goto return_cleanup;
843         }
844
845         /*
846          * Note that cid_num and cid_name aren't passed in the ast_channel_alloc
847          * call, so it's done here instead.
848          *
849          * All these failure points just return -1. The individual strings will
850          * be cleared when we destroy the channel.
851          */
852         ast_party_redirecting_copy(&chan->redirecting, &owner->redirecting);
853
854         ast_party_dialed_copy(&chan->dialed, &owner->dialed);
855
856         ast_connected_line_copy_to_caller(&chan->caller, &owner->connected);
857         ast_connected_line_copy_from_caller(&chan->connected, &owner->caller);
858
859         ast_string_field_set(chan, language, owner->language);
860         ast_string_field_set(chan, accountcode, owner->accountcode);
861         ast_string_field_set(chan, musicclass, owner->musicclass);
862         ast_cdr_update(chan);
863
864         ast_channel_cc_params_init(chan, ast_channel_get_cc_config_params(owner));
865
866         /* Make sure we inherit the ANSWERED_ELSEWHERE flag if it's set on the queue/dial call request in the dialplan */
867         if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
868                 ast_set_flag(chan, AST_FLAG_ANSWERED_ELSEWHERE);
869         }
870
871         /* copy the channel variables from the incoming channel to the outgoing channel */
872         /* Note that due to certain assumptions, they MUST be in the same order */
873         AST_LIST_TRAVERSE(&owner->varshead, varptr, entries) {
874                 namelen = strlen(varptr->name);
875                 len = sizeof(struct ast_var_t) + namelen + strlen(varptr->value) + 2;
876                 if ((new = ast_calloc(1, len))) {
877                         memcpy(new, varptr, len);
878                         new->value = &(new->name[0]) + namelen + 1;
879                         AST_LIST_INSERT_TAIL(&chan->varshead, new, entries);
880                 }
881         }
882         ast_channel_datastore_inherit(owner, chan);
883         /* If the local channel has /n or /b on the end of it,
884          * we need to lop that off for our argument to setting
885          * up the CC_INTERFACES variable
886          */
887         if ((slash = strrchr(reduced_dest, '/'))) {
888                 *slash = '\0';
889         }
890         ast_set_cc_interfaces_chanvar(chan, reduced_dest);
891
892         exten = ast_strdupa(chan->exten);
893         context = ast_strdupa(chan->context);
894
895         ao2_unlock(p);
896         pvt_locked = 0;
897
898         ast_channel_unlock(chan);
899
900         if (!ast_exists_extension(chan, context, exten, 1,
901                 S_COR(owner->caller.id.number.valid, owner->caller.id.number.str, NULL))) {
902                 ast_log(LOG_NOTICE, "No such extension/context %s@%s while calling Local channel\n", exten, context);
903                 res = -1;
904                 chan = ast_channel_unref(chan); /* we already unlocked it, so clear it hear so the cleanup label won't touch it. */
905                 goto return_cleanup;
906         }
907
908         manager_event(EVENT_FLAG_CALL, "LocalBridge",
909                       "Channel1: %s\r\n"
910                       "Channel2: %s\r\n"
911                       "Uniqueid1: %s\r\n"
912                       "Uniqueid2: %s\r\n"
913                       "Context: %s\r\n"
914                       "Exten: %s\r\n"
915                       "LocalOptimization: %s\n",
916                         p->owner->name, p->chan->name, p->owner->uniqueid, p->chan->uniqueid,
917                         p->context, p->exten,
918                         ast_test_flag(p, LOCAL_NO_OPTIMIZATION) ? "Yes" : "No");
919
920
921         /* Start switch on sub channel */
922         if (!(res = ast_pbx_start(chan))) {
923                 ao2_lock(p);
924                 ast_set_flag(p, LOCAL_LAUNCHED_PBX);
925                 ao2_unlock(p);
926         }
927         chan = ast_channel_unref(chan); /* chan is already unlocked, clear it here so the cleanup lable won't touch it. */
928
929 return_cleanup:
930         if (p) {
931                 if (pvt_locked) {
932                         ao2_unlock(p);
933                 }
934                 ao2_ref(p, -1);
935         }
936         if (chan) {
937                 ast_channel_unlock(chan);
938                 chan = ast_channel_unref(chan);
939         }
940
941         /* owner is supposed to be == to ast,  if it
942          * is, don't unlock it because ast must exit locked */
943         if (owner) {
944                 if (owner != ast) {
945                         ast_channel_unlock(owner);
946                         ast_channel_lock(ast);
947                 }
948                 owner = ast_channel_unref(owner);
949         } else {
950                 /* we have to exit with ast locked */
951                 ast_channel_lock(ast);
952         }
953
954         return res;
955 }
956
957 /*! \brief Hangup a call through the local proxy channel */
958 static int local_hangup(struct ast_channel *ast)
959 {
960         struct local_pvt *p = ast->tech_pvt;
961         int isoutbound;
962         int hangup_chan = 0;
963         int res = 0;
964         struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = ast->hangupcause };
965         struct ast_channel *owner = NULL;
966         struct ast_channel *chan = NULL;
967
968         if (!p) {
969                 return -1;
970         }
971
972         /* give the pvt a ref since we are unlocking the channel. */
973         ao2_ref(p, 1);
974
975         /* the pvt isn't going anywhere, we gave it a ref */
976         ast_channel_unlock(ast);
977
978         /* lock everything */
979         awesome_locking(p, &chan, &owner);
980
981         if (ast != chan && ast != owner) {
982                 res = -1;
983                 goto local_hangup_cleanup;
984         }
985
986         isoutbound = IS_OUTBOUND(ast, p); /* just comparing pointer of ast */
987
988         if (p->chan && ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
989                 ast_set_flag(p->chan, AST_FLAG_ANSWERED_ELSEWHERE);
990                 ast_debug(2, "This local call has the ANSWERED_ELSEWHERE flag set.\n");
991         }
992
993         if (isoutbound) {
994                 const char *status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
995                 if ((status) && (p->owner)) {
996                         p->owner->hangupcause = p->chan->hangupcause;
997                         pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
998                 }
999
1000                 ast_clear_flag(p, LOCAL_LAUNCHED_PBX);
1001                 ast_module_user_remove(p->u_chan);
1002                 p->chan = NULL;
1003         } else {
1004                 ast_module_user_remove(p->u_owner);
1005                 if (p->chan) {
1006                         ast_queue_hangup(p->chan);
1007                 }
1008                 p->owner = NULL;
1009         }
1010
1011         ast->tech_pvt = NULL; /* this is one of our locked channels, doesn't matter which */
1012
1013         if (!p->owner && !p->chan) {
1014                 ao2_unlock(p);
1015                 /* Remove from list */
1016                 ao2_unlink(locals, p);
1017                 ao2_ref(p, -1);
1018                 p = NULL;
1019                 res = 0;
1020                 goto local_hangup_cleanup;
1021         }
1022         if (p->chan && !ast_test_flag(p, LOCAL_LAUNCHED_PBX)) {
1023                 /* Need to actually hangup since there is no PBX */
1024                 hangup_chan = 1;
1025         } else {
1026                 local_queue_frame(p, isoutbound, &f, NULL, 0);
1027         }
1028
1029 local_hangup_cleanup:
1030         if (p) {
1031                 ao2_unlock(p);
1032                 ao2_ref(p, -1);
1033         }
1034         if (chan) {
1035                 ast_channel_unlock(chan);
1036                 if (hangup_chan) {
1037                         ast_hangup(chan);
1038                 }
1039                 chan = ast_channel_unref(chan);
1040         }
1041         if (owner) {
1042                 ast_channel_unlock(owner);
1043                 owner = ast_channel_unref(owner);
1044         }
1045
1046         /* leave with the same stupid channel locked that came in */
1047         ast_channel_lock(ast);
1048         return res;
1049 }
1050
1051 static void local_destroy(void *obj)
1052 {
1053         struct local_pvt *pvt = obj;
1054         pvt->reqcap = ast_format_cap_destroy(pvt->reqcap);
1055 }
1056
1057 /*! \brief Create a call structure */
1058 static struct local_pvt *local_alloc(const char *data, struct ast_format_cap *cap)
1059 {
1060         struct local_pvt *tmp = NULL;
1061         char *c = NULL, *opts = NULL;
1062
1063         if (!(tmp = ao2_alloc(sizeof(*tmp), local_destroy))) {
1064                 return NULL;
1065         }
1066         if (!(tmp->reqcap = ast_format_cap_dup(cap))) {
1067                 ao2_ref(tmp, -1);
1068                 return NULL;
1069         }
1070
1071         /* Initialize private structure information */
1072         ast_copy_string(tmp->exten, data, sizeof(tmp->exten));
1073
1074         memcpy(&tmp->jb_conf, &g_jb_conf, sizeof(tmp->jb_conf));
1075
1076         /* Look for options */
1077         if ((opts = strchr(tmp->exten, '/'))) {
1078                 *opts++ = '\0';
1079                 if (strchr(opts, 'n'))
1080                         ast_set_flag(tmp, LOCAL_NO_OPTIMIZATION);
1081                 if (strchr(opts, 'j')) {
1082                         if (ast_test_flag(tmp, LOCAL_NO_OPTIMIZATION))
1083                                 ast_set_flag(&tmp->jb_conf, AST_JB_ENABLED);
1084                         else {
1085                                 ast_log(LOG_ERROR, "You must use the 'n' option for chan_local "
1086                                         "to use the 'j' option to enable the jitterbuffer\n");
1087                         }
1088                 }
1089                 if (strchr(opts, 'b')) {
1090                         ast_set_flag(tmp, LOCAL_BRIDGE);
1091                 }
1092                 if (strchr(opts, 'm')) {
1093                         ast_set_flag(tmp, LOCAL_MOH_PASSTHRU);
1094                 }
1095         }
1096
1097         /* Look for a context */
1098         if ((c = strchr(tmp->exten, '@')))
1099                 *c++ = '\0';
1100
1101         ast_copy_string(tmp->context, c ? c : "default", sizeof(tmp->context));
1102 #if 0
1103         /* We can't do this check here, because we don't know the CallerID yet, and
1104          * the CallerID could potentially affect what step is actually taken (or
1105          * even if that step exists). */
1106         if (!ast_exists_extension(NULL, tmp->context, tmp->exten, 1, NULL)) {
1107                 ast_log(LOG_NOTICE, "No such extension/context %s@%s creating local channel\n", tmp->exten, tmp->context);
1108                 tmp = local_pvt_destroy(tmp);
1109         } else {
1110 #endif
1111                 /* Add to list */
1112                 ao2_link(locals, tmp);
1113 #if 0
1114         }
1115 #endif
1116         return tmp; /* this is returned with a ref */
1117 }
1118
1119 /*! \brief Start new local channel */
1120 static struct ast_channel *local_new(struct local_pvt *p, int state, const char *linkedid)
1121 {
1122         struct ast_channel *tmp = NULL, *tmp2 = NULL;
1123         int randnum = ast_random() & 0xffff;
1124         struct ast_format fmt;
1125         const char *t;
1126         int ama;
1127
1128         /* Allocate two new Asterisk channels */
1129         /* safe accountcode */
1130         if (p->owner && p->owner->accountcode)
1131                 t = p->owner->accountcode;
1132         else
1133                 t = "";
1134
1135         if (p->owner)
1136                 ama = p->owner->amaflags;
1137         else
1138                 ama = 0;
1139         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)) 
1140                 || !(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))) {
1141                 if (tmp) {
1142                         tmp = ast_channel_release(tmp);
1143                 }
1144                 ast_log(LOG_WARNING, "Unable to allocate channel structure(s)\n");
1145                 return NULL;
1146         }
1147
1148         tmp2->tech = tmp->tech = &local_tech;
1149
1150         ast_format_cap_copy(tmp->nativeformats, p->reqcap);
1151         ast_format_cap_copy(tmp2->nativeformats, p->reqcap);
1152
1153         /* Determine our read/write format and set it on each channel */
1154         ast_best_codec(p->reqcap, &fmt);
1155         ast_format_copy(&tmp->writeformat, &fmt);
1156         ast_format_copy(&tmp2->writeformat, &fmt);
1157         ast_format_copy(&tmp->rawwriteformat, &fmt);
1158         ast_format_copy(&tmp2->rawwriteformat, &fmt);
1159         ast_format_copy(&tmp->readformat, &fmt);
1160         ast_format_copy(&tmp2->readformat, &fmt);
1161         ast_format_copy(&tmp->rawreadformat, &fmt);
1162         ast_format_copy(&tmp2->rawreadformat, &fmt);
1163
1164         tmp->tech_pvt = p;
1165         tmp2->tech_pvt = p;
1166
1167         p->owner = tmp;
1168         p->chan = tmp2;
1169         p->u_owner = ast_module_user_add(p->owner);
1170         p->u_chan = ast_module_user_add(p->chan);
1171
1172         ast_copy_string(tmp->context, p->context, sizeof(tmp->context));
1173         ast_copy_string(tmp2->context, p->context, sizeof(tmp2->context));
1174         ast_copy_string(tmp2->exten, p->exten, sizeof(tmp->exten));
1175         tmp->priority = 1;
1176         tmp2->priority = 1;
1177
1178         ast_jb_configure(tmp, &p->jb_conf);
1179
1180         return tmp;
1181 }
1182
1183 /*! \brief Part of PBX interface */
1184 static struct ast_channel *local_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, void *data, int *cause)
1185 {
1186         struct local_pvt *p = NULL;
1187         struct ast_channel *chan = NULL;
1188
1189         /* Allocate a new private structure and then Asterisk channel */
1190         if ((p = local_alloc(data, cap))) {
1191                 if (!(chan = local_new(p, AST_STATE_DOWN, requestor ? requestor->linkedid : NULL))) {
1192                         ao2_unlink(locals, p);
1193                 }
1194                 if (chan && ast_channel_cc_params_init(chan, requestor ? ast_channel_get_cc_config_params((struct ast_channel *)requestor) : NULL)) {
1195                         chan = ast_channel_release(chan);
1196                         ao2_unlink(locals, p);
1197                 }
1198                 ao2_ref(p, -1); /* kill the ref from the alloc */
1199         }
1200
1201         return chan;
1202 }
1203
1204 /*! \brief CLI command "local show channels" */
1205 static char *locals_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1206 {
1207         struct local_pvt *p = NULL;
1208         struct ao2_iterator it;
1209
1210         switch (cmd) {
1211         case CLI_INIT:
1212                 e->command = "local show channels";
1213                 e->usage =
1214                         "Usage: local show channels\n"
1215                         "       Provides summary information on active local proxy channels.\n";
1216                 return NULL;
1217         case CLI_GENERATE:
1218                 return NULL;
1219         }
1220
1221         if (a->argc != 3)
1222                 return CLI_SHOWUSAGE;
1223
1224         if (ao2_container_count(locals) == 0) {
1225                 ast_cli(a->fd, "No local channels in use\n");
1226                 return RESULT_SUCCESS;
1227         }
1228
1229         it = ao2_iterator_init(locals, 0);
1230         while ((p = ao2_iterator_next(&it))) {
1231                 ao2_lock(p);
1232                 ast_cli(a->fd, "%s -- %s@%s\n", p->owner ? p->owner->name : "<unowned>", p->exten, p->context);
1233                 ao2_unlock(p);
1234                 ao2_ref(p, -1);
1235         }
1236         ao2_iterator_destroy(&it);
1237
1238         return CLI_SUCCESS;
1239 }
1240
1241 static struct ast_cli_entry cli_local[] = {
1242         AST_CLI_DEFINE(locals_show, "List status of local channels"),
1243 };
1244
1245 static int manager_optimize_away(struct mansession *s, const struct message *m)
1246 {
1247         const char *channel;
1248         struct local_pvt *p, *tmp = NULL;
1249         struct ast_channel *c;
1250         int found = 0;
1251         struct ao2_iterator it;
1252
1253         channel = astman_get_header(m, "Channel");
1254
1255         if (ast_strlen_zero(channel)) {
1256                 astman_send_error(s, m, "'Channel' not specified.");
1257                 return 0;
1258         }
1259
1260         c = ast_channel_get_by_name(channel);
1261         if (!c) {
1262                 astman_send_error(s, m, "Channel does not exist.");
1263                 return 0;
1264         }
1265
1266         p = c->tech_pvt;
1267         ast_channel_unref(c);
1268         c = NULL;
1269
1270         it = ao2_iterator_init(locals, 0);
1271         while ((tmp = ao2_iterator_next(&it))) {
1272                 if (tmp == p) {
1273                         ao2_lock(tmp);
1274                         found = 1;
1275                         ast_clear_flag(tmp, LOCAL_NO_OPTIMIZATION);
1276                         ao2_unlock(tmp);
1277                         ao2_ref(tmp, -1);
1278                         break;
1279                 }
1280                 ao2_ref(tmp, -1);
1281         }
1282         ao2_iterator_destroy(&it);
1283
1284         if (found) {
1285                 astman_send_ack(s, m, "Queued channel to be optimized away");
1286         } else {
1287                 astman_send_error(s, m, "Unable to find channel");
1288         }
1289
1290         return 0;
1291 }
1292
1293
1294 static int locals_cmp_cb(void *obj, void *arg, int flags)
1295 {
1296         return (obj == arg) ? CMP_MATCH : 0;
1297 }
1298
1299 /*! \brief Load module into PBX, register channel */
1300 static int load_module(void)
1301 {
1302         if (!(local_tech.capabilities = ast_format_cap_alloc())) {
1303                 return AST_MODULE_LOAD_FAILURE;
1304         }
1305         ast_format_cap_add_all(local_tech.capabilities);
1306
1307         if (!(locals = ao2_container_alloc(BUCKET_SIZE, NULL, locals_cmp_cb))) {
1308                 ast_format_cap_destroy(local_tech.capabilities);
1309                 return AST_MODULE_LOAD_FAILURE;
1310         }
1311
1312         /* Make sure we can register our channel type */
1313         if (ast_channel_register(&local_tech)) {
1314                 ast_log(LOG_ERROR, "Unable to register channel class 'Local'\n");
1315                 ao2_ref(locals, -1);
1316                 ast_format_cap_destroy(local_tech.capabilities);
1317                 return AST_MODULE_LOAD_FAILURE;
1318         }
1319         ast_cli_register_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1320         ast_manager_register_xml("LocalOptimizeAway", EVENT_FLAG_SYSTEM|EVENT_FLAG_CALL, manager_optimize_away);
1321
1322         return AST_MODULE_LOAD_SUCCESS;
1323 }
1324
1325 /*! \brief Unload the local proxy channel from Asterisk */
1326 static int unload_module(void)
1327 {
1328         struct local_pvt *p = NULL;
1329         struct ao2_iterator it;
1330
1331         /* First, take us out of the channel loop */
1332         ast_cli_unregister_multiple(cli_local, sizeof(cli_local) / sizeof(struct ast_cli_entry));
1333         ast_manager_unregister("LocalOptimizeAway");
1334         ast_channel_unregister(&local_tech);
1335
1336         it = ao2_iterator_init(locals, 0);
1337         while ((p = ao2_iterator_next(&it))) {
1338                 if (p->owner) {
1339                         ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
1340                 }
1341                 ao2_ref(p, -1);
1342         }
1343         ao2_iterator_destroy(&it);
1344         ao2_ref(locals, -1);
1345
1346         ast_format_cap_destroy(local_tech.capabilities);
1347         return 0;
1348 }
1349
1350 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Local Proxy Channel (Note: used internally by other modules)",
1351                 .load = load_module,
1352                 .unload = unload_module,
1353                 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
1354         );