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