res_pjsip_refer: Fix issue where native bridge may not occur upon completion of a...
[asterisk/asterisk.git] / res / res_pjsip_refer.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@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 /*** MODULEINFO
20         <depend>pjproject</depend>
21         <depend>res_pjsip</depend>
22         <depend>res_pjsip_session</depend>
23         <support_level>core</support_level>
24  ***/
25
26 #include "asterisk.h"
27
28 #include <pjsip.h>
29 #include <pjsip_ua.h>
30
31 #include "asterisk/res_pjsip.h"
32 #include "asterisk/res_pjsip_session.h"
33 #include "asterisk/module.h"
34 #include "asterisk/pbx.h"
35 #include "asterisk/taskprocessor.h"
36 #include "asterisk/bridge.h"
37 #include "asterisk/framehook.h"
38 #include "asterisk/stasis_bridges.h"
39 #include "asterisk/stasis_channels.h"
40
41 /*! \brief REFER Progress structure */
42 struct refer_progress {
43         /*! \brief Subscription to provide updates on */
44         pjsip_evsub *sub;
45         /*! \brief Dialog for subscription */
46         pjsip_dialog *dlg;
47         /*! \brief Received packet, used to construct final response in case no subscription exists */
48         pjsip_rx_data *rdata;
49         /*! \brief Frame hook for monitoring REFER progress */
50         int framehook;
51         /*! \brief Last received subclass in frame hook */
52         int subclass;
53         /*! \brief Serializer for notifications */
54         struct ast_taskprocessor *serializer;
55         /*! \brief Stasis subscription for bridge events */
56         struct stasis_subscription *bridge_sub;
57         /*! \brief Reference to transfer_channel_data related to the refer */
58         struct transfer_channel_data *transfer_data;
59         /*! \brief Uniqueid of transferee channel */
60         char *transferee;
61 };
62
63 /*! \brief REFER Progress notification structure */
64 struct refer_progress_notification {
65         /*! \brief Refer progress structure to send notification on */
66         struct refer_progress *progress;
67         /*! \brief SIP response code to send */
68         int response;
69         /*! \brief Subscription state */
70         pjsip_evsub_state state;
71 };
72
73 /*! \brief REFER Progress module, used to attach REFER progress structure to subscriptions */
74 static pjsip_module refer_progress_module = {
75         .name = { "REFER Progress", 14 },
76         .id = -1,
77 };
78
79 /*! \brief Destructor for REFER Progress notification structure */
80 static void refer_progress_notification_destroy(void *obj)
81 {
82         struct refer_progress_notification *notification = obj;
83
84         ao2_cleanup(notification->progress);
85 }
86
87 /*! \brief Allocator for REFER Progress notification structure */
88 static struct refer_progress_notification *refer_progress_notification_alloc(struct refer_progress *progress, int response,
89         pjsip_evsub_state state)
90 {
91         struct refer_progress_notification *notification = ao2_alloc(sizeof(*notification), refer_progress_notification_destroy);
92
93         if (!notification) {
94                 return NULL;
95         }
96
97         ao2_ref(progress, +1);
98         notification->progress = progress;
99         notification->response = response;
100         notification->state = state;
101
102         return notification;
103 }
104
105 /*! \brief Serialized callback for subscription notification */
106 static int refer_progress_notify(void *data)
107 {
108         RAII_VAR(struct refer_progress_notification *, notification, data, ao2_cleanup);
109         pjsip_evsub *sub;
110         pjsip_tx_data *tdata;
111
112         /* If the subscription has already been terminated we can't send a notification */
113         if (!(sub = notification->progress->sub)) {
114                 ast_debug(3, "Not sending NOTIFY of response '%d' and state '%u' on progress monitor '%p' as subscription has been terminated\n",
115                         notification->response, notification->state, notification->progress);
116                 return 0;
117         }
118
119         /* If the subscription is being terminated we want to actually remove the progress structure here to
120          * stop a deadlock from occurring - basically terminated changes the state which queues a synchronous task
121          * but we are already running a task... thus it would deadlock */
122         if (notification->state == PJSIP_EVSUB_STATE_TERMINATED) {
123                 ast_debug(3, "Subscription '%p' is being terminated as a result of a NOTIFY, removing REFER progress structure early on progress monitor '%p'\n",
124                         notification->progress->sub, notification->progress);
125                 pjsip_dlg_inc_lock(notification->progress->dlg);
126                 pjsip_evsub_set_mod_data(notification->progress->sub, refer_progress_module.id, NULL);
127                 pjsip_dlg_dec_lock(notification->progress->dlg);
128
129                 /* This is for dropping the reference on the subscription */
130                 ao2_cleanup(notification->progress);
131
132                 notification->progress->sub = NULL;
133         }
134
135         ast_debug(3, "Sending NOTIFY with response '%d' and state '%u' on subscription '%p' and progress monitor '%p'\n",
136                 notification->response, notification->state, sub, notification->progress);
137
138         /* Actually send the notification */
139         if (pjsip_xfer_notify(sub, notification->state, notification->response, NULL, &tdata) == PJ_SUCCESS) {
140                 pjsip_xfer_send_request(sub, tdata);
141         }
142
143         return 0;
144 }
145
146 static void refer_progress_bridge(void *data, struct stasis_subscription *sub,
147                 struct stasis_message *message)
148 {
149         struct refer_progress *progress = data;
150         struct ast_bridge_blob *enter_blob;
151         struct refer_progress_notification *notification;
152         struct ast_channel *chan;
153
154         if (stasis_subscription_final_message(sub, message)) {
155                 ao2_ref(progress, -1);
156                 return;
157         }
158
159         if (ast_channel_entered_bridge_type() != stasis_message_type(message)) {
160                 /* Don't care */
161                 return;
162         }
163
164         enter_blob = stasis_message_data(message);
165         if (strcmp(enter_blob->channel->uniqueid, progress->transferee)) {
166                 /* Don't care */
167                 return;
168         }
169
170         if (!progress->transfer_data->completed) {
171                 /* We can't act on this message because the transfer_channel_data doesn't show that
172                  * the transfer is ready to progress */
173                 return;
174         }
175
176         /* OMG the transferee is joining a bridge. His call got answered! */
177         notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
178         if (notification) {
179                 if (ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
180                         ao2_cleanup(notification);
181                 }
182                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
183         }
184
185         chan = ast_channel_get_by_name(progress->transferee);
186         if (!chan) {
187                 /* The channel is already gone */
188                 return;
189         }
190
191         ast_channel_lock(chan);
192         ast_debug(3, "Detaching REFER progress monitoring hook from '%s' as it has joined a bridge\n",
193                 ast_channel_name(chan));
194         ast_framehook_detach(chan, progress->framehook);
195         ast_channel_unlock(chan);
196
197         ast_channel_unref(chan);
198 }
199
200 /*! \brief Progress monitoring frame hook - examines frames to determine state of transfer */
201 static struct ast_frame *refer_progress_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data)
202 {
203         struct refer_progress *progress = data;
204         struct refer_progress_notification *notification = NULL;
205
206         /* We only care about frames *to* the channel */
207         if (!f || (event != AST_FRAMEHOOK_EVENT_WRITE)) {
208                 return f;
209         }
210
211         /* If the completed flag hasn't been raised, skip this pass. */
212         if (!progress->transfer_data->completed) {
213                 return f;
214         }
215
216         /* Determine the state of the REFER based on the control frames (or voice frames) passing */
217         if (f->frametype == AST_FRAME_VOICE && !progress->subclass) {
218                 /* Media is passing without progress, this means the call has been answered */
219                 notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
220         } else if (f->frametype == AST_FRAME_CONTROL) {
221                 /* Based on the control frame being written we can send a NOTIFY advising of the progress */
222                 if ((f->subclass.integer == AST_CONTROL_RING) || (f->subclass.integer == AST_CONTROL_RINGING)) {
223                         progress->subclass = f->subclass.integer;
224                         notification = refer_progress_notification_alloc(progress, 180, PJSIP_EVSUB_STATE_ACTIVE);
225                 } else if (f->subclass.integer == AST_CONTROL_BUSY) {
226                         progress->subclass = f->subclass.integer;
227                         notification = refer_progress_notification_alloc(progress, 486, PJSIP_EVSUB_STATE_TERMINATED);
228                 } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
229                         progress->subclass = f->subclass.integer;
230                         notification = refer_progress_notification_alloc(progress, 503, PJSIP_EVSUB_STATE_TERMINATED);
231                 } else if (f->subclass.integer == AST_CONTROL_PROGRESS) {
232                         progress->subclass = f->subclass.integer;
233                         notification = refer_progress_notification_alloc(progress, 183, PJSIP_EVSUB_STATE_ACTIVE);
234                 } else if (f->subclass.integer == AST_CONTROL_PROCEEDING) {
235                         progress->subclass = f->subclass.integer;
236                         notification = refer_progress_notification_alloc(progress, 100, PJSIP_EVSUB_STATE_ACTIVE);
237                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
238                         progress->subclass = f->subclass.integer;
239                         notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
240                 }
241         }
242
243         /* If a notification is due to be sent push it to the thread pool */
244         if (notification) {
245                 if (ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
246                         ao2_cleanup(notification);
247                 }
248
249                 /* If the subscription is being terminated we don't need the frame hook any longer */
250                 if (notification->state == PJSIP_EVSUB_STATE_TERMINATED) {
251                         ast_debug(3, "Detaching REFER progress monitoring hook from '%s' as subscription is being terminated\n",
252                                 ast_channel_name(chan));
253                         ast_framehook_detach(chan, progress->framehook);
254                 }
255         }
256
257         return f;
258 }
259
260 /*! \brief Destroy callback for monitoring framehook */
261 static void refer_progress_framehook_destroy(void *data)
262 {
263         struct refer_progress *progress = data;
264         struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, 503, PJSIP_EVSUB_STATE_TERMINATED);
265
266         if (notification && ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
267                 ao2_cleanup(notification);
268         }
269
270         if (progress->bridge_sub) {
271                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
272         }
273
274         ao2_cleanup(progress);
275 }
276
277 /*! \brief Serialized callback for subscription termination */
278 static int refer_progress_terminate(void *data)
279 {
280         struct refer_progress *progress = data;
281
282         /* The subscription is no longer valid */
283         progress->sub = NULL;
284
285         return 0;
286 }
287
288 /*! \brief Callback for REFER subscription state changes */
289 static void refer_progress_on_evsub_state(pjsip_evsub *sub, pjsip_event *event)
290 {
291         struct refer_progress *progress = pjsip_evsub_get_mod_data(sub, refer_progress_module.id);
292
293         /* If being destroyed queue it up to the serializer */
294         if (progress && (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED)) {
295                 /* To prevent a deadlock race condition we unlock the dialog so other serialized tasks can execute */
296                 ast_debug(3, "Subscription '%p' has been remotely terminated, waiting for other tasks to complete on progress monitor '%p'\n",
297                         sub, progress);
298
299                 /* It's possible that a task is waiting to remove us already, so bump the refcount of progress so it doesn't get destroyed */
300                 ao2_ref(progress, +1);
301                 pjsip_dlg_dec_lock(progress->dlg);
302                 ast_sip_push_task_synchronous(progress->serializer, refer_progress_terminate, progress);
303                 pjsip_dlg_inc_lock(progress->dlg);
304                 ao2_ref(progress, -1);
305
306                 ast_debug(3, "Subscription '%p' removed from progress monitor '%p'\n", sub, progress);
307
308                 /* Since it was unlocked it is possible for this to have been removed already, so check again */
309                 if (pjsip_evsub_get_mod_data(sub, refer_progress_module.id)) {
310                         pjsip_evsub_set_mod_data(sub, refer_progress_module.id, NULL);
311                         ao2_cleanup(progress);
312                 }
313         }
314 }
315
316 /*! \brief Callback structure for subscription */
317 static pjsip_evsub_user refer_progress_evsub_cb = {
318         .on_evsub_state = refer_progress_on_evsub_state,
319 };
320
321 /*! \brief Destructor for REFER progress sutrcture */
322 static void refer_progress_destroy(void *obj)
323 {
324         struct refer_progress *progress = obj;
325
326         if (progress->bridge_sub) {
327                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
328         }
329
330         ao2_cleanup(progress->transfer_data);
331
332         ast_free(progress->transferee);
333         ast_taskprocessor_unreference(progress->serializer);
334 }
335
336 /*! \brief Internal helper function which sets up a refer progress structure if needed */
337 static int refer_progress_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata, struct refer_progress **progress)
338 {
339         const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
340         pjsip_generic_string_hdr *refer_sub = NULL;
341         const pj_str_t str_true = { "true", 4 };
342         pjsip_tx_data *tdata;
343         pjsip_hdr hdr_list;
344
345         *progress = NULL;
346
347         /* Grab the optional Refer-Sub header, it can be used to suppress the implicit subscription */
348         refer_sub = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL);
349         if ((refer_sub && pj_strnicmp(&refer_sub->hvalue, &str_true, 4))) {
350                 return 0;
351         }
352
353         if (!(*progress = ao2_alloc(sizeof(struct refer_progress), refer_progress_destroy))) {
354                 return -1;
355         }
356
357         ast_debug(3, "Created progress monitor '%p' for transfer occurring from channel '%s' and endpoint '%s'\n",
358                 progress, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
359
360         (*progress)->framehook = -1;
361
362         /* To prevent a potential deadlock we need the dialog so we can lock/unlock */
363         (*progress)->dlg = session->inv_session->dlg;
364
365         if (!((*progress)->serializer = ast_sip_create_serializer())) {
366                 goto error;
367         }
368
369         /* Create the implicit subscription for monitoring of this transfer */
370         if (pjsip_xfer_create_uas(session->inv_session->dlg, &refer_progress_evsub_cb, rdata, &(*progress)->sub) != PJ_SUCCESS) {
371                 goto error;
372         }
373
374         /* Associate the REFER progress structure with the subscription */
375         ao2_ref(*progress, +1);
376         pjsip_evsub_set_mod_data((*progress)->sub, refer_progress_module.id, *progress);
377
378         pj_list_init(&hdr_list);
379         if (refer_sub) {
380                 pjsip_hdr *hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(session->inv_session->dlg->pool, &str_refer_sub, &str_true);
381
382                 pj_list_push_back(&hdr_list, hdr);
383         }
384
385         /* Accept the REFER request */
386         ast_debug(3, "Accepting REFER request for progress monitor '%p'\n", *progress);
387         pjsip_xfer_accept((*progress)->sub, rdata, 202, &hdr_list);
388
389         /* Send initial NOTIFY Request */
390         ast_debug(3, "Sending initial 100 Trying NOTIFY for progress monitor '%p'\n", *progress);
391         if (pjsip_xfer_notify((*progress)->sub, PJSIP_EVSUB_STATE_ACTIVE, 100, NULL, &tdata) == PJ_SUCCESS) {
392                 pjsip_xfer_send_request((*progress)->sub, tdata);
393         }
394
395         return 0;
396
397 error:
398         ao2_cleanup(*progress);
399         *progress = NULL;
400         return -1;
401 }
402
403 /*! \brief Structure for attended transfer task */
404 struct refer_attended {
405         /*! \brief Transferer session */
406         struct ast_sip_session *transferer;
407         /*! \brief Transferer channel */
408         struct ast_channel *transferer_chan;
409         /*! \brief Second transferer session */
410         struct ast_sip_session *transferer_second       ;
411         /*! \brief Optional refer progress structure */
412         struct refer_progress *progress;
413 };
414
415 /*! \brief Destructor for attended transfer task */
416 static void refer_attended_destroy(void *obj)
417 {
418         struct refer_attended *attended = obj;
419
420         ao2_cleanup(attended->transferer);
421         ast_channel_unref(attended->transferer_chan);
422         ao2_cleanup(attended->transferer_second);
423 }
424
425 /*! \brief Allocator for attended transfer task */
426 static struct refer_attended *refer_attended_alloc(struct ast_sip_session *transferer, struct ast_sip_session *transferer_second,
427         struct refer_progress *progress)
428 {
429         struct refer_attended *attended = ao2_alloc(sizeof(*attended), refer_attended_destroy);
430
431         if (!attended) {
432                 return NULL;
433         }
434
435         ao2_ref(transferer, +1);
436         attended->transferer = transferer;
437         ast_channel_ref(transferer->channel);
438         attended->transferer_chan = transferer->channel;
439         ao2_ref(transferer_second, +1);
440         attended->transferer_second = transferer_second;
441
442         if (progress) {
443                 ao2_ref(progress, +1);
444                 attended->progress = progress;
445         }
446
447         return attended;
448 }
449
450 /*! \brief Task for attended transfer */
451 static int refer_attended(void *data)
452 {
453         RAII_VAR(struct refer_attended *, attended, data, ao2_cleanup);
454         int response = 0;
455
456         if (!attended->transferer_second->channel) {
457                 return -1;
458         }
459
460         ast_debug(3, "Performing a REFER attended transfer - Transferer #1: %s Transferer #2: %s\n",
461                 ast_channel_name(attended->transferer_chan), ast_channel_name(attended->transferer_second->channel));
462
463         switch (ast_bridge_transfer_attended(attended->transferer_chan, attended->transferer_second->channel)) {
464         case AST_BRIDGE_TRANSFER_INVALID:
465                 response = 400;
466                 break;
467         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
468                 response = 403;
469                 break;
470         case AST_BRIDGE_TRANSFER_FAIL:
471                 response = 500;
472                 break;
473         case AST_BRIDGE_TRANSFER_SUCCESS:
474                 response = 200;
475                 ast_sip_session_defer_termination(attended->transferer);
476                 break;
477         }
478
479         ast_debug(3, "Final response for REFER attended transfer - Transferer #1: %s Transferer #2: %s is '%d'\n",
480                 ast_channel_name(attended->transferer_chan), ast_channel_name(attended->transferer_second->channel), response);
481
482         if (attended->progress && response) {
483                 struct refer_progress_notification *notification = refer_progress_notification_alloc(attended->progress, response, PJSIP_EVSUB_STATE_TERMINATED);
484
485                 if (notification) {
486                         refer_progress_notify(notification);
487                 }
488         }
489
490         return 0;
491 }
492
493 /*! \brief Structure for blind transfer callback details */
494 struct refer_blind {
495         /*! \brief Context being used for transfer */
496         const char *context;
497         /*! \brief Optional progress structure */
498         struct refer_progress *progress;
499         /*! \brief REFER message */
500         pjsip_rx_data *rdata;
501         /*! \brief Optional Replaces header */
502         pjsip_replaces_hdr *replaces;
503         /*! \brief Optional Refer-To header */
504         pjsip_sip_uri *refer_to;
505 };
506
507 /*! \brief Blind transfer callback function */
508 static void refer_blind_callback(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
509         enum ast_transfer_type transfer_type)
510 {
511         struct refer_blind *refer = user_data_wrapper->data;
512         pjsip_generic_string_hdr *referred_by;
513
514         static const pj_str_t str_referred_by = { "Referred-By", 11 };
515
516         pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
517
518         /* If progress monitoring is being done attach a frame hook so we can monitor it */
519         if (refer->progress) {
520                 struct ast_framehook_interface hook = {
521                         .version = AST_FRAMEHOOK_INTERFACE_VERSION,
522                         .event_cb = refer_progress_framehook,
523                         .destroy_cb = refer_progress_framehook_destroy,
524                         .data = refer->progress,
525                         .disable_inheritance = 1,
526                 };
527
528                 refer->progress->transferee = ast_strdup(ast_channel_uniqueid(chan));
529                 if (!refer->progress->transferee) {
530                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
531                                 PJSIP_EVSUB_STATE_TERMINATED);
532
533                         ast_log(LOG_WARNING, "Could not copy channel name '%s' during transfer - assuming success\n",
534                                 ast_channel_name(chan));
535
536                         if (notification) {
537                                 refer_progress_notify(notification);
538                         }
539                 }
540
541                 /* Progress needs a reference to the transfer_channel_data so that it can track the completed status of the transfer */
542                 ao2_ref(user_data_wrapper, +1);
543                 refer->progress->transfer_data = user_data_wrapper;
544
545                 /* We need to bump the reference count up on the progress structure since it is in the frame hook now */
546                 ao2_ref(refer->progress, +1);
547
548                 /* If we can't attach a frame hook for whatever reason send a notification of success immediately */
549                 if ((refer->progress->framehook = ast_framehook_attach(chan, &hook)) < 0) {
550                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
551                                 PJSIP_EVSUB_STATE_TERMINATED);
552
553                         ast_log(LOG_WARNING, "Could not attach REFER transfer progress monitoring hook to channel '%s' - assuming success\n",
554                                 ast_channel_name(chan));
555
556                         if (notification) {
557                                 refer_progress_notify(notification);
558                         }
559
560                         ao2_cleanup(refer->progress);
561                 }
562
563                 /* We need to bump the reference count for the stasis subscription */
564                 ao2_ref(refer->progress, +1);
565                 /* We also will need to detect if the transferee enters a bridge. This is currently the only reliable way to
566                  * detect if the transfer target has answered the call
567                  */
568                 refer->progress->bridge_sub = stasis_subscribe_pool(ast_bridge_topic_all(), refer_progress_bridge, refer->progress);
569                 if (!refer->progress->bridge_sub) {
570                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
571                                 PJSIP_EVSUB_STATE_TERMINATED);
572
573                         ast_log(LOG_WARNING, "Could not create bridge stasis subscription for monitoring progress on transfer of channel '%s' - assuming success\n",
574                                         ast_channel_name(chan));
575
576                         if (notification) {
577                                 refer_progress_notify(notification);
578                         }
579
580                         ast_framehook_detach(chan, refer->progress->framehook);
581
582                         ao2_cleanup(refer->progress);
583                 }
584         }
585
586         pbx_builtin_setvar_helper(chan, "SIPREFERRINGCONTEXT", S_OR(refer->context, NULL));
587
588         referred_by = pjsip_msg_find_hdr_by_name(refer->rdata->msg_info.msg,
589                 &str_referred_by, NULL);
590         if (referred_by) {
591                 size_t uri_size = pj_strlen(&referred_by->hvalue) + 1;
592                 char *uri = ast_alloca(uri_size);
593
594                 ast_copy_pj_str(uri, &referred_by->hvalue, uri_size);
595                 pbx_builtin_setvar_helper(chan, "__SIPREFERREDBYHDR", S_OR(uri, NULL));
596         } else {
597                 pbx_builtin_setvar_helper(chan, "SIPREFERREDBYHDR", NULL);
598         }
599
600         if (refer->replaces) {
601                 char replaces[512];
602
603                 pjsip_hdr_print_on(refer->replaces, replaces, sizeof(replaces));
604                 pbx_builtin_setvar_helper(chan, "__SIPREPLACESHDR", S_OR(replaces, NULL));
605         } else {
606                 pbx_builtin_setvar_helper(chan, "SIPREPLACESHDR", NULL);
607         }
608
609         if (refer->refer_to) {
610                 char refer_to[PJSIP_MAX_URL_SIZE];
611
612                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, refer->refer_to, refer_to, sizeof(refer_to));
613                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", S_OR(refer_to, NULL));
614         } else {
615                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", NULL);
616         }
617 }
618
619 static int refer_incoming_attended_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target_uri,
620         pjsip_param *replaces_param, struct refer_progress *progress)
621 {
622         const pj_str_t str_replaces = { "Replaces", 8 };
623         pj_str_t replaces_content;
624         pjsip_replaces_hdr *replaces;
625         int parsed_len;
626         pjsip_dialog *dlg;
627
628         pj_strdup_with_null(rdata->tp_info.pool, &replaces_content, &replaces_param->value);
629
630         /* Parsing the parameter as a Replaces header easily grabs the needed information */
631         if (!(replaces = pjsip_parse_hdr(rdata->tp_info.pool, &str_replaces, replaces_content.ptr,
632                 pj_strlen(&replaces_content), &parsed_len))) {
633                 ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' with invalid Replaces header, rejecting\n",
634                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
635                 return 400;
636         }
637
638         /* See if the dialog is local, or remote */
639         if ((dlg = pjsip_ua_find_dialog(&replaces->call_id, &replaces->to_tag, &replaces->from_tag, PJ_TRUE))) {
640                 RAII_VAR(struct ast_sip_session *, other_session, ast_sip_dialog_get_session(dlg), ao2_cleanup);
641                 struct refer_attended *attended;
642
643                 pjsip_dlg_dec_lock(dlg);
644
645                 if (!other_session) {
646                         ast_debug(3, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but no session exists on it\n",
647                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
648                         return 603;
649                 }
650
651                 /* We defer actually doing the attended transfer to the other session so no deadlock can occur */
652                 if (!(attended = refer_attended_alloc(session, other_session, progress))) {
653                         ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but could not allocate structure to complete, rejecting\n",
654                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
655                         return 500;
656                 }
657
658                 /* Push it to the other session, which will have both channels with minimal locking */
659                 if (ast_sip_push_task(other_session->serializer, refer_attended, attended)) {
660                         ao2_cleanup(attended);
661                         return 500;
662                 }
663
664                 ast_debug(3, "Attended transfer from '%s' pushed to second channel serializer\n",
665                         ast_channel_name(session->channel));
666
667                 return 200;
668         } else {
669                 const char *context = (session->channel ? pbx_builtin_getvar_helper(session->channel, "TRANSFER_CONTEXT") : "");
670                 struct refer_blind refer = { 0, };
671
672                 if (ast_strlen_zero(context)) {
673                         context = session->endpoint->context;
674                 }
675
676                 if (!ast_exists_extension(NULL, context, "external_replaces", 1, NULL)) {
677                         ast_log(LOG_ERROR, "Received REFER for remote session on channel '%s' from endpoint '%s' but 'external_replaces' context does not exist for handling\n",
678                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
679                         return 404;
680                 }
681
682                 refer.context = context;
683                 refer.progress = progress;
684                 refer.rdata = rdata;
685                 refer.replaces = replaces;
686                 refer.refer_to = target_uri;
687
688                 switch (ast_bridge_transfer_blind(1, session->channel, "external_replaces", context, refer_blind_callback, &refer)) {
689                 case AST_BRIDGE_TRANSFER_INVALID:
690                         return 400;
691                 case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
692                         return 403;
693                 case AST_BRIDGE_TRANSFER_FAIL:
694                         return 500;
695                 case AST_BRIDGE_TRANSFER_SUCCESS:
696                         ast_sip_session_defer_termination(session);
697                         return 200;
698                 }
699
700                 return 503;
701         }
702
703         return 0;
704 }
705
706 static int refer_incoming_blind_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target,
707         struct refer_progress *progress)
708 {
709         const char *context;
710         char exten[AST_MAX_EXTENSION];
711         struct refer_blind refer = { 0, };
712
713         if (!session->channel) {
714                 return 404;
715         }
716
717         /* If no explicit transfer context has been provided use their configured context */
718         context = pbx_builtin_getvar_helper(session->channel, "TRANSFER_CONTEXT");
719         if (ast_strlen_zero(context)) {
720                 context = session->endpoint->context;
721         }
722
723         /* Using the user portion of the target URI see if it exists as a valid extension in their context */
724         ast_copy_pj_str(exten, &target->user, sizeof(exten));
725         if (!ast_exists_extension(NULL, context, exten, 1, NULL)) {
726                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer to '%s@%s' but target does not exist\n",
727                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), exten, context);
728                 return 404;
729         }
730
731         refer.context = context;
732         refer.progress = progress;
733         refer.rdata = rdata;
734         refer.refer_to = target;
735
736         switch (ast_bridge_transfer_blind(1, session->channel, exten, context, refer_blind_callback, &refer)) {
737         case AST_BRIDGE_TRANSFER_INVALID:
738                 return 400;
739         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
740                 return 403;
741         case AST_BRIDGE_TRANSFER_FAIL:
742                 return 500;
743         case AST_BRIDGE_TRANSFER_SUCCESS:
744                 ast_sip_session_defer_termination(session);
745                 return 200;
746         }
747
748         return 503;
749 }
750
751 /*! \brief Structure used to retrieve channel from another session */
752 struct invite_replaces {
753         /*! \brief Session we want the channel from */
754         struct ast_sip_session *session;
755         /*! \brief Channel from the session (with reference) */
756         struct ast_channel *channel;
757         /*! \brief Bridge the channel is in */
758         struct ast_bridge *bridge;
759 };
760
761 /*! \brief Task for invite replaces */
762 static int invite_replaces(void *data)
763 {
764         struct invite_replaces *invite = data;
765
766         if (!invite->session->channel) {
767                 return -1;
768         }
769
770         ast_channel_ref(invite->session->channel);
771         invite->channel = invite->session->channel;
772
773         ast_channel_lock(invite->channel);
774         invite->bridge = ast_channel_get_bridge(invite->channel);
775         ast_channel_unlock(invite->channel);
776
777         return 0;
778 }
779
780 static int refer_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
781 {
782         pjsip_dialog *other_dlg = NULL;
783         pjsip_tx_data *packet;
784         int response = 0;
785         RAII_VAR(struct ast_sip_session *, other_session, NULL, ao2_cleanup);
786         struct invite_replaces invite;
787
788         /* If a Replaces header is present make sure it is valid */
789         if (pjsip_replaces_verify_request(rdata, &other_dlg, PJ_TRUE, &packet) != PJ_SUCCESS) {
790                 response = packet->msg->line.status.code;
791                 pjsip_tx_data_dec_ref(packet);
792                 goto end;
793         }
794
795         /* If no other dialog exists then this INVITE request does not have a Replaces header */
796         if (!other_dlg) {
797                 return 0;
798         }
799
800         other_session = ast_sip_dialog_get_session(other_dlg);
801         pjsip_dlg_dec_lock(other_dlg);
802
803         /* Don't accept an in-dialog INVITE with Replaces as it does not make much sense */
804         if (session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
805                 response = 488;
806                 goto end;
807         }
808
809         if (!other_session) {
810                 response = 481;
811                 ast_debug(3, "INVITE with Replaces received on channel '%s' from endpoint '%s', but requested session does not exist\n",
812                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
813                 goto end;
814         }
815
816         invite.session = other_session;
817
818         if (ast_sip_push_task_synchronous(other_session->serializer, invite_replaces, &invite)) {
819                 response = 481;
820                 goto end;
821         }
822
823         ast_channel_lock(session->channel);
824         ast_setstate(session->channel, AST_STATE_RING);
825         ast_channel_unlock(session->channel);
826         ast_raw_answer(session->channel);
827
828         if (!invite.bridge) {
829                 struct ast_channel *chan = session->channel;
830
831                 /* This will use a synchronous task but we aren't operating in the serializer at this point in time, so it
832                  * won't deadlock */
833                 if (!ast_channel_move(invite.channel, session->channel)) {
834                         ast_hangup(chan);
835                 } else {
836                         response = 500;
837                 }
838         } else {
839                 if (ast_bridge_impart(invite.bridge, session->channel, invite.channel, NULL,
840                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
841                         response = 500;
842                 }
843         }
844
845         if (!response) {
846                 ast_debug(3, "INVITE with Replaces successfully completed on channels '%s' and '%s'\n",
847                         ast_channel_name(session->channel), ast_channel_name(invite.channel));
848         }
849
850         ast_channel_unref(invite.channel);
851         ao2_cleanup(invite.bridge);
852
853 end:
854         if (response) {
855                 if (session->inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
856                         ast_debug(3, "INVITE with Replaces failed on channel '%s', sending response of '%d'\n",
857                                 ast_channel_name(session->channel), response);
858                         session->defer_terminate = 1;
859                         ast_hangup(session->channel);
860                         session->channel = NULL;
861
862                         if (pjsip_inv_end_session(session->inv_session, response, NULL, &packet) == PJ_SUCCESS) {
863                                 ast_sip_session_send_response(session, packet);
864                         }
865                 } else {
866                         ast_debug(3, "INVITE with Replaces in-dialog on channel '%s', hanging up\n",
867                                 ast_channel_name(session->channel));
868                         ast_queue_hangup(session->channel);
869                 }
870         }
871
872         return 1;
873 }
874
875 static int refer_incoming_refer_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
876 {
877         pjsip_generic_string_hdr *refer_to;
878         char *uri;
879         pjsip_uri *target;
880         pjsip_sip_uri *target_uri;
881         RAII_VAR(struct refer_progress *, progress, NULL, ao2_cleanup);
882         pjsip_param *replaces;
883         int response;
884
885         static const pj_str_t str_refer_to = { "Refer-To", 8 };
886         static const pj_str_t str_replaces = { "Replaces", 8 };
887
888         if (!session->endpoint->allowtransfer) {
889                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 603, NULL, NULL, NULL);
890                 ast_log(LOG_WARNING, "Endpoint %s transfer attempt blocked due to configuration\n",
891                                 ast_sorcery_object_get_id(session->endpoint));
892                 return 0;
893         }
894
895         /* A Refer-To header is required */
896         refer_to = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL);
897         if (!refer_to) {
898                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
899                 ast_debug(3, "Received a REFER without Refer-To on channel '%s' from endpoint '%s'\n",
900                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
901                 return 0;
902         }
903
904         /* This is done on purpose (and is safe) - it's done so that the value passed to
905          * pjsip_parse_uri is NULL terminated as required
906          */
907         uri = refer_to->hvalue.ptr;
908         uri[refer_to->hvalue.slen] = '\0';
909
910         target = pjsip_parse_uri(rdata->tp_info.pool, refer_to->hvalue.ptr, refer_to->hvalue.slen, 0);
911         if (!target
912                 || (!PJSIP_URI_SCHEME_IS_SIP(target)
913                         && !PJSIP_URI_SCHEME_IS_SIPS(target))) {
914                 size_t uri_size = pj_strlen(&refer_to->hvalue) + 1;
915                 char *uri = ast_alloca(uri_size);
916
917                 ast_copy_pj_str(uri, &refer_to->hvalue, uri_size);
918
919                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
920                 ast_debug(3, "Received a REFER without a parseable Refer-To ('%s') on channel '%s' from endpoint '%s'\n",
921                         uri, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
922                 return 0;
923         }
924         target_uri = pjsip_uri_get_uri(target);
925
926         /* Set up REFER progress subscription if requested/possible */
927         if (refer_progress_alloc(session, rdata, &progress)) {
928                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 500, NULL, NULL, NULL);
929                 ast_debug(3, "Could not set up subscription for REFER on channel '%s' from endpoint '%s'\n",
930                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
931                 return 0;
932         }
933
934         /* Determine if this is an attended or blind transfer */
935         if ((replaces = pjsip_param_find(&target_uri->header_param, &str_replaces)) ||
936                 (replaces = pjsip_param_find(&target_uri->other_param, &str_replaces))) {
937                 response = refer_incoming_attended_request(session, rdata, target_uri, replaces, progress);
938         } else {
939                 response = refer_incoming_blind_request(session, rdata, target_uri, progress);
940         }
941
942         if (!progress) {
943                 /* The transferer has requested no subscription, so send a final response immediately */
944                 pjsip_tx_data *tdata;
945                 const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
946                 const pj_str_t str_false = { "false", 5 };
947                 pjsip_hdr *hdr;
948
949                 ast_debug(3, "Progress monitoring not requested for REFER on channel '%s' from endpoint '%s', sending immediate response of '%d'\n",
950                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), response);
951
952                 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, response, NULL, &tdata) != PJ_SUCCESS) {
953                         pjsip_dlg_respond(session->inv_session->dlg, rdata, response, NULL, NULL, NULL);
954                         return 0;
955                 }
956
957                 hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub, &str_false);
958                 pjsip_msg_add_hdr(tdata->msg, hdr);
959
960                 pjsip_dlg_send_response(session->inv_session->dlg, pjsip_rdata_get_tsx(rdata), tdata);
961         } else if (response != 200) {
962                 /* Since this failed we can send a final NOTIFY now and terminate the subscription */
963                 struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, response, PJSIP_EVSUB_STATE_TERMINATED);
964
965                 if (notification) {
966                         /* The refer_progress_notify function will call ao2_cleanup on this for us */
967                         refer_progress_notify(notification);
968                 }
969         }
970
971         return 0;
972 }
973
974 static int refer_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
975 {
976         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_refer_method())) {
977                 return refer_incoming_refer_request(session, rdata);
978         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_invite_method)) {
979                 return refer_incoming_invite_request(session, rdata);
980         } else {
981                 return 0;
982         }
983 }
984
985 static void refer_outgoing_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
986 {
987         const char *hdr;
988
989         if (pjsip_method_cmp(&tdata->msg->line.req.method, &pjsip_invite_method)
990                 || !session->channel
991                 || session->inv_session->state != PJSIP_INV_STATE_NULL) {
992                 return;
993         }
994
995         ast_channel_lock(session->channel);
996         hdr = pbx_builtin_getvar_helper(session->channel, "SIPREPLACESHDR");
997         if (!ast_strlen_zero(hdr)) {
998                 ast_sip_add_header(tdata, "Replaces", hdr);
999         }
1000
1001         hdr = pbx_builtin_getvar_helper(session->channel, "SIPREFERREDBYHDR");
1002         if (!ast_strlen_zero(hdr)) {
1003                 ast_sip_add_header(tdata, "Referred-By", hdr);
1004         }
1005         ast_channel_unlock(session->channel);
1006 }
1007
1008 static struct ast_sip_session_supplement refer_supplement = {
1009         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
1010         .incoming_request = refer_incoming_request,
1011         .outgoing_request = refer_outgoing_request,
1012 };
1013
1014 static int load_module(void)
1015 {
1016         const pj_str_t str_norefersub = { "norefersub", 10 };
1017
1018         CHECK_PJSIP_SESSION_MODULE_LOADED();
1019
1020         pjsip_replaces_init_module(ast_sip_get_pjsip_endpoint());
1021         pjsip_xfer_init_module(ast_sip_get_pjsip_endpoint());
1022         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_SUPPORTED, NULL, 1, &str_norefersub);
1023
1024         ast_sip_register_service(&refer_progress_module);
1025         ast_sip_session_register_supplement(&refer_supplement);
1026
1027         return AST_MODULE_LOAD_SUCCESS;
1028 }
1029
1030 static int unload_module(void)
1031 {
1032         ast_sip_session_unregister_supplement(&refer_supplement);
1033         ast_sip_unregister_service(&refer_progress_module);
1034
1035         return 0;
1036 }
1037
1038 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Blind and Attended Transfer Support",
1039                 .support_level = AST_MODULE_SUPPORT_CORE,
1040                 .load = load_module,
1041                 .unload = unload_module,
1042                 .load_pri = AST_MODPRI_APP_DEPEND,
1043                    );