Debian Codegraph @

main/core_local.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 2013 Digium, Inc.
5 *
6 * Richard Mudgett <[email protected]>
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 /*!
20 * \file
21 * \brief Local proxy channel driver.
22 *
23 * \author Richard Mudgett <[email protected]>
24 *
25 * See Also:
26 * \arg \ref AstCREDITS
27 */
28
29 /*** MODULEINFO
30 <support_level>core</support_level>
31 ***/
32
33
34 #include "asterisk.h"
35
36 /* ------------------------------------------------------------------- */
37
38 #include "asterisk/channel.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/cli.h"
41 #include "asterisk/manager.h"
42 #include "asterisk/devicestate.h"
43 #include "asterisk/astobj2.h"
44 #include "asterisk/bridge.h"
45 #include "asterisk/core_unreal.h"
46 #include "asterisk/core_local.h"
47 #include "asterisk/stasis.h"
48 #include "asterisk/stasis_channels.h"
49 #include "asterisk/_private.h"
50 #include "asterisk/stasis_channels.h"
51 #include "asterisk/stream.h"
52 #include "asterisk/translate.h"
53
54 /*** DOCUMENTATION
55 <manager name="LocalOptimizeAway" language="en_US">
56 <since>
57 <version>1.8.0</version>
58 </since>
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 <managerEvent language="en_US" name="LocalBridge">
75 <managerEventInstance class="EVENT_FLAG_CALL">
76 <since>
77 <version>12.0.0</version>
78 </since>
79 <synopsis>Raised when two halves of a Local Channel form a bridge.</synopsis>
80 <syntax>
81 <channel_snapshot prefix="LocalOne"/>
82 <channel_snapshot prefix="LocalTwo"/>
83 <parameter name="Context">
84 <para>The context in the dialplan that Channel2 starts in.</para>
85 </parameter>
86 <parameter name="Exten">
87 <para>The extension in the dialplan that Channel2 starts in.</para>
88 </parameter>
89 <parameter name="LocalOptimization">
90 <enumlist>
91 <enum name="Yes"/>
92 <enum name="No"/>
93 </enumlist>
94 </parameter>
95 </syntax>
96 </managerEventInstance>
97 </managerEvent>
98 <managerEvent language="en_US" name="LocalOptimizationBegin">
99 <managerEventInstance class="EVENT_FLAG_CALL">
100 <since>
101 <version>12.0.0</version>
102 </since>
103 <synopsis>Raised when two halves of a Local Channel begin to optimize
104 themselves out of the media path.</synopsis>
105 <syntax>
106 <channel_snapshot prefix="LocalOne"/>
107 <channel_snapshot prefix="LocalTwo"/>
108 <channel_snapshot prefix="Source"/>
109 <parameter name="DestUniqueId">
110 <para>The unique ID of the bridge into which the local channel is optimizing.</para>
111 </parameter>
112 <parameter name="Id">
113 <para>Identification for the optimization operation.</para>
114 </parameter>
115 </syntax>
116 <see-also>
117 <ref type="managerEvent">LocalOptimizationEnd</ref>
118 <ref type="manager">LocalOptimizeAway</ref>
119 </see-also>
120 </managerEventInstance>
121 </managerEvent>
122 <managerEvent language="en_US" name="LocalOptimizationEnd">
123 <managerEventInstance class="EVENT_FLAG_CALL">
124 <since>
125 <version>12.0.0</version>
126 </since>
127 <synopsis>Raised when two halves of a Local Channel have finished optimizing
128 themselves out of the media path.</synopsis>
129 <syntax>
130 <channel_snapshot prefix="LocalOne"/>
131 <channel_snapshot prefix="LocalTwo"/>
132 <parameter name="Success">
133 <para>Indicates whether the local optimization succeeded.</para>
134 </parameter>
135 <parameter name="Id">
136 <para>Identification for the optimization operation. Matches the <replaceable>Id</replaceable>
137 from a previous <literal>LocalOptimizationBegin</literal></para>
138 </parameter>
139 </syntax>
140 <see-also>
141 <ref type="managerEvent">LocalOptimizationBegin</ref>
142 <ref type="manager">LocalOptimizeAway</ref>
143 </see-also>
144 </managerEventInstance>
145 </managerEvent>
146 ***/
147
148 static const char tdesc[] = "Local Proxy Channel Driver";
149
150 static struct ao2_container *locals;
151
152 static struct ast_channel *local_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
153 static struct ast_channel *local_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
154 static int local_call(struct ast_channel *ast, const char *dest, int timeout);
155 static int local_hangup(struct ast_channel *ast);
156 static int local_devicestate(const char *data);
157 static void local_optimization_started_cb(struct ast_unreal_pvt *base, struct ast_channel *source,
158 enum ast_unreal_channel_indicator dest, unsigned int id);
159 static void local_optimization_finished_cb(struct ast_unreal_pvt *base, int success, unsigned int id);
160 static int local_setoption(struct ast_channel *chan, int option, void *data, int datalen);
161
162 static struct ast_manager_event_blob *local_message_to_ami(struct stasis_message *msg);
163
164 /*!
165 * @{ \brief Define local channel message types.
166 */
167 STASIS_MESSAGE_TYPE_DEFN(ast_local_bridge_type,
168 .to_ami = local_message_to_ami,
169 );
170 STASIS_MESSAGE_TYPE_DEFN(ast_local_optimization_begin_type,
171 .to_ami = local_message_to_ami,
172 );
173 STASIS_MESSAGE_TYPE_DEFN(ast_local_optimization_end_type,
174 .to_ami = local_message_to_ami,
175 );
176 /*! @} */
177
178 /*! \brief Callbacks from the unreal core when channel optimization occurs */
179 struct ast_unreal_pvt_callbacks local_unreal_callbacks = {
180 .optimization_started = local_optimization_started_cb,
181 .optimization_finished = local_optimization_finished_cb,
182 };
183
184 /* PBX interface structure for channel registration */
185 static struct ast_channel_tech local_tech = {
186 .type = "Local",
187 .description = tdesc,
188 .requester = local_request,
189 .requester_with_stream_topology = local_request_with_stream_topology,
190 .send_digit_begin = ast_unreal_digit_begin,
191 .send_digit_end = ast_unreal_digit_end,
192 .call = local_call,
193 .hangup = local_hangup,
194 .answer = ast_unreal_answer,
195 .read_stream = ast_unreal_read,
196 .write = ast_unreal_write,
197 .write_stream = ast_unreal_write_stream,
198 .exception = ast_unreal_read,
199 .indicate = ast_unreal_indicate,
200 .fixup = ast_unreal_fixup,
201 .send_html = ast_unreal_sendhtml,
202 .send_text = ast_unreal_sendtext,
203 .devicestate = local_devicestate,
204 .queryoption = ast_unreal_queryoption,
205 .setoption = local_setoption,
206 };
207
208 /*! What to do with the ;2 channel when ast_call() happens. */
209 enum local_call_action {
210 /* The ast_call() will run dialplan on the ;2 channel. */
211 LOCAL_CALL_ACTION_DIALPLAN,
212 /* The ast_call() will impart the ;2 channel into a bridge. */
213 LOCAL_CALL_ACTION_BRIDGE,
214 /* The ast_call() will masquerade the ;2 channel into a channel. */
215 LOCAL_CALL_ACTION_MASQUERADE,
216 };
217
218 /*! Join a bridge on ast_call() parameters. */
219 struct local_bridge {
220 /*! Bridge to join. */
221 struct ast_bridge *join;
222 /*! Channel to swap with when joining bridge. */
223 struct ast_channel *swap;
224 /*! Features that are specific to this channel when pushed into the bridge. */
225 struct ast_bridge_features *features;
226 };
227
228 /*!
229 * \brief the local pvt structure for all channels
230 *
231 * The local channel pvt has two ast_chan objects - the "owner" and the "next channel", the outbound channel
232 *
233 * ast_chan owner -> local_pvt -> ast_chan chan
234 */
235 struct local_pvt {
236 /*! Unreal channel driver base class values. */
237 struct ast_unreal_pvt base;
238 /*! Additional action arguments */
239 union {
240 /*! Make ;2 join a bridge on ast_call(). */
241 struct local_bridge bridge;
242 /*! Make ;2 masquerade into this channel on ast_call(). */
243 struct ast_channel *masq;
244 } action;
245 /*! What to do with the ;2 channel on ast_call(). */
246 enum local_call_action type;
247 /*! Context to call */
248 char context[AST_MAX_CONTEXT];
249 /*! Extension to call */
250 char exten[AST_MAX_EXTENSION];
251 };
252
253 void ast_local_lock_all(struct ast_channel *chan, void **tech_pvt,
254 struct ast_channel **base_chan, struct ast_channel **base_owner)
255 {
256 struct local_pvt *p = ast_channel_tech_pvt(chan);
257
258 *tech_pvt = NULL;
259 *base_chan = NULL;
260 *base_owner = NULL;
261
262 if (p) {
263 *tech_pvt = ao2_bump(p);
264 ast_unreal_lock_all(&p->base, base_chan, base_owner);
265 }
266 }
267
268 void ast_local_unlock_all(void *tech_pvt, struct ast_channel *base_chan,
269 struct ast_channel *base_owner)
270 {
271 if (base_chan) {
272 ast_channel_unlock(base_chan);
273 ast_channel_unref(base_chan);
274 }
275
276 if (base_owner) {
277 ast_channel_unlock(base_owner);
278 ast_channel_unref(base_owner);
279 }
280
281 if (tech_pvt) {
282 struct local_pvt *p = tech_pvt;
283 ao2_unlock(&p->base);
284 ao2_ref(tech_pvt, -1);
285 }
286 }
287
288 struct ast_channel *ast_local_get_peer(struct ast_channel *ast)
289 {
290 struct local_pvt *p = ast_channel_tech_pvt(ast);
291 struct local_pvt *found;
292 struct ast_channel *peer;
293
294 if (!p) {
295 return NULL;
296 }
297
298 found = p ? ao2_find(locals, p, 0) : NULL;
299 if (!found) {
300 /* ast is either not a local channel or it has already been hungup */
301 return NULL;
302 }
303 ao2_lock(found);
304 if (ast == p->base.owner) {
305 peer = p->base.chan;
306 } else if (ast == p->base.chan) {
307 peer = p->base.owner;
308 } else {
309 peer = NULL;
310 }
311 if (peer) {
312 ast_channel_ref(peer);
313 }
314 ao2_unlock(found);
315 ao2_ref(found, -1);
316 return peer;
317 }
318
319 /*! \brief Adds devicestate to local channels */
320 static int local_devicestate(const char *data)
321 {
322 int is_inuse = 0;
323 int res = AST_DEVICE_INVALID;
324 char *exten = ast_strdupa(data);
325 char *context;
326 char *opts;
327 struct local_pvt *lp;
328 struct ao2_iterator it;
329
330 context = strchr(exten, '@');
331 if (!context) {
332 ast_log(LOG_WARNING,
333 "Someone used Local/%s somewhere without a @context. This is bad.\n", data);
334 return AST_DEVICE_INVALID;
335 }
336 *context++ = '\0';
337
338 /* Strip options if they exist.
339 * However, don't strip '/' before an '@' (exten could contain slashes).
340 * So only start looking for '/' in context, because options would be past
341 * this point if they exist, but anything before would be a '/' in the exten,
342 * not options. */
343 opts = strchr(context, '/');
344 if (opts) {
345 *opts = '\0';
346 }
347
348 it = ao2_iterator_init(locals, 0);
349 for (; (lp = ao2_iterator_next(&it)); ao2_ref(lp, -1)) {
350 ao2_lock(lp);
351 if (!strcmp(exten, lp->exten)
352 && !strcmp(context, lp->context)) {
353 res = AST_DEVICE_NOT_INUSE;
354 if (lp->base.owner
355 && ast_test_flag(&lp->base, AST_UNREAL_CARETAKER_THREAD)) {
356 is_inuse = 1;
357 }
358 }
359 ao2_unlock(lp);
360 if (is_inuse) {
361 res = AST_DEVICE_INUSE;
362 ao2_ref(lp, -1);
363 break;
364 }
365 }
366 ao2_iterator_destroy(&it);
367
368 if (res == AST_DEVICE_INVALID) {
369 ast_debug(3, "Checking if extension %s@%s exists (devicestate)\n", exten, context);
370 if (ast_exists_extension(NULL, context, exten, 1, NULL)) {
371 res = AST_DEVICE_NOT_INUSE;
372 }
373 }
374
375 return res;
376 }
377
378 static struct ast_multi_channel_blob *local_channel_optimization_blob(struct local_pvt *p,
379 struct ast_json *json_object)
380 {
381 struct ast_multi_channel_blob *payload;
382 RAII_VAR(struct ast_channel_snapshot *, local_one_snapshot, NULL, ao2_cleanup);
383 RAII_VAR(struct ast_channel_snapshot *, local_two_snapshot, NULL, ao2_cleanup);
384
385 local_one_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(p->base.owner));
386 if (!local_one_snapshot) {
387 return NULL;
388 }
389
390 local_two_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(p->base.chan));
391 if (!local_two_snapshot) {
392 return NULL;
393 }
394
395 payload = ast_multi_channel_blob_create(json_object);
396 if (!payload) {
397 return NULL;
398 }
399 ast_multi_channel_blob_add_channel(payload, "1", local_one_snapshot);
400 ast_multi_channel_blob_add_channel(payload, "2", local_two_snapshot);
401
402 return payload;
403 }
404
405 /*! \brief Callback for \ref ast_unreal_pvt_callbacks \p optimization_started */
406 static void local_optimization_started_cb(struct ast_unreal_pvt *base, struct ast_channel *source,
407 enum ast_unreal_channel_indicator dest, unsigned int id)
408 {
409 RAII_VAR(struct ast_json *, json_object, ast_json_null(), ast_json_unref);
410 RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
411 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
412 struct local_pvt *p = (struct local_pvt *)base;
413
414 if (!ast_local_optimization_begin_type()) {
415 return;
416 }
417
418 json_object = ast_json_pack("{s: i, s: I}",
419 "dest", dest, "id", (ast_json_int_t)id);
420
421 if (!json_object) {
422 return;
423 }
424
425 payload = local_channel_optimization_blob(p, json_object);
426 if (!payload) {
427 return;
428 }
429
430 if (source) {
431 RAII_VAR(struct ast_channel_snapshot *, source_snapshot, NULL, ao2_cleanup);
432 source_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(source));
433 if (!source_snapshot) {
434 return;
435 }
436
437 ast_multi_channel_blob_add_channel(payload, "source", source_snapshot);
438 }
439
440 msg = stasis_message_create(ast_local_optimization_begin_type(), payload);
441 if (!msg) {
442 return;
443 }
444
445 stasis_publish(ast_channel_topic(p->base.owner), msg);
446 }
447
448 /*! \brief Callback for \ref ast_unreal_pvt_callbacks \p optimization_finished */
449 static void local_optimization_finished_cb(struct ast_unreal_pvt *base, int success, unsigned int id)
450 {
451 RAII_VAR(struct ast_json *, json_object, ast_json_null(), ast_json_unref);
452 RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
453 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
454 struct local_pvt *p = (struct local_pvt *)base;
455
456 if (!ast_local_optimization_end_type()) {
457 return;
458 }
459
460 json_object = ast_json_pack("{s: i, s: I}", "success", success, "id", (ast_json_int_t)id);
461
462 if (!json_object) {
463 return;
464 }
465
466 payload = local_channel_optimization_blob(p, json_object);
467 if (!payload) {
468 return;
469 }
470
471 msg = stasis_message_create(ast_local_optimization_end_type(), payload);
472 if (!msg) {
473 return;
474 }
475
476 stasis_publish(ast_channel_topic(p->base.owner), msg);
477 }
478
479 static struct ast_manager_event_blob *local_message_to_ami(struct stasis_message *message)
480 {
481 struct ast_multi_channel_blob *obj = stasis_message_data(message);
482 struct ast_json *blob = ast_multi_channel_blob_get_json(obj);
483 struct ast_channel_snapshot *local_snapshot_one;
484 struct ast_channel_snapshot *local_snapshot_two;
485 RAII_VAR(struct ast_str *, local_channel_one, NULL, ast_free);
486 RAII_VAR(struct ast_str *, local_channel_two, NULL, ast_free);
487 RAII_VAR(struct ast_str *, event_buffer, NULL, ast_free);
488 const char *event;
489
490 local_snapshot_one = ast_multi_channel_blob_get_channel(obj, "1");
491 local_snapshot_two = ast_multi_channel_blob_get_channel(obj, "2");
492 if (!local_snapshot_one || !local_snapshot_two) {
493 return NULL;
494 }
495
496 event_buffer = ast_str_create(1024);
497 local_channel_one = ast_manager_build_channel_state_string_prefix(local_snapshot_one, "LocalOne");
498 local_channel_two = ast_manager_build_channel_state_string_prefix(local_snapshot_two, "LocalTwo");
499 if (!event_buffer || !local_channel_one || !local_channel_two) {
500 return NULL;
501 }
502
503 if (stasis_message_type(message) == ast_local_optimization_begin_type()) {
504 struct ast_channel_snapshot *source_snapshot;
505 RAII_VAR(struct ast_str *, source_str, NULL, ast_free);
506 const char *dest_uniqueid;
507
508 source_snapshot = ast_multi_channel_blob_get_channel(obj, "source");
509 if (source_snapshot) {
510 source_str = ast_manager_build_channel_state_string_prefix(source_snapshot, "Source");
511 if (!source_str) {
512 return NULL;
513 }
514 }
515
516 dest_uniqueid = ast_json_object_get(blob, "dest") == AST_UNREAL_OWNER ?
517 local_snapshot_one->base->uniqueid : local_snapshot_two->base->uniqueid;
518
519 event = "LocalOptimizationBegin";
520 if (source_str) {
521 ast_str_append(&event_buffer, 0, "%s", ast_str_buffer(source_str));
522 }
523 ast_str_append(&event_buffer, 0, "DestUniqueId: %s\r\n", dest_uniqueid);
524 ast_str_append(&event_buffer, 0, "Id: %u\r\n", (unsigned int) ast_json_integer_get(ast_json_object_get(blob, "id")));
525 } else if (stasis_message_type(message) == ast_local_optimization_end_type()) {
526 event = "LocalOptimizationEnd";
527 ast_str_append(&event_buffer, 0, "Success: %s\r\n", ast_json_integer_get(ast_json_object_get(blob, "success")) ? "Yes" : "No");
528 ast_str_append(&event_buffer, 0, "Id: %u\r\n", (unsigned int) ast_json_integer_get(ast_json_object_get(blob, "id")));
529 } else if (stasis_message_type(message) == ast_local_bridge_type()) {
530 event = "LocalBridge";
531 ast_str_append(&event_buffer, 0, "Context: %s\r\n", ast_json_string_get(ast_json_object_get(blob, "context")));
532 ast_str_append(&event_buffer, 0, "Exten: %s\r\n", ast_json_string_get(ast_json_object_get(blob, "exten")));
533 ast_str_append(&event_buffer, 0, "LocalOptimization: %s\r\n", ast_json_is_true(ast_json_object_get(blob, "can_optimize")) ? "Yes" : "No");
534 } else {
535 return NULL;
536 }
537
538 return ast_manager_event_blob_create(EVENT_FLAG_CALL, event,
539 "%s"
540 "%s"
541 "%s",
542 ast_str_buffer(local_channel_one),
543 ast_str_buffer(local_channel_two),
544 ast_str_buffer(event_buffer));
545 }
546
547 /*!
548 * \internal
549 * \brief Post the \ref ast_local_bridge_type \ref stasis message
550 * \since 12.0.0
551 *
552 * \param p local_pvt to raise the local bridge message
553 */
554 static void publish_local_bridge_message(struct local_pvt *p)
555 {
556 RAII_VAR(struct ast_multi_channel_blob *, multi_blob, NULL, ao2_cleanup);
557 RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
558 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
559 RAII_VAR(struct ast_channel_snapshot *, one_snapshot, NULL, ao2_cleanup);
560 RAII_VAR(struct ast_channel_snapshot *, two_snapshot, NULL, ao2_cleanup);
561 struct ast_channel *owner;
562 struct ast_channel *chan;
563
564 if (!ast_local_bridge_type()) {
565 return;
566 }
567
568 ast_unreal_lock_all(&p->base, &chan, &owner);
569
570 blob = ast_json_pack("{s: s, s: s, s: b}",
571 "context", p->context,
572 "exten", p->exten,
573 "can_optimize", !ast_test_flag(&p->base, AST_UNREAL_NO_OPTIMIZATION));
574 if (!blob) {
575 goto end;
576 }
577
578 multi_blob = ast_multi_channel_blob_create(blob);
579 if (!multi_blob) {
580 goto end;
581 }
582
583 one_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(owner));
584 if (!one_snapshot) {
585 goto end;
586 }
587
588 two_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan));
589 if (!two_snapshot) {
590 goto end;
591 }
592
593 ast_multi_channel_blob_add_channel(multi_blob, "1", one_snapshot);
594 ast_multi_channel_blob_add_channel(multi_blob, "2", two_snapshot);
595
596 msg = stasis_message_create(ast_local_bridge_type(), multi_blob);
597 if (!msg) {
598 goto end;
599 }
600
601 stasis_publish(ast_channel_topic(owner), msg);
602
603 end:
604 ast_channel_unlock(owner);
605 ast_channel_unref(owner);
606
607 ast_channel_unlock(chan);
608 ast_channel_unref(chan);
609
610 ao2_unlock(&p->base);
611 }
612
613 int ast_local_setup_bridge(struct ast_channel *ast, struct ast_bridge *bridge, struct ast_channel *swap, struct ast_bridge_features *features)
614 {
615 struct local_pvt *p;
616 struct local_pvt *found;
617 int res = -1;
618
619 /* Sanity checks. */
620 if (!ast || !bridge) {
621 ast_bridge_features_destroy(features);
622 return -1;
623 }
624
625 ast_channel_lock(ast);
626 p = ast_channel_tech_pvt(ast);
627 ast_channel_unlock(ast);
628
629 found = p ? ao2_find(locals, p, 0) : NULL;
630 if (found) {
631 ao2_lock(found);
632 if (found->type == LOCAL_CALL_ACTION_DIALPLAN
633 && found->base.owner
634 && found->base.chan
635 && !ast_test_flag(&found->base, AST_UNREAL_CARETAKER_THREAD)) {
636 ao2_ref(bridge, +1);
637 if (swap) {
638 ast_channel_ref(swap);
639 }
640 found->type = LOCAL_CALL_ACTION_BRIDGE;
641 found->action.bridge.join = bridge;
642 found->action.bridge.swap = swap;
643 found->action.bridge.features = features;
644 res = 0;
645 } else {
646 ast_bridge_features_destroy(features);
647 }
648 ao2_unlock(found);
649 ao2_ref(found, -1);
650 }
651
652 return res;
653 }
654
655 int ast_local_setup_masquerade(struct ast_channel *ast, struct ast_channel *masq)
656 {
657 struct local_pvt *p;
658 struct local_pvt *found;
659 int res = -1;
660
661 /* Sanity checks. */
662 if (!ast || !masq) {
663 return -1;
664 }
665
666 ast_channel_lock(ast);
667 p = ast_channel_tech_pvt(ast);
668 ast_channel_unlock(ast);
669
670 found = p ? ao2_find(locals, p, 0) : NULL;
671 if (found) {
672 ao2_lock(found);
673 if (found->type == LOCAL_CALL_ACTION_DIALPLAN
674 && found->base.owner
675 && found->base.chan
676 && !ast_test_flag(&found->base, AST_UNREAL_CARETAKER_THREAD)) {
677 ast_channel_ref(masq);
678 found->type = LOCAL_CALL_ACTION_MASQUERADE;
679 found->action.masq = masq;
680 res = 0;
681 }
682 ao2_unlock(found);
683 ao2_ref(found, -1);
684 }
685
686 return res;
687 }
688
689 /*! \brief Initiate new call, part of PBX interface
690 * dest is the dial string */
691 static int local_call(struct ast_channel *ast, const char *dest, int timeout)
692 {
693 struct local_pvt *p = ast_channel_tech_pvt(ast);
694 int pvt_locked = 0;
695
696 struct ast_channel *owner = NULL;
697 struct ast_channel *chan = NULL;
698 int res;
699 char *reduced_dest = ast_strdupa(dest);
700 char *slash;
701 const char *chan_cid;
702
703 if (!p) {
704 return -1;
705 }
706
707 /* since we are letting go of channel locks that were locked coming into
708 * this function, then we need to give the tech pvt a ref */
709 ao2_ref(p, 1);
710 ast_channel_unlock(ast);
711
712 ast_unreal_lock_all(&p->base, &chan, &owner);
713 pvt_locked = 1;
714
715 if (owner != ast) {
716 res = -1;
717 goto return_cleanup;
718 }
719
720 if (!owner || !chan) {
721 res = -1;
722 goto return_cleanup;
723 }
724
725 ast_unreal_call_setup(owner, chan);
726
727 /*
728 * If the local channel has /n on the end of it, we need to lop
729 * that off for our argument to setting up the CC_INTERFACES
730 * variable.
731 */
732 if ((slash = strrchr(reduced_dest, '/'))) {
733 *slash = '\0';
734 }
735 if (ast_cc_is_enabled()) {
736 ast_set_cc_interfaces_chanvar(chan, reduced_dest);
737 }
738
739 ao2_unlock(p);
740 pvt_locked = 0;
741
742 ast_channel_unlock(owner);
743
744 chan_cid = S_COR(ast_channel_caller(chan)->id.number.valid,
745 ast_channel_caller(chan)->id.number.str, NULL);
746 if (chan_cid) {
747 chan_cid = ast_strdupa(chan_cid);
748 }
749 ast_channel_unlock(chan);
750
751 res = -1;
752 switch (p->type) {
753 case LOCAL_CALL_ACTION_DIALPLAN:
754 if (!ast_exists_extension(NULL, p->context, p->exten, 1, chan_cid)) {
755 ast_log(LOG_NOTICE, "No such extension/context %s@%s while calling Local channel\n",
756 p->exten, p->context);
757 } else {
758 publish_local_bridge_message(p);
759
760 /* Start switch on sub channel */
761 res = ast_pbx_start(chan);
762 }
763 break;
764 case LOCAL_CALL_ACTION_BRIDGE:
765 publish_local_bridge_message(p);
766 ast_answer(chan);
767 res = ast_bridge_impart(p->action.bridge.join, chan, p->action.bridge.swap,
768 p->action.bridge.features, AST_BRIDGE_IMPART_CHAN_INDEPENDENT);
769 ao2_ref(p->action.bridge.join, -1);
770 p->action.bridge.join = NULL;
771 ao2_cleanup(p->action.bridge.swap);
772 p->action.bridge.swap = NULL;
773 p->action.bridge.features = NULL;
774 break;
775 case LOCAL_CALL_ACTION_MASQUERADE:
776 publish_local_bridge_message(p);
777 ast_answer(chan);
778 res = ast_channel_move(p->action.masq, chan);
779 if (!res) {
780 /* Chan is now an orphaned zombie. Destroy it. */
781 ast_hangup(chan);
782 }
783 p->action.masq = ast_channel_unref(p->action.masq);
784 break;
785 }
786 if (!res) {
787 ao2_lock(p);
788 ast_set_flag(&p->base, AST_UNREAL_CARETAKER_THREAD);
789 ao2_unlock(p);
790 }
791
792 /* we already unlocked them, clear them here so the cleanup label won't touch them. */
793 owner = ast_channel_unref(owner);
794 chan = ast_channel_unref(chan);
795
796 return_cleanup:
797 if (p) {
798 if (pvt_locked) {
799 ao2_unlock(p);
800 }
801 ao2_ref(p, -1);
802 }
803 if (chan) {
804 ast_channel_unlock(chan);
805 ast_channel_unref(chan);
806 }
807
808 /*
809 * owner is supposed to be == to ast, if it is, don't unlock it
810 * because ast must exit locked
811 */
812 if (owner) {
813 if (owner != ast) {
814 ast_channel_unlock(owner);
815 ast_channel_lock(ast);
816 }
817 ast_channel_unref(owner);
818 } else {
819 /* we have to exit with ast locked */
820 ast_channel_lock(ast);
821 }
822
823 return res;
824 }
825
826 /*! \brief Hangup a call through the local proxy channel */
827 static int local_hangup(struct ast_channel *ast)
828 {
829 struct local_pvt *p = ast_channel_tech_pvt(ast);
830 int res;
831
832 if (!p) {
833 return -1;
834 }
835
836 /* give the pvt a ref to fulfill calling requirements. */
837 ao2_ref(p, +1);
838 res = ast_unreal_hangup(&p->base, ast);
839 if (!res) {
840 int unlink;
841
842 ao2_lock(p);
843 unlink = !p->base.owner && !p->base.chan;
844 ao2_unlock(p);
845 if (unlink) {
846 ao2_unlink(locals, p);
847 }
848 }
849 ao2_ref(p, -1);
850
851 return res;
852 }
853
854 /*!
855 * \internal
856 * \brief struct local_pvt destructor.
857 *
858 * \param vdoomed Object to destroy.
859 */
860 static void local_pvt_destructor(void *vdoomed)
861 {
862 struct local_pvt *doomed = vdoomed;
863
864 switch (doomed->type) {
865 case LOCAL_CALL_ACTION_DIALPLAN:
866 break;
867 case LOCAL_CALL_ACTION_BRIDGE:
868 ao2_cleanup(doomed->action.bridge.join);
869 ao2_cleanup(doomed->action.bridge.swap);
870 ast_bridge_features_destroy(doomed->action.bridge.features);
871 break;
872 case LOCAL_CALL_ACTION_MASQUERADE:
873 ao2_cleanup(doomed->action.masq);
874 break;
875 }
876 ast_unreal_destructor(&doomed->base);
877 }
878
879 /*! \brief Create a call structure */
880 static struct local_pvt *local_alloc(const char *data, struct ast_stream_topology *topology)
881 {
882 struct local_pvt *pvt;
883 char *parse;
884 char *context;
885 char *opts;
886
887 pvt = (struct local_pvt *) ast_unreal_alloc_stream_topology(sizeof(*pvt), local_pvt_destructor, topology);
888 if (!pvt) {
889 return NULL;
890 }
891 pvt->base.callbacks = &local_unreal_callbacks;
892
893 parse = ast_strdupa(data);
894
895 /*
896 * Local channels intercept MOH by default.
897 *
898 * This is a silly default because it represents state held by
899 * the local channels. Unless local channel optimization is
900 * disabled, the state will disappear when the local channels
901 * optimize out.
902 */
903 ast_set_flag(&pvt->base, AST_UNREAL_MOH_INTERCEPT);
904
905 /* Look for options.
906 * Slashes can appear in channel names, so options are after the last match. */
907 if ((opts = strrchr(parse, '/'))) {
908 *opts++ = '\0';
909 if (strchr(opts, 'n')) {
910 ast_set_flag(&pvt->base, AST_UNREAL_NO_OPTIMIZATION);
911 }
912 if (strchr(opts, 'j')) {
913 if (ast_test_flag(&pvt->base, AST_UNREAL_NO_OPTIMIZATION)) {
914 ast_set_flag(&pvt->base.jb_conf, AST_JB_ENABLED);
915 } else {
916 ast_log(LOG_ERROR, "You must use the 'n' option with the 'j' option to enable the jitter buffer\n");
917 }
918 }
919 if (strchr(opts, 'm')) {
920 ast_clear_flag(&pvt->base, AST_UNREAL_MOH_INTERCEPT);
921 }
922 }
923
924 /* Look for a context */
925 if ((context = strchr(parse, '@'))) {
926 *context++ = '\0';
927 }
928
929 ast_copy_string(pvt->context, S_OR(context, "default"), sizeof(pvt->context));
930 ast_copy_string(pvt->exten, parse, sizeof(pvt->exten));
931 snprintf(pvt->base.name, sizeof(pvt->base.name), "%s@%s", pvt->exten, pvt->context);
932
933 return pvt; /* this is returned with a ref */
934 }
935
936 /*! \brief Part of PBX interface */
937 static struct ast_channel *local_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
938 {
939 struct ast_stream_topology *topology;
940 struct ast_channel *chan;
941
942 topology = ast_stream_topology_create_from_format_cap(cap);
943 if (!topology) {
944 return NULL;
945 }
946
947 chan = local_request_with_stream_topology(type, topology, assignedids, requestor, data, cause);
948
949 ast_stream_topology_free(topology);
950
951 return chan;
952 }
953
954 /*! \brief Part of PBX interface */
955 static struct ast_channel *local_request_with_stream_topology(const char *type, struct ast_stream_topology *topology, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause)
956 {
957 struct ast_stream_topology *audio_filtered_topology;
958 int i;
959 struct local_pvt *p;
960 struct ast_channel *chan;
961 ast_callid callid;
962
963 /* Create a copy of the requested topology as we don't have ownership over
964 * the one that is passed in.
965 */
966 audio_filtered_topology = ast_stream_topology_clone(topology);
967 if (!audio_filtered_topology) {
968 return NULL;
969 }
970
971 /* Some users of Local channels request every known format in the
972 * universe. The core itself automatically pruned this list down to a single
973 * "best" format for audio in non-multistream. We replicate the logic here to
974 * do the same thing.
975 */
976 for (i = 0; i < ast_stream_topology_get_count(audio_filtered_topology); ++i) {
977 struct ast_stream *stream;
978 int res;
979 struct ast_format *tmp_fmt = NULL;
980 struct ast_format *best_audio_fmt = NULL;
981 struct ast_format_cap *caps;
982
983 stream = ast_stream_topology_get_stream(audio_filtered_topology, i);
984
985 if (ast_stream_get_type(stream) != AST_MEDIA_TYPE_AUDIO ||
986 ast_stream_get_state(stream) == AST_STREAM_STATE_REMOVED) {
987 continue;
988 }
989
990 /* Respect the immutable state of formats on the stream and create a new
991 * format capabilities to replace the existing one.
992 */
993 caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
994 if (!caps) {
995 ao2_ref(audio_filtered_topology, -1);
996 return NULL;
997 }
998
999 /* The ast_translator_best_choice function treats both caps as const
1000 * but does not declare it in the API.
1001 */
1002 res = ast_translator_best_choice((struct ast_format_cap *)ast_stream_get_formats(stream), local_tech.capabilities,
1003 &tmp_fmt, &best_audio_fmt);
1004 if (res < 0) {
1005 struct ast_str *tech_codecs = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
1006 struct ast_str *request_codecs = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
1007
1008 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %s) to %s\n", type,
1009 ast_format_cap_get_names(local_tech.capabilities, &tech_codecs),
1010 ast_format_cap_get_names(ast_stream_get_formats(stream), &request_codecs));
1011
1012 /* If there are no formats then we abort */
1013 ao2_ref(caps, -1);
1014 ao2_ref(audio_filtered_topology, -1);
1015 return NULL;
1016 }
1017
1018 ast_format_cap_append(caps, best_audio_fmt, 0);
1019 ast_stream_set_formats(stream, caps);
1020
1021 ao2_ref(caps, -1);
1022 ao2_ref(tmp_fmt, -1);
1023 ao2_ref(best_audio_fmt, -1);
1024 }
1025
1026 /* Allocate a new private structure and then Asterisk channels */
1027 p = local_alloc(data, audio_filtered_topology);
1028 ao2_ref(audio_filtered_topology, -1);
1029 if (!p) {
1030 return NULL;
1031 }
1032 callid = ast_read_threadstorage_callid();
1033 chan = ast_unreal_new_channels(&p->base, &local_tech, AST_STATE_DOWN, AST_STATE_RING,
1034 p->exten, p->context, assignedids, requestor, callid);
1035 if (chan) {
1036 ao2_link(locals, p);
1037 }
1038 ao2_ref(p, -1); /* kill the ref from the alloc */
1039
1040 return chan;
1041 }
1042
1043
1044 /*! \brief CLI command "local show channels" */
1045 static char *locals_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1046 {
1047 struct local_pvt *p;
1048 struct ao2_iterator it;
1049
1050 switch (cmd) {
1051 case CLI_INIT:
1052 e->command = "local show channels";
1053 e->usage =
1054 "Usage: local show channels\n"
1055 " Provides summary information on active local proxy channels.\n";
1056 return NULL;
1057 case CLI_GENERATE:
1058 return NULL;
1059 }
1060
1061 if (a->argc != 3) {
1062 return CLI_SHOWUSAGE;
1063 }
1064
1065 if (ao2_container_count(locals) == 0) {
1066 ast_cli(a->fd, "No local channels in use\n");
1067 return RESULT_SUCCESS;
1068 }
1069
1070 it = ao2_iterator_init(locals, 0);
1071 while ((p = ao2_iterator_next(&it))) {
1072 ao2_lock(p);
1073 ast_cli(a->fd, "%s -- %s\n",
1074 p->base.owner ? ast_channel_name(p->base.owner) : "<unowned>",
1075 p->base.name);
1076 ao2_unlock(p);
1077 ao2_ref(p, -1);
1078 }
1079 ao2_iterator_destroy(&it);
1080
1081 return CLI_SUCCESS;
1082 }
1083
1084 static struct ast_cli_entry cli_local[] = {
1085 AST_CLI_DEFINE(locals_show, "List status of local channels"),
1086 };
1087
1088 static int manager_optimize_away(struct mansession *s, const struct message *m)
1089 {
1090 const char *channel;
1091 struct local_pvt *p;
1092 struct local_pvt *found;
1093 struct ast_channel *chan;
1094
1095 channel = astman_get_header(m, "Channel");
1096 if (ast_strlen_zero(channel)) {
1097 astman_send_error(s, m, "'Channel' not specified.");
1098 return 0;
1099 }
1100
1101 chan = ast_channel_get_by_name(channel);
1102 if (!chan) {
1103 astman_send_error(s, m, "Channel does not exist.");
1104 return 0;
1105 }
1106
1107 p = ast_channel_tech_pvt(chan);
1108 ast_channel_unref(chan);
1109
1110 found = p ? ao2_find(locals, p, 0) : NULL;
1111 if (found) {
1112 ao2_lock(found);
1113 ast_clear_flag(&found->base, AST_UNREAL_NO_OPTIMIZATION);
1114 ao2_unlock(found);
1115 ao2_ref(found, -1);
1116 astman_send_ack(s, m, "Queued channel to be optimized away");
1117 } else {
1118 astman_send_error(s, m, "Unable to find channel");
1119 }
1120
1121 return 0;
1122 }
1123
1124
1125 static int locals_cmp_cb(void *obj, void *arg, int flags)
1126 {
1127 return (obj == arg) ? CMP_MATCH : 0;
1128 }
1129
1130 /*!
1131 * \internal
1132 * \brief Shutdown the local proxy channel.
1133 * \since 12.0.0
1134 */
1135 static void local_shutdown(void)
1136 {
1137 /* First, take us out of the channel loop */
1138 ast_cli_unregister_multiple(cli_local, ARRAY_LEN(cli_local));
1139 ast_manager_unregister("LocalOptimizeAway");
1140 ast_channel_unregister(&local_tech);
1141
1142 ao2_ref(locals, -1);
1143 locals = NULL;
1144
1145 ao2_cleanup(local_tech.capabilities);
1146 local_tech.capabilities = NULL;
1147
1148 STASIS_MESSAGE_TYPE_CLEANUP(ast_local_optimization_begin_type);
1149 STASIS_MESSAGE_TYPE_CLEANUP(ast_local_optimization_end_type);
1150 STASIS_MESSAGE_TYPE_CLEANUP(ast_local_bridge_type);
1151 }
1152
1153 int ast_local_init(void)
1154 {
1155 if (STASIS_MESSAGE_TYPE_INIT(ast_local_optimization_begin_type)) {
1156 return -1;
1157 }
1158
1159 if (STASIS_MESSAGE_TYPE_INIT(ast_local_optimization_end_type)) {
1160 return -1;
1161 }
1162
1163 if (STASIS_MESSAGE_TYPE_INIT(ast_local_bridge_type)) {
1164 return -1;
1165 }
1166
1167 if (!(local_tech.capabilities = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1168 return -1;
1169 }
1170 ast_format_cap_append_by_type(local_tech.capabilities, AST_MEDIA_TYPE_UNKNOWN);
1171
1172 locals = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, locals_cmp_cb);
1173 if (!locals) {
1174 return -1;
1175 }
1176
1177 /* Make sure we can register our channel type */
1178 if (ast_channel_register(&local_tech)) {
1179 ast_log(LOG_ERROR, "Unable to register channel class 'Local'\n");
1180
1181 return -1;
1182 }
1183 ast_cli_register_multiple(cli_local, ARRAY_LEN(cli_local));
1184 ast_manager_register_xml_core("LocalOptimizeAway", EVENT_FLAG_SYSTEM|EVENT_FLAG_CALL, manager_optimize_away);
1185
1186 ast_register_cleanup(local_shutdown);
1187 return 0;
1188 }
1189
1190 int local_setoption(struct ast_channel *ast, int option, void *data, int datalen)
1191 {
1192 switch (option) {
1193 case AST_OPTION_SECURE_SIGNALING:
1194 case AST_OPTION_SECURE_MEDIA:
1195 return 0; /* local calls (like forwardings) are secure always */
1196 default:
1197 return ast_unreal_setoption(ast, option, data, datalen);
1198 }
1199 }