ast_json_pack(): Use safer json ref mechanism.
[asterisk/asterisk.git] / main / core_unreal.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013 Digium, Inc.
5  *
6  * Richard Mudgett <rmudgett@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 /*!
20  * \file
21  * \brief Unreal channel derivatives framework for channel drivers like local channels.
22  *
23  * \author Richard Mudgett <rmudgett@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 #include "asterisk/causes.h"
36 #include "asterisk/channel.h"
37 #include "asterisk/stasis_channels.h"
38 #include "asterisk/pbx.h"
39 #include "asterisk/musiconhold.h"
40 #include "asterisk/astobj2.h"
41 #include "asterisk/bridge.h"
42 #include "asterisk/core_unreal.h"
43
44 static unsigned int name_sequence = 0;
45
46 void ast_unreal_lock_all(struct ast_unreal_pvt *p, struct ast_channel **outchan, struct ast_channel **outowner)
47 {
48         struct ast_channel *chan = NULL;
49         struct ast_channel *owner = NULL;
50
51         ao2_lock(p);
52         for (;;) {
53                 if (p->chan) {
54                         chan = p->chan;
55                         ast_channel_ref(chan);
56                 }
57                 if (p->owner) {
58                         owner = p->owner;
59                         ast_channel_ref(owner);
60                 }
61                 ao2_unlock(p);
62
63                 /* if we don't have both channels, then this is very easy */
64                 if (!owner || !chan) {
65                         if (owner) {
66                                 ast_channel_lock(owner);
67                         } else if(chan) {
68                                 ast_channel_lock(chan);
69                         }
70                 } else {
71                         /* lock both channels first, then get the pvt lock */
72                         ast_channel_lock_both(chan, owner);
73                 }
74                 ao2_lock(p);
75
76                 /* Now that we have all the locks, validate that nothing changed */
77                 if (p->owner != owner || p->chan != chan) {
78                         if (owner) {
79                                 ast_channel_unlock(owner);
80                                 owner = ast_channel_unref(owner);
81                         }
82                         if (chan) {
83                                 ast_channel_unlock(chan);
84                                 chan = ast_channel_unref(chan);
85                         }
86                         continue;
87                 }
88
89                 break;
90         }
91         *outowner = p->owner;
92         *outchan = p->chan;
93 }
94
95 /* Called with ast locked */
96 int ast_unreal_setoption(struct ast_channel *ast, int option, void *data, int datalen)
97 {
98         int res = 0;
99         struct ast_unreal_pvt *p;
100         struct ast_channel *otherchan = NULL;
101         ast_chan_write_info_t *write_info;
102         char *info_data;
103
104         if (option != AST_OPTION_CHANNEL_WRITE) {
105                 return -1;
106         }
107
108         write_info = data;
109
110         if (write_info->version != AST_CHAN_WRITE_INFO_T_VERSION) {
111                 ast_log(LOG_ERROR, "The chan_write_info_t type has changed, and this channel hasn't been updated!\n");
112                 return -1;
113         }
114
115         info_data = write_info->data;
116         if (!strcmp(write_info->function, "CHANNEL")) {
117                 if (!strncasecmp(info_data, "hangup_handler_", 15)) {
118                         /* Block CHANNEL(hangup_handler_xxx) writes to the other unreal channel. */
119                         return 0;
120                 }
121
122                 /* Crossover the accountcode and peeraccount to cross the unreal bridge. */
123                 if (!strcasecmp(info_data, "accountcode")) {
124                         info_data = "peeraccount";
125                 } else if (!strcasecmp(info_data, "peeraccount")) {
126                         info_data = "accountcode";
127                 }
128         }
129
130         /* get the tech pvt */
131         if (!(p = ast_channel_tech_pvt(ast))) {
132                 return -1;
133         }
134         ao2_ref(p, 1);
135         ast_channel_unlock(ast); /* Held when called, unlock before locking another channel */
136
137         /* get the channel we are supposed to write to */
138         ao2_lock(p);
139         otherchan = (write_info->chan == p->owner) ? p->chan : p->owner;
140         if (!otherchan || otherchan == write_info->chan) {
141                 res = -1;
142                 otherchan = NULL;
143                 ao2_unlock(p);
144                 goto setoption_cleanup;
145         }
146         ast_channel_ref(otherchan);
147
148         /* clear the pvt lock before grabbing the channel */
149         ao2_unlock(p);
150
151         ast_channel_lock(otherchan);
152         res = write_info->write_fn(otherchan, write_info->function, info_data, write_info->value);
153         ast_channel_unlock(otherchan);
154
155 setoption_cleanup:
156         ao2_ref(p, -1);
157         if (otherchan) {
158                 ast_channel_unref(otherchan);
159         }
160         ast_channel_lock(ast); /* Lock back before we leave */
161         return res;
162 }
163
164 /* Called with ast locked */
165 int ast_unreal_queryoption(struct ast_channel *ast, int option, void *data, int *datalen)
166 {
167         struct ast_unreal_pvt *p;
168         struct ast_channel *peer;
169         struct ast_channel *other;
170         int res = 0;
171
172         if (option != AST_OPTION_T38_STATE) {
173                 /* AST_OPTION_T38_STATE is the only supported option at this time */
174                 return -1;
175         }
176
177         /* for some reason the channel is not locked in channel.c when this function is called */
178         if (!(p = ast_channel_tech_pvt(ast))) {
179                 return -1;
180         }
181
182         ao2_lock(p);
183         other = AST_UNREAL_IS_OUTBOUND(ast, p) ? p->owner : p->chan;
184         if (!other) {
185                 ao2_unlock(p);
186                 return -1;
187         }
188         ast_channel_ref(other);
189         ao2_unlock(p);
190         ast_channel_unlock(ast); /* Held when called, unlock before locking another channel */
191
192         peer = ast_channel_bridge_peer(other);
193         if (peer) {
194                 res = ast_channel_queryoption(peer, option, data, datalen, 0);
195                 ast_channel_unref(peer);
196         }
197         ast_channel_unref(other);
198         ast_channel_lock(ast); /* Lock back before we leave */
199
200         return res;
201 }
202
203 /*!
204  * \brief queue a frame onto either the p->owner or p->chan
205  *
206  * \note the ast_unreal_pvt MUST have it's ref count bumped before entering this function and
207  * decremented after this function is called.  This is a side effect of the deadlock
208  * avoidance that is necessary to lock 2 channels and a tech_pvt.  Without a ref counted
209  * ast_unreal_pvt, it is impossible to guarantee it will not be destroyed by another thread
210  * during deadlock avoidance.
211  */
212 static int unreal_queue_frame(struct ast_unreal_pvt *p, int isoutbound, struct ast_frame *f,
213         struct ast_channel *us, int us_locked)
214 {
215         struct ast_channel *other;
216
217         /* Recalculate outbound channel */
218         other = isoutbound ? p->owner : p->chan;
219         if (!other) {
220                 return 0;
221         }
222
223         /* do not queue media frames if a generator is on both unreal channels */
224         if (us
225                 && (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO)
226                 && ast_channel_generator(us)
227                 && ast_channel_generator(other)) {
228                 return 0;
229         }
230
231         /* grab a ref on the channel before unlocking the pvt,
232          * other can not go away from us now regardless of locking */
233         ast_channel_ref(other);
234         if (us && us_locked) {
235                 ast_channel_unlock(us);
236         }
237         ao2_unlock(p);
238
239         if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_RINGING) {
240                 ast_setstate(other, AST_STATE_RINGING);
241         }
242         ast_queue_frame(other, f);
243
244         other = ast_channel_unref(other);
245         if (us && us_locked) {
246                 ast_channel_lock(us);
247         }
248         ao2_lock(p);
249
250         return 0;
251 }
252
253 int ast_unreal_answer(struct ast_channel *ast)
254 {
255         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
256         int isoutbound;
257         int res = -1;
258
259         if (!p) {
260                 return -1;
261         }
262
263         ao2_ref(p, 1);
264         ao2_lock(p);
265         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
266         if (isoutbound) {
267                 /* Pass along answer since somebody answered us */
268                 struct ast_frame answer = { AST_FRAME_CONTROL, { AST_CONTROL_ANSWER } };
269
270                 res = unreal_queue_frame(p, isoutbound, &answer, ast, 1);
271         } else {
272                 ast_log(LOG_WARNING, "Huh?  %s is being asked to answer?\n",
273                         ast_channel_name(ast));
274         }
275         ao2_unlock(p);
276         ao2_ref(p, -1);
277         return res;
278 }
279
280 /*!
281  * \internal
282  * \brief Check and optimize out the unreal channels between bridges.
283  * \since 12.0.0
284  *
285  * \param ast Channel writing a frame into the unreal channels.
286  * \param p Unreal channel private.
287  *
288  * \note It is assumed that ast is locked.
289  * \note It is assumed that p is locked.
290  *
291  * \retval 0 if unreal channels were not optimized out.
292  * \retval non-zero if unreal channels were optimized out.
293  */
294 static int got_optimized_out(struct ast_channel *ast, struct ast_unreal_pvt *p)
295 {
296         int res = 0;
297
298         /* Do a few conditional checks early on just to see if this optimization is possible */
299         if (ast_test_flag(p, AST_UNREAL_NO_OPTIMIZATION) || !p->chan || !p->owner) {
300                 return res;
301         }
302
303         if (ast == p->owner) {
304                 res = ast_bridge_unreal_optimize_out(p->owner, p->chan, p);
305         } else if (ast == p->chan) {
306                 res = ast_bridge_unreal_optimize_out(p->chan, p->owner, p);
307         }
308
309         return res;
310 }
311
312 struct ast_frame  *ast_unreal_read(struct ast_channel *ast)
313 {
314         return &ast_null_frame;
315 }
316
317 int ast_unreal_write(struct ast_channel *ast, struct ast_frame *f)
318 {
319         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
320         int res = -1;
321
322         if (!p) {
323                 return -1;
324         }
325
326         /* If we are told to write a frame with a type that has no corresponding
327          * stream on the channel then drop it.
328          */
329         if (f->frametype == AST_FRAME_VOICE) {
330                 if (!ast_channel_get_default_stream(ast, AST_MEDIA_TYPE_AUDIO)) {
331                         return 0;
332                 }
333         } else if (f->frametype == AST_FRAME_VIDEO ||
334                 (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_VIDUPDATE)) {
335                 if (!ast_channel_get_default_stream(ast, AST_MEDIA_TYPE_VIDEO)) {
336                         return 0;
337                 }
338         }
339
340         /* Just queue for delivery to the other side */
341         ao2_ref(p, 1);
342         ao2_lock(p);
343         switch (f->frametype) {
344         case AST_FRAME_VOICE:
345         case AST_FRAME_VIDEO:
346                 if (got_optimized_out(ast, p)) {
347                         break;
348                 }
349                 /* fall through */
350         default:
351                 res = unreal_queue_frame(p, AST_UNREAL_IS_OUTBOUND(ast, p), f, ast, 1);
352                 break;
353         }
354         ao2_unlock(p);
355         ao2_ref(p, -1);
356
357         return res;
358 }
359
360 int ast_unreal_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
361 {
362         struct ast_unreal_pvt *p = ast_channel_tech_pvt(newchan);
363         struct ast_bridge *bridge_owner;
364         struct ast_bridge *bridge_chan;
365
366         if (!p) {
367                 return -1;
368         }
369
370         ao2_lock(p);
371
372         if ((p->owner != oldchan) && (p->chan != oldchan)) {
373                 ast_log(LOG_WARNING, "Old channel %p wasn't %p or %p\n", oldchan, p->owner, p->chan);
374                 ao2_unlock(p);
375                 return -1;
376         }
377         if (p->owner == oldchan) {
378                 p->owner = newchan;
379         } else {
380                 p->chan = newchan;
381         }
382
383         if (ast_check_hangup(newchan) || !p->owner || !p->chan) {
384                 ao2_unlock(p);
385                 return 0;
386         }
387
388         /* Do not let a masquerade cause an unreal channel to be bridged to itself! */
389         bridge_owner = ast_channel_internal_bridge(p->owner);
390         bridge_chan = ast_channel_internal_bridge(p->chan);
391         if (bridge_owner && bridge_owner == bridge_chan) {
392                 ast_log(LOG_WARNING, "You can not bridge an unreal channel (%s) to itself!\n",
393                         ast_channel_name(newchan));
394                 ao2_unlock(p);
395                 ast_queue_hangup(newchan);
396                 return -1;
397         }
398
399         ao2_unlock(p);
400         return 0;
401 }
402
403 /*!
404  * \internal
405  * \brief Queue up a frame representing the indication as a control frame.
406  * \since 12.0.0
407  *
408  * \param p Unreal private structure.
409  * \param ast Channel indicating the condition.
410  * \param condition What is being indicated.
411  * \param data Extra data.
412  * \param datalen Length of extra data.
413  *
414  * \retval 0 on success.
415  * \retval AST_T38_REQUEST_PARMS if successful and condition is AST_CONTROL_T38_PARAMETERS.
416  * \retval -1 on error.
417  */
418 static int unreal_queue_indicate(struct ast_unreal_pvt *p, struct ast_channel *ast, int condition, const void *data, size_t datalen)
419 {
420         int res = 0;
421         int isoutbound;
422
423         ao2_lock(p);
424         /*
425          * Block -1 stop tones events if we are to be optimized out.  We
426          * don't need a flurry of these events on an unreal channel chain
427          * when initially connected to slow the optimization process.
428          */
429         if (0 <= condition || ast_test_flag(p, AST_UNREAL_NO_OPTIMIZATION)) {
430                 struct ast_frame f = {
431                         .frametype = AST_FRAME_CONTROL,
432                         .subclass.integer = condition,
433                         .data.ptr = (void *) data,
434                         .datalen = datalen,
435                 };
436
437                 isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
438                 res = unreal_queue_frame(p, isoutbound, &f, ast, 1);
439                 if (!res
440                         && condition == AST_CONTROL_T38_PARAMETERS
441                         && datalen == sizeof(struct ast_control_t38_parameters)) {
442                         const struct ast_control_t38_parameters *parameters = data;
443
444                         if (parameters->request_response == AST_T38_REQUEST_PARMS) {
445                                 res = AST_T38_REQUEST_PARMS;
446                         }
447                 }
448         } else {
449                 ast_debug(4, "Blocked indication %d\n", condition);
450         }
451         ao2_unlock(p);
452
453         return res;
454 }
455
456 /*!
457  * \internal
458  * \brief Handle COLP and redirecting conditions.
459  * \since 12.0.0
460  *
461  * \param p Unreal private structure.
462  * \param ast Channel indicating the condition.
463  * \param condition What is being indicated.
464  *
465  * \retval 0 on success.
466  * \retval -1 on error.
467  */
468 static int unreal_colp_redirect_indicate(struct ast_unreal_pvt *p, struct ast_channel *ast, int condition)
469 {
470         struct ast_channel *my_chan;
471         struct ast_channel *my_owner;
472         struct ast_channel *this_channel;
473         struct ast_channel *the_other_channel;
474         int isoutbound;
475         int res = 0;
476         unsigned char frame_data[1024];
477         struct ast_frame f = {
478                 .frametype = AST_FRAME_CONTROL,
479                 .subclass.integer = condition,
480                 .data.ptr = frame_data,
481         };
482
483         /*
484          * A connected line update frame may only contain a partial
485          * amount of data, such as just a source, or just a ton, and not
486          * the full amount of information.  However, the collected
487          * information is all stored in the outgoing channel's
488          * connectedline structure, so when receiving a connected line
489          * update on an outgoing unreal channel, we need to transmit the
490          * collected connected line information instead of whatever
491          * happens to be in this control frame.  The same applies for
492          * redirecting information, which is why it is handled here as
493          * well.
494          */
495         ast_channel_unlock(ast);
496         ast_unreal_lock_all(p, &my_chan, &my_owner);
497         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
498         if (isoutbound) {
499                 this_channel = p->chan;
500                 the_other_channel = p->owner;
501         } else {
502                 this_channel = p->owner;
503                 the_other_channel = p->chan;
504         }
505         if (the_other_channel) {
506                 if (condition == AST_CONTROL_CONNECTED_LINE) {
507                         ast_connected_line_copy_to_caller(ast_channel_caller(the_other_channel),
508                                 ast_channel_connected(this_channel));
509                         f.datalen = ast_connected_line_build_data(frame_data, sizeof(frame_data),
510                                 ast_channel_connected(this_channel), NULL);
511                 } else {
512                         f.datalen = ast_redirecting_build_data(frame_data, sizeof(frame_data),
513                                 ast_channel_redirecting(this_channel), NULL);
514                 }
515         }
516         if (my_chan) {
517                 ast_channel_unlock(my_chan);
518                 ast_channel_unref(my_chan);
519         }
520         if (my_owner) {
521                 ast_channel_unlock(my_owner);
522                 ast_channel_unref(my_owner);
523         }
524         if (the_other_channel) {
525                 res = unreal_queue_frame(p, isoutbound, &f, ast, 0);
526         }
527         ao2_unlock(p);
528         ast_channel_lock(ast);
529
530         return res;
531 }
532
533 int ast_unreal_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
534 {
535         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
536         int res = 0;
537
538         if (!p) {
539                 return -1;
540         }
541
542         ao2_ref(p, 1); /* ref for unreal_queue_frame */
543
544         switch (condition) {
545         case AST_CONTROL_MASQUERADE_NOTIFY:
546                 /*
547                  * Always block this because this is the channel being
548                  * masqueraded; not anything down the chain.
549                  */
550                 break;
551         case AST_CONTROL_CONNECTED_LINE:
552         case AST_CONTROL_REDIRECTING:
553                 res = unreal_colp_redirect_indicate(p, ast, condition);
554                 break;
555         case AST_CONTROL_HOLD:
556                 if (ast_test_flag(p, AST_UNREAL_MOH_INTERCEPT)) {
557                         ast_moh_start(ast, data, NULL);
558                         break;
559                 }
560                 res = unreal_queue_indicate(p, ast, condition, data, datalen);
561                 break;
562         case AST_CONTROL_UNHOLD:
563                 if (ast_test_flag(p, AST_UNREAL_MOH_INTERCEPT)) {
564                         ast_moh_stop(ast);
565                         break;
566                 }
567                 res = unreal_queue_indicate(p, ast, condition, data, datalen);
568                 break;
569         case AST_CONTROL_RINGING:
570                 /* Don't queue ringing frames if the channel is not in a "ring" state. Otherwise,
571                  * the real channel on the other end will likely start a playtones generator. It is
572                  * possible that this playtones generator will never be stopped under certain
573                  * circumstances.
574                  */
575                 if (ast_channel_state(ast) == AST_STATE_RING) {
576                         res = unreal_queue_indicate(p, ast, condition, data, datalen);
577                 } else {
578                         res = -1;
579                 }
580                 break;
581         case AST_CONTROL_PVT_CAUSE_CODE:
582                 /* Return -1 so that asterisk core will correctly set up hangupcauses. */
583                 unreal_queue_indicate(p, ast, condition, data, datalen);
584                 res = -1;
585                 break;
586         default:
587                 res = unreal_queue_indicate(p, ast, condition, data, datalen);
588                 break;
589         }
590
591         ao2_ref(p, -1);
592         return res;
593 }
594
595 int ast_unreal_digit_begin(struct ast_channel *ast, char digit)
596 {
597         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
598         int res = -1;
599         struct ast_frame f = { AST_FRAME_DTMF_BEGIN, };
600         int isoutbound;
601
602         if (!p) {
603                 return -1;
604         }
605
606         ao2_ref(p, 1); /* ref for unreal_queue_frame */
607         ao2_lock(p);
608         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
609         f.subclass.integer = digit;
610         res = unreal_queue_frame(p, isoutbound, &f, ast, 0);
611         ao2_unlock(p);
612         ao2_ref(p, -1);
613
614         return res;
615 }
616
617 int ast_unreal_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
618 {
619         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
620         int res = -1;
621         struct ast_frame f = { AST_FRAME_DTMF_END, };
622         int isoutbound;
623
624         if (!p) {
625                 return -1;
626         }
627
628         ao2_ref(p, 1); /* ref for unreal_queue_frame */
629         ao2_lock(p);
630         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
631         f.subclass.integer = digit;
632         f.len = duration;
633         res = unreal_queue_frame(p, isoutbound, &f, ast, 0);
634         ao2_unlock(p);
635         ao2_ref(p, -1);
636
637         return res;
638 }
639
640 int ast_unreal_sendtext(struct ast_channel *ast, const char *text)
641 {
642         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
643         int res = -1;
644         struct ast_frame f = { AST_FRAME_TEXT, };
645         int isoutbound;
646
647         if (!p) {
648                 return -1;
649         }
650
651         ao2_ref(p, 1); /* ref for unreal_queue_frame */
652         ao2_lock(p);
653         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
654         f.data.ptr = (char *) text;
655         f.datalen = strlen(text) + 1;
656         res = unreal_queue_frame(p, isoutbound, &f, ast, 0);
657         ao2_unlock(p);
658         ao2_ref(p, -1);
659         return res;
660 }
661
662 int ast_unreal_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
663 {
664         struct ast_unreal_pvt *p = ast_channel_tech_pvt(ast);
665         int res = -1;
666         struct ast_frame f = { AST_FRAME_HTML, };
667         int isoutbound;
668
669         if (!p) {
670                 return -1;
671         }
672
673         ao2_ref(p, 1); /* ref for unreal_queue_frame */
674         ao2_lock(p);
675         isoutbound = AST_UNREAL_IS_OUTBOUND(ast, p);
676         f.subclass.integer = subclass;
677         f.data.ptr = (char *)data;
678         f.datalen = datalen;
679         res = unreal_queue_frame(p, isoutbound, &f, ast, 0);
680         ao2_unlock(p);
681         ao2_ref(p, -1);
682
683         return res;
684 }
685
686 void ast_unreal_call_setup(struct ast_channel *semi1, struct ast_channel *semi2)
687 {
688         struct ast_var_t *varptr;
689         struct ast_var_t *clone_var;
690
691         ast_channel_stage_snapshot(semi2);
692
693         /*
694          * Note that cid_num and cid_name aren't passed in the
695          * ast_channel_alloc calls in ast_unreal_new_channels().  It's
696          * done here instead.
697          */
698         ast_party_redirecting_copy(ast_channel_redirecting(semi2), ast_channel_redirecting(semi1));
699
700         ast_party_dialed_copy(ast_channel_dialed(semi2), ast_channel_dialed(semi1));
701
702         /* Crossover the CallerID and conected-line to cross the unreal bridge. */
703         ast_connected_line_copy_to_caller(ast_channel_caller(semi2), ast_channel_connected(semi1));
704         ast_connected_line_copy_from_caller(ast_channel_connected(semi2), ast_channel_caller(semi1));
705
706         ast_channel_language_set(semi2, ast_channel_language(semi1));
707         ast_channel_musicclass_set(semi2, ast_channel_musicclass(semi1));
708         ast_channel_parkinglot_set(semi2, ast_channel_parkinglot(semi1));
709
710         /* Crossover the accountcode and peeraccount to cross the unreal bridge. */
711         ast_channel_accountcode_set(semi2, ast_channel_peeraccount(semi1));
712         ast_channel_peeraccount_set(semi2, ast_channel_accountcode(semi1));
713
714         ast_channel_cc_params_init(semi2, ast_channel_get_cc_config_params(semi1));
715
716         /*
717          * Make sure we inherit the AST_CAUSE_ANSWERED_ELSEWHERE if it's
718          * set on the queue/dial call request in the dialplan.
719          */
720         if (ast_channel_hangupcause(semi1) == AST_CAUSE_ANSWERED_ELSEWHERE) {
721                 ast_channel_hangupcause_set(semi2, AST_CAUSE_ANSWERED_ELSEWHERE);
722         }
723
724         /*
725          * Copy the channel variables from the semi1 channel to the
726          * outgoing channel.
727          *
728          * Note that due to certain assumptions, they MUST be in the
729          * same order.
730          */
731         AST_LIST_TRAVERSE(ast_channel_varshead(semi1), varptr, entries) {
732                 clone_var = ast_var_assign(varptr->name, varptr->value);
733                 if (clone_var) {
734                         AST_LIST_INSERT_TAIL(ast_channel_varshead(semi2), clone_var, entries);
735                         ast_channel_publish_varset(semi2, ast_var_full_name(clone_var),
736                                 ast_var_value(clone_var));
737                 }
738         }
739         ast_channel_datastore_inherit(semi1, semi2);
740
741         ast_channel_stage_snapshot_done(semi2);
742 }
743
744 int ast_unreal_channel_push_to_bridge(struct ast_channel *ast, struct ast_bridge *bridge, unsigned int flags)
745 {
746         struct ast_bridge_features *features;
747         struct ast_channel *chan;
748         struct ast_channel *owner;
749         ast_callid bridge_callid;
750         RAII_VAR(struct ast_unreal_pvt *, p, NULL, ao2_cleanup);
751
752         ast_bridge_lock(bridge);
753         bridge_callid = bridge->callid;
754         ast_bridge_unlock(bridge);
755
756         {
757                 SCOPED_CHANNELLOCK(lock, ast);
758                 p = ast_channel_tech_pvt(ast);
759                 if (!p) {
760                         return -1;
761                 }
762                 ao2_ref(p, +1);
763         }
764
765         {
766                 SCOPED_AO2LOCK(lock, p);
767                 chan = p->chan;
768                 if (!chan) {
769                         return -1;
770                 }
771
772                 owner = p->owner;
773                 if (!owner) {
774                         return -1;
775                 }
776
777                 ast_channel_ref(chan);
778                 ast_channel_ref(owner);
779         }
780
781         if (bridge_callid) {
782                 ast_callid chan_callid;
783                 ast_callid owner_callid;
784
785                 /* chan side call ID setting */
786                 ast_channel_lock(chan);
787
788                 chan_callid = ast_channel_callid(chan);
789                 if (!chan_callid) {
790                         ast_channel_callid_set(chan, bridge_callid);
791                 }
792                 ast_channel_unlock(chan);
793
794                 /* owner side call ID setting */
795                 ast_channel_lock(owner);
796
797                 owner_callid = ast_channel_callid(owner);
798                 if (!owner_callid) {
799                         ast_channel_callid_set(owner, bridge_callid);
800                 }
801
802                 ast_channel_unlock(owner);
803         }
804
805         /* We are done with the owner now that its call ID matches the bridge */
806         ast_channel_unref(owner);
807         owner = NULL;
808
809         features = ast_bridge_features_new();
810         if (!features) {
811                 ast_channel_unref(chan);
812                 return -1;
813         }
814
815         ast_set_flag(&features->feature_flags, flags);
816
817         /* Impart the semi2 channel into the bridge */
818         if (ast_bridge_impart(bridge, chan, NULL, features,
819                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
820                 ast_channel_unref(chan);
821                 return -1;
822         }
823
824         /* The bridge thread now controls the chan ref from the ast_unreal_pvt */
825         ao2_lock(p);
826         ast_set_flag(p, AST_UNREAL_CARETAKER_THREAD);
827         ao2_unlock(p);
828
829         ast_channel_unref(chan);
830
831         return 0;
832 }
833
834 int ast_unreal_hangup(struct ast_unreal_pvt *p, struct ast_channel *ast)
835 {
836         int hangup_chan = 0;
837         int res = 0;
838         int cause;
839         struct ast_channel *owner = NULL;
840         struct ast_channel *chan = NULL;
841
842         /* the pvt isn't going anywhere, it has a ref */
843         ast_channel_unlock(ast);
844
845         /* lock everything */
846         ast_unreal_lock_all(p, &chan, &owner);
847
848         if (ast != chan && ast != owner) {
849                 res = -1;
850                 goto unreal_hangup_cleanup;
851         }
852
853         cause = ast_channel_hangupcause(ast);
854
855         if (ast == p->chan) {
856                 /* Outgoing side is hanging up. */
857                 ast_clear_flag(p, AST_UNREAL_CARETAKER_THREAD);
858                 p->chan = NULL;
859                 if (p->owner) {
860                         const char *status = pbx_builtin_getvar_helper(p->chan, "DIALSTATUS");
861
862                         if (status) {
863                                 ast_channel_hangupcause_set(p->owner, cause);
864                                 pbx_builtin_setvar_helper(p->owner, "CHANLOCALSTATUS", status);
865                         }
866                         ast_queue_hangup_with_cause(p->owner, cause);
867                 }
868         } else {
869                 /* Owner side is hanging up. */
870                 p->owner = NULL;
871                 if (p->chan) {
872                         if (cause == AST_CAUSE_ANSWERED_ELSEWHERE) {
873                                 ast_channel_hangupcause_set(p->chan, AST_CAUSE_ANSWERED_ELSEWHERE);
874                                 ast_debug(2, "%s has AST_CAUSE_ANSWERED_ELSEWHERE set.\n",
875                                         ast_channel_name(p->chan));
876                         }
877                         if (!ast_test_flag(p, AST_UNREAL_CARETAKER_THREAD)) {
878                                 /*
879                                  * Need to actually hangup p->chan since nothing else is taking
880                                  * care of it.
881                                  */
882                                 hangup_chan = 1;
883                         } else {
884                                 ast_queue_hangup_with_cause(p->chan, cause);
885                         }
886                 }
887         }
888
889         /* this is one of our locked channels, doesn't matter which */
890         ast_channel_tech_pvt_set(ast, NULL);
891         ao2_ref(p, -1);
892
893 unreal_hangup_cleanup:
894         ao2_unlock(p);
895         if (owner) {
896                 ast_channel_unlock(owner);
897                 ast_channel_unref(owner);
898         }
899         if (chan) {
900                 ast_channel_unlock(chan);
901                 if (hangup_chan) {
902                         ast_hangup(chan);
903                 }
904                 ast_channel_unref(chan);
905         }
906
907         /* leave with the channel locked that came in */
908         ast_channel_lock(ast);
909
910         return res;
911 }
912
913 void ast_unreal_destructor(void *vdoomed)
914 {
915         struct ast_unreal_pvt *doomed = vdoomed;
916
917         ao2_cleanup(doomed->reqcap);
918         doomed->reqcap = NULL;
919 }
920
921 struct ast_unreal_pvt *ast_unreal_alloc(size_t size, ao2_destructor_fn destructor, struct ast_format_cap *cap)
922 {
923         struct ast_unreal_pvt *unreal;
924
925         static const struct ast_jb_conf jb_conf = {
926                 .flags = 0,
927                 .max_size = -1,
928                 .resync_threshold = -1,
929                 .impl = "",
930                 .target_extra = -1,
931         };
932
933         unreal = ao2_alloc(size, destructor);
934         if (!unreal) {
935                 return NULL;
936         }
937
938         unreal->reqcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
939         if (!unreal->reqcap) {
940                 ao2_ref(unreal, -1);
941                 return NULL;
942         }
943         ast_format_cap_append_from_cap(unreal->reqcap, cap, AST_MEDIA_TYPE_UNKNOWN);
944
945         memcpy(&unreal->jb_conf, &jb_conf, sizeof(unreal->jb_conf));
946
947         return unreal;
948 }
949
950 struct ast_channel *ast_unreal_new_channels(struct ast_unreal_pvt *p,
951         const struct ast_channel_tech *tech, int semi1_state, int semi2_state,
952         const char *exten, const char *context, const struct ast_assigned_ids *assignedids,
953         const struct ast_channel *requestor, ast_callid callid)
954 {
955         struct ast_channel *owner;
956         struct ast_channel *chan;
957         RAII_VAR(struct ast_format *, fmt, NULL, ao2_cleanup);
958         struct ast_assigned_ids id1 = {NULL, NULL};
959         struct ast_assigned_ids id2 = {NULL, NULL};
960         int generated_seqno = ast_atomic_fetchadd_int((int *) &name_sequence, +1);
961
962         /* set unique ids for the two channels */
963         if (assignedids && !ast_strlen_zero(assignedids->uniqueid)) {
964                 id1.uniqueid = assignedids->uniqueid;
965                 id2.uniqueid = assignedids->uniqueid2;
966         }
967
968         /* if id1 given but not id2, use default of id1;2 */
969         if (id1.uniqueid && ast_strlen_zero(id2.uniqueid)) {
970                 char *uniqueid2;
971
972                 uniqueid2 = ast_alloca(strlen(id1.uniqueid) + 3);
973                 strcpy(uniqueid2, id1.uniqueid);/* Safe */
974                 strcat(uniqueid2, ";2");/* Safe */
975                 id2.uniqueid = uniqueid2;
976         }
977
978         /*
979          * Allocate two new Asterisk channels
980          *
981          * Make sure that the ;2 channel gets the same linkedid as ;1.
982          * You can't pass linkedid to both allocations since if linkedid
983          * isn't set, then each channel will generate its own linkedid.
984          */
985         owner = ast_channel_alloc(1, semi1_state, NULL, NULL, NULL,
986                 exten, context, &id1, requestor, 0,
987                 "%s/%s-%08x;1", tech->type, p->name, (unsigned)generated_seqno);
988         if (!owner) {
989                 ast_log(LOG_WARNING, "Unable to allocate owner channel structure\n");
990                 return NULL;
991         }
992
993         if (callid) {
994                 ast_channel_callid_set(owner, callid);
995         }
996
997         ast_channel_tech_set(owner, tech);
998         ao2_ref(p, +1);
999         ast_channel_tech_pvt_set(owner, p);
1000
1001         ast_channel_nativeformats_set(owner, p->reqcap);
1002
1003         /* Determine our read/write format and set it on each channel */
1004         fmt = ast_format_cap_get_format(p->reqcap, 0);
1005         if (!fmt) {
1006                 ast_channel_tech_pvt_set(owner, NULL);
1007                 ao2_ref(p, -1);
1008                 ast_channel_unlock(owner);
1009                 ast_channel_release(owner);
1010                 return NULL;
1011         }
1012
1013         ast_channel_set_writeformat(owner, fmt);
1014         ast_channel_set_rawwriteformat(owner, fmt);
1015         ast_channel_set_readformat(owner, fmt);
1016         ast_channel_set_rawreadformat(owner, fmt);
1017
1018         ast_set_flag(ast_channel_flags(owner), AST_FLAG_DISABLE_DEVSTATE_CACHE);
1019
1020         ast_jb_configure(owner, &p->jb_conf);
1021
1022         if (ast_channel_cc_params_init(owner, requestor
1023                 ? ast_channel_get_cc_config_params((struct ast_channel *) requestor) : NULL)) {
1024                 ast_channel_tech_pvt_set(owner, NULL);
1025                 ao2_ref(p, -1);
1026                 ast_channel_tech_pvt_set(owner, NULL);
1027                 ast_channel_unlock(owner);
1028                 ast_channel_release(owner);
1029                 return NULL;
1030         }
1031
1032         p->owner = owner;
1033         ast_channel_unlock(owner);
1034
1035         chan = ast_channel_alloc(1, semi2_state, NULL, NULL, NULL,
1036                 exten, context, &id2, owner, 0,
1037                 "%s/%s-%08x;2", tech->type, p->name, (unsigned)generated_seqno);
1038         if (!chan) {
1039                 ast_log(LOG_WARNING, "Unable to allocate chan channel structure\n");
1040                 ast_channel_tech_pvt_set(owner, NULL);
1041                 ao2_ref(p, -1);
1042                 ast_channel_tech_pvt_set(owner, NULL);
1043                 ast_channel_release(owner);
1044                 return NULL;
1045         }
1046
1047         if (callid) {
1048                 ast_channel_callid_set(chan, callid);
1049         }
1050
1051         ast_channel_tech_set(chan, tech);
1052         ao2_ref(p, +1);
1053         ast_channel_tech_pvt_set(chan, p);
1054
1055         ast_channel_nativeformats_set(chan, p->reqcap);
1056
1057         /* Format was already determined when setting up owner */
1058         ast_channel_set_writeformat(chan, fmt);
1059         ast_channel_set_rawwriteformat(chan, fmt);
1060         ast_channel_set_readformat(chan, fmt);
1061         ast_channel_set_rawreadformat(chan, fmt);
1062
1063         ast_set_flag(ast_channel_flags(chan), AST_FLAG_DISABLE_DEVSTATE_CACHE);
1064
1065         p->chan = chan;
1066         ast_channel_unlock(chan);
1067
1068         return owner;
1069 }