chan_ooh323: fix h323 log file path
[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 #include "asterisk/causes.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 Reference to transfer_channel_data related to the refer */
59         struct transfer_channel_data *transfer_data;
60         /*! \brief Uniqueid of transferee channel */
61         char *transferee;
62         /*! \brief Non-zero if the 100 notify has been sent */
63         int sent_100;
64         /*! \brief Whether to notifies all the progress details on blind transfer */
65         unsigned int refer_blind_progress;
66 };
67
68 /*! \brief REFER Progress notification structure */
69 struct refer_progress_notification {
70         /*! \brief Refer progress structure to send notification on */
71         struct refer_progress *progress;
72         /*! \brief SIP response code to send */
73         int response;
74         /*! \brief Subscription state */
75         pjsip_evsub_state state;
76 };
77
78 /*! \brief REFER Progress module, used to attach REFER progress structure to subscriptions */
79 static pjsip_module refer_progress_module = {
80         .name = { "REFER Progress", 14 },
81         .id = -1,
82 };
83
84 /*! \brief Destructor for REFER Progress notification structure */
85 static void refer_progress_notification_destroy(void *obj)
86 {
87         struct refer_progress_notification *notification = obj;
88
89         ao2_cleanup(notification->progress);
90 }
91
92 /*! \brief Allocator for REFER Progress notification structure */
93 static struct refer_progress_notification *refer_progress_notification_alloc(struct refer_progress *progress, int response,
94         pjsip_evsub_state state)
95 {
96         struct refer_progress_notification *notification = ao2_alloc(sizeof(*notification), refer_progress_notification_destroy);
97
98         if (!notification) {
99                 return NULL;
100         }
101
102         ao2_ref(progress, +1);
103         notification->progress = progress;
104         notification->response = response;
105         notification->state = state;
106
107         return notification;
108 }
109
110 /*! \brief Serialized callback for subscription notification */
111 static int refer_progress_notify(void *data)
112 {
113         RAII_VAR(struct refer_progress_notification *, notification, data, ao2_cleanup);
114         pjsip_evsub *sub;
115         pjsip_tx_data *tdata;
116
117         /* If the subscription has already been terminated we can't send a notification */
118         if (!(sub = notification->progress->sub)) {
119                 ast_debug(3, "Not sending NOTIFY of response '%d' and state '%u' on progress monitor '%p' as subscription has been terminated\n",
120                         notification->response, notification->state, notification->progress);
121                 return 0;
122         }
123
124         /* If the subscription is being terminated we want to actually remove the progress structure here to
125          * stop a deadlock from occurring - basically terminated changes the state which queues a synchronous task
126          * but we are already running a task... thus it would deadlock */
127         if (notification->state == PJSIP_EVSUB_STATE_TERMINATED) {
128                 ast_debug(3, "Subscription '%p' is being terminated as a result of a NOTIFY, removing REFER progress structure early on progress monitor '%p'\n",
129                         notification->progress->sub, notification->progress);
130                 pjsip_dlg_inc_lock(notification->progress->dlg);
131                 pjsip_evsub_set_mod_data(notification->progress->sub, refer_progress_module.id, NULL);
132                 pjsip_dlg_dec_lock(notification->progress->dlg);
133
134                 /* This is for dropping the reference on the subscription */
135                 ao2_cleanup(notification->progress);
136
137                 notification->progress->sub = NULL;
138         }
139
140         /* Send a deferred initial 100 Trying SIP frag NOTIFY if we haven't already. */
141         if (!notification->progress->sent_100) {
142                 notification->progress->sent_100 = 1;
143                 if (notification->response != 100) {
144                         ast_debug(3, "Sending initial 100 Trying NOTIFY for progress monitor '%p'\n",
145                                 notification->progress);
146                         if (pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_ACTIVE, 100, NULL, &tdata) == PJ_SUCCESS) {
147                                 pjsip_xfer_send_request(sub, tdata);
148                         }
149                 }
150         }
151
152         ast_debug(3, "Sending NOTIFY with response '%d' and state '%u' on subscription '%p' and progress monitor '%p'\n",
153                 notification->response, notification->state, sub, notification->progress);
154
155         /* Actually send the notification */
156         if (pjsip_xfer_notify(sub, notification->state, notification->response, NULL, &tdata) == PJ_SUCCESS) {
157                 pjsip_xfer_send_request(sub, tdata);
158         }
159
160         return 0;
161 }
162
163 static void refer_progress_bridge(void *data, struct stasis_subscription *sub,
164                 struct stasis_message *message)
165 {
166         struct refer_progress *progress = data;
167         struct ast_bridge_blob *enter_blob;
168         struct refer_progress_notification *notification;
169         struct ast_channel *chan;
170
171         if (stasis_subscription_final_message(sub, message)) {
172                 ao2_ref(progress, -1);
173                 return;
174         }
175
176         if (ast_channel_entered_bridge_type() != stasis_message_type(message)) {
177                 /* Don't care */
178                 return;
179         }
180
181         enter_blob = stasis_message_data(message);
182         if (strcmp(enter_blob->channel->base->uniqueid, progress->transferee)) {
183                 /* Don't care */
184                 return;
185         }
186
187         if (!progress->transfer_data->completed) {
188                 /* We can't act on this message because the transfer_channel_data doesn't show that
189                  * the transfer is ready to progress */
190                 return;
191         }
192
193         /* OMG the transferee is joining a bridge. His call got answered! */
194         notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
195         if (notification) {
196                 if (ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
197                         ao2_cleanup(notification);
198                 }
199                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
200         }
201
202         chan = ast_channel_get_by_name(progress->transferee);
203         if (!chan) {
204                 /* The channel is already gone */
205                 return;
206         }
207
208         ast_channel_lock(chan);
209         ast_debug(3, "Detaching REFER progress monitoring hook from '%s' as it has joined a bridge\n",
210                 ast_channel_name(chan));
211         ast_framehook_detach(chan, progress->framehook);
212         ast_channel_unlock(chan);
213
214         ast_channel_unref(chan);
215 }
216
217 /*! \brief Progress monitoring frame hook - examines frames to determine state of transfer */
218 static struct ast_frame *refer_progress_framehook(struct ast_channel *chan, struct ast_frame *f, enum ast_framehook_event event, void *data)
219 {
220         struct refer_progress *progress = data;
221         struct refer_progress_notification *notification = NULL;
222
223         /* We only care about frames *to* the channel */
224         if (!f || (event != AST_FRAMEHOOK_EVENT_WRITE)) {
225                 return f;
226         }
227
228         /* If the completed flag hasn't been raised, skip this pass. */
229         if (!progress->transfer_data->completed) {
230                 return f;
231         }
232
233         /* Determine the state of the REFER based on the control frames (or voice frames) passing */
234         if (f->frametype == AST_FRAME_VOICE && !progress->subclass) {
235                 /* Media is passing without progress, this means the call has been answered */
236                 notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
237         } else if (f->frametype == AST_FRAME_CONTROL) {
238                 /* Based on the control frame being written we can send a NOTIFY advising of the progress */
239                 if ((f->subclass.integer == AST_CONTROL_RING) || (f->subclass.integer == AST_CONTROL_RINGING)) {
240                         progress->subclass = f->subclass.integer;
241                         notification = refer_progress_notification_alloc(progress, 180, PJSIP_EVSUB_STATE_ACTIVE);
242                 } else if (f->subclass.integer == AST_CONTROL_BUSY) {
243                         progress->subclass = f->subclass.integer;
244                         notification = refer_progress_notification_alloc(progress, 486, PJSIP_EVSUB_STATE_TERMINATED);
245                 } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
246                         progress->subclass = f->subclass.integer;
247                         notification = refer_progress_notification_alloc(progress, 503, PJSIP_EVSUB_STATE_TERMINATED);
248                 } else if (f->subclass.integer == AST_CONTROL_PROGRESS) {
249                         progress->subclass = f->subclass.integer;
250                         notification = refer_progress_notification_alloc(progress, 183, PJSIP_EVSUB_STATE_ACTIVE);
251                 } else if (f->subclass.integer == AST_CONTROL_PROCEEDING) {
252                         progress->subclass = f->subclass.integer;
253                         notification = refer_progress_notification_alloc(progress, 100, PJSIP_EVSUB_STATE_ACTIVE);
254                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
255                         progress->subclass = f->subclass.integer;
256                         notification = refer_progress_notification_alloc(progress, 200, PJSIP_EVSUB_STATE_TERMINATED);
257                 }
258         }
259
260         /* If a notification is due to be sent push it to the thread pool */
261         if (notification) {
262                 /* If the subscription is being terminated we don't need the frame hook any longer */
263                 if (notification->state == PJSIP_EVSUB_STATE_TERMINATED) {
264                         ast_debug(3, "Detaching REFER progress monitoring hook from '%s' as subscription is being terminated\n",
265                                 ast_channel_name(chan));
266                         ast_framehook_detach(chan, progress->framehook);
267                 }
268
269                 if (ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
270                         ao2_cleanup(notification);
271                 }
272         }
273
274         return f;
275 }
276
277 /*! \brief Destroy callback for monitoring framehook */
278 static void refer_progress_framehook_destroy(void *data)
279 {
280         struct refer_progress *progress = data;
281         struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, 503, PJSIP_EVSUB_STATE_TERMINATED);
282
283         if (notification && ast_sip_push_task(progress->serializer, refer_progress_notify, notification)) {
284                 ao2_cleanup(notification);
285         }
286
287         if (progress->bridge_sub) {
288                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
289         }
290
291         ao2_cleanup(progress);
292 }
293
294 /*! \brief Serialized callback for subscription termination */
295 static int refer_progress_terminate(void *data)
296 {
297         struct refer_progress *progress = data;
298
299         /* The subscription is no longer valid */
300         progress->sub = NULL;
301
302         return 0;
303 }
304
305 /*! \brief Callback for REFER subscription state changes */
306 static void refer_progress_on_evsub_state(pjsip_evsub *sub, pjsip_event *event)
307 {
308         struct refer_progress *progress = pjsip_evsub_get_mod_data(sub, refer_progress_module.id);
309
310         /* If being destroyed queue it up to the serializer */
311         if (progress && (pjsip_evsub_get_state(sub) == PJSIP_EVSUB_STATE_TERMINATED)) {
312                 /* To prevent a deadlock race condition we unlock the dialog so other serialized tasks can execute */
313                 ast_debug(3, "Subscription '%p' has been remotely terminated, waiting for other tasks to complete on progress monitor '%p'\n",
314                         sub, progress);
315
316                 /* It's possible that a task is waiting to remove us already, so bump the refcount of progress so it doesn't get destroyed */
317                 ao2_ref(progress, +1);
318                 pjsip_dlg_dec_lock(progress->dlg);
319                 /*
320                  * XXX We are always going to execute this inline rather than
321                  * in the serializer because this function is a PJPROJECT
322                  * callback and thus has to be a SIP servant thread.
323                  *
324                  * The likely remedy is to push most of this function into
325                  * refer_progress_terminate() with ast_sip_push_task().
326                  */
327                 ast_sip_push_task_wait_servant(progress->serializer, refer_progress_terminate, progress);
328                 pjsip_dlg_inc_lock(progress->dlg);
329                 ao2_ref(progress, -1);
330
331                 ast_debug(3, "Subscription '%p' removed from progress monitor '%p'\n", sub, progress);
332
333                 /* Since it was unlocked it is possible for this to have been removed already, so check again */
334                 if (pjsip_evsub_get_mod_data(sub, refer_progress_module.id)) {
335                         pjsip_evsub_set_mod_data(sub, refer_progress_module.id, NULL);
336                         ao2_cleanup(progress);
337                 }
338         }
339 }
340
341 /*! \brief Callback structure for subscription */
342 static pjsip_evsub_user refer_progress_evsub_cb = {
343         .on_evsub_state = refer_progress_on_evsub_state,
344 };
345
346 /*! \brief Destructor for REFER progress sutrcture */
347 static void refer_progress_destroy(void *obj)
348 {
349         struct refer_progress *progress = obj;
350
351         if (progress->bridge_sub) {
352                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
353         }
354
355         ao2_cleanup(progress->transfer_data);
356
357         ast_free(progress->transferee);
358         ast_taskprocessor_unreference(progress->serializer);
359 }
360
361 /*! \brief Internal helper function which sets up a refer progress structure if needed */
362 static int refer_progress_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata, struct refer_progress **progress)
363 {
364         const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
365         pjsip_generic_string_hdr *refer_sub = NULL;
366         const pj_str_t str_true = { "true", 4 };
367         pjsip_hdr hdr_list;
368         char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
369
370         *progress = NULL;
371
372         /* Grab the optional Refer-Sub header, it can be used to suppress the implicit subscription */
373         refer_sub = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL);
374         if ((refer_sub && pj_strnicmp(&refer_sub->hvalue, &str_true, 4))) {
375                 return 0;
376         }
377
378         if (!(*progress = ao2_alloc(sizeof(struct refer_progress), refer_progress_destroy))) {
379                 return -1;
380         }
381
382         ast_debug(3, "Created progress monitor '%p' for transfer occurring from channel '%s' and endpoint '%s'\n",
383                 progress, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
384
385         (*progress)->refer_blind_progress = session->endpoint->refer_blind_progress;
386
387         (*progress)->framehook = -1;
388
389         /* To prevent a potential deadlock we need the dialog so we can lock/unlock */
390         (*progress)->dlg = session->inv_session->dlg;
391
392         /* Create name with seq number appended. */
393         ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/refer/%s",
394                 ast_sorcery_object_get_id(session->endpoint));
395
396         if (!((*progress)->serializer = ast_sip_create_serializer(tps_name))) {
397                 goto error;
398         }
399
400         /* Create the implicit subscription for monitoring of this transfer */
401         if (pjsip_xfer_create_uas(session->inv_session->dlg, &refer_progress_evsub_cb, rdata, &(*progress)->sub) != PJ_SUCCESS) {
402                 goto error;
403         }
404
405         /* Associate the REFER progress structure with the subscription */
406         ao2_ref(*progress, +1);
407         pjsip_evsub_set_mod_data((*progress)->sub, refer_progress_module.id, *progress);
408
409         pj_list_init(&hdr_list);
410         if (refer_sub) {
411                 pjsip_hdr *hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(session->inv_session->dlg->pool, &str_refer_sub, &str_true);
412
413                 pj_list_push_back(&hdr_list, hdr);
414         }
415
416         /* Accept the REFER request */
417         ast_debug(3, "Accepting REFER request for progress monitor '%p'\n", *progress);
418         pjsip_xfer_accept((*progress)->sub, rdata, 202, &hdr_list);
419
420         return 0;
421
422 error:
423         ao2_cleanup(*progress);
424         *progress = NULL;
425         return -1;
426 }
427
428 /*! \brief Structure for attended transfer task */
429 struct refer_attended {
430         /*! \brief Transferer session */
431         struct ast_sip_session *transferer;
432         /*! \brief Transferer channel */
433         struct ast_channel *transferer_chan;
434         /*! \brief Second transferer session */
435         struct ast_sip_session *transferer_second;
436         /*! \brief Optional refer progress structure */
437         struct refer_progress *progress;
438 };
439
440 /*! \brief Destructor for attended transfer task */
441 static void refer_attended_destroy(void *obj)
442 {
443         struct refer_attended *attended = obj;
444
445         ao2_cleanup(attended->transferer);
446         ast_channel_cleanup(attended->transferer_chan);
447         ao2_cleanup(attended->transferer_second);
448         ao2_cleanup(attended->progress);
449 }
450
451 /*! \brief Allocator for attended transfer task */
452 static struct refer_attended *refer_attended_alloc(struct ast_sip_session *transferer,
453         struct ast_sip_session *transferer_second,
454         struct refer_progress *progress)
455 {
456         struct refer_attended *attended;
457
458         attended = ao2_alloc_options(sizeof(*attended), refer_attended_destroy,
459                 AO2_ALLOC_OPT_LOCK_NOLOCK);
460         if (!attended) {
461                 return NULL;
462         }
463
464         ao2_ref(transferer, +1);
465         attended->transferer = transferer;
466         ast_channel_ref(transferer->channel);
467         attended->transferer_chan = transferer->channel;
468         ao2_ref(transferer_second, +1);
469         attended->transferer_second = transferer_second;
470
471         if (progress) {
472                 ao2_ref(progress, +1);
473                 attended->progress = progress;
474         }
475
476         return attended;
477 }
478
479 static int session_end_if_deferred_task(void *data)
480 {
481         struct ast_sip_session *session = data;
482
483         ast_sip_session_end_if_deferred(session);
484         ao2_ref(session, -1);
485         return 0;
486 }
487
488 static int defer_termination_cancel_task(void *data)
489 {
490         struct ast_sip_session *session = data;
491
492         ast_sip_session_end_if_deferred(session);
493         ast_sip_session_defer_termination_cancel(session);
494         ao2_ref(session, -1);
495         return 0;
496 }
497
498 /*!
499  * \internal
500  * \brief Convert transfer enum to SIP response code.
501  * \since 13.3.0
502  *
503  * \param xfer_code Core transfer function enum result.
504  *
505  * \return SIP response code
506  */
507 static int xfer_response_code2sip(enum ast_transfer_result xfer_code)
508 {
509         int response;
510
511         response = 503;
512         switch (xfer_code) {
513         case AST_BRIDGE_TRANSFER_INVALID:
514                 response = 400;
515                 break;
516         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
517                 response = 403;
518                 break;
519         case AST_BRIDGE_TRANSFER_FAIL:
520                 response = 500;
521                 break;
522         case AST_BRIDGE_TRANSFER_SUCCESS:
523                 response = 200;
524                 break;
525         }
526         return response;
527 }
528
529 /*! \brief Task for attended transfer executed by attended->transferer_second serializer */
530 static int refer_attended_task(void *data)
531 {
532         struct refer_attended *attended = data;
533         int response;
534         int (*task_cb)(void *data);
535
536         if (attended->transferer_second->channel) {
537                 ast_debug(3, "Performing a REFER attended transfer - Transferer #1: %s Transferer #2: %s\n",
538                         ast_channel_name(attended->transferer_chan),
539                         ast_channel_name(attended->transferer_second->channel));
540
541                 response = xfer_response_code2sip(ast_bridge_transfer_attended(
542                         attended->transferer_chan,
543                         attended->transferer_second->channel));
544
545                 ast_debug(3, "Final response for REFER attended transfer - Transferer #1: %s Transferer #2: %s is '%d'\n",
546                         ast_channel_name(attended->transferer_chan),
547                         ast_channel_name(attended->transferer_second->channel),
548                         response);
549         } else {
550                 ast_debug(3, "Received REFER request on channel '%s' but other channel has gone.\n",
551                         ast_channel_name(attended->transferer_chan));
552                 response = 603;
553         }
554
555         if (attended->progress) {
556                 struct refer_progress_notification *notification;
557
558                 notification = refer_progress_notification_alloc(attended->progress, response,
559                         PJSIP_EVSUB_STATE_TERMINATED);
560                 if (notification) {
561                         refer_progress_notify(notification);
562                 }
563         }
564
565         if (response == 200) {
566                 task_cb = session_end_if_deferred_task;
567         } else {
568                 task_cb = defer_termination_cancel_task;
569         }
570         if (!ast_sip_push_task(attended->transferer->serializer,
571                 task_cb, attended->transferer)) {
572                 /* Gave the ref to the pushed task. */
573                 attended->transferer = NULL;
574         } else {
575                 /* Do this anyway even though it is the wrong serializer. */
576                 ast_sip_session_end_if_deferred(attended->transferer);
577         }
578
579         ao2_ref(attended, -1);
580         return 0;
581 }
582
583 /*! \brief Structure for blind transfer callback details */
584 struct refer_blind {
585         /*! \brief Context being used for transfer */
586         const char *context;
587         /*! \brief Optional progress structure */
588         struct refer_progress *progress;
589         /*! \brief REFER message */
590         pjsip_rx_data *rdata;
591         /*! \brief Optional Replaces header */
592         pjsip_replaces_hdr *replaces;
593         /*! \brief Optional Refer-To header */
594         pjsip_sip_uri *refer_to;
595         /*! \brief Attended transfer flag */
596         unsigned int attended:1;
597 };
598
599 /*! \brief Blind transfer callback function */
600 static void refer_blind_callback(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
601         enum ast_transfer_type transfer_type)
602 {
603         struct refer_blind *refer = user_data_wrapper->data;
604         pjsip_generic_string_hdr *referred_by;
605
606         static const pj_str_t str_referred_by = { "Referred-By", 11 };
607         static const pj_str_t str_referred_by_s = { "b", 1 };
608
609         pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
610
611         if (refer->progress && !refer->attended && !refer->progress->refer_blind_progress) {
612                 /* If blind transfer and endpoint doesn't want to receive all the progress details */
613                 struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
614                         PJSIP_EVSUB_STATE_TERMINATED);
615
616                 if (notification) {
617                         refer_progress_notify(notification);
618                 }
619         } else if (refer->progress) {
620                 /* If attended transfer and progress monitoring is being done attach a frame hook so we can monitor it */
621                 struct ast_framehook_interface hook = {
622                         .version = AST_FRAMEHOOK_INTERFACE_VERSION,
623                         .event_cb = refer_progress_framehook,
624                         .destroy_cb = refer_progress_framehook_destroy,
625                         .data = refer->progress,
626                         .disable_inheritance = 1,
627                 };
628
629                 refer->progress->transferee = ast_strdup(ast_channel_uniqueid(chan));
630                 if (!refer->progress->transferee) {
631                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
632                                 PJSIP_EVSUB_STATE_TERMINATED);
633
634                         ast_log(LOG_WARNING, "Could not copy channel name '%s' during transfer - assuming success\n",
635                                 ast_channel_name(chan));
636
637                         if (notification) {
638                                 refer_progress_notify(notification);
639                         }
640                 }
641
642                 /* Progress needs a reference to the transfer_channel_data so that it can track the completed status of the transfer */
643                 ao2_ref(user_data_wrapper, +1);
644                 refer->progress->transfer_data = user_data_wrapper;
645
646                 /* We need to bump the reference count up on the progress structure since it is in the frame hook now */
647                 ao2_ref(refer->progress, +1);
648
649                 /* If we can't attach a frame hook for whatever reason send a notification of success immediately */
650                 ast_channel_lock(chan);
651                 refer->progress->framehook = ast_framehook_attach(chan, &hook);
652                 ast_channel_unlock(chan);
653                 if (refer->progress->framehook < 0) {
654                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
655                                 PJSIP_EVSUB_STATE_TERMINATED);
656
657                         ast_log(LOG_WARNING, "Could not attach REFER transfer progress monitoring hook to channel '%s' - assuming success\n",
658                                 ast_channel_name(chan));
659
660                         if (notification) {
661                                 refer_progress_notify(notification);
662                         }
663
664                         ao2_cleanup(refer->progress);
665                 }
666
667                 /* We need to bump the reference count for the stasis subscription */
668                 ao2_ref(refer->progress, +1);
669                 /* We also will need to detect if the transferee enters a bridge. This is currently the only reliable way to
670                  * detect if the transfer target has answered the call
671                  */
672                 refer->progress->bridge_sub = stasis_subscribe_pool(ast_bridge_topic_all(), refer_progress_bridge, refer->progress);
673                 if (!refer->progress->bridge_sub) {
674                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
675                                 PJSIP_EVSUB_STATE_TERMINATED);
676
677                         ast_log(LOG_WARNING, "Could not create bridge stasis subscription for monitoring progress on transfer of channel '%s' - assuming success\n",
678                                         ast_channel_name(chan));
679
680                         if (notification) {
681                                 refer_progress_notify(notification);
682                         }
683
684                         ast_channel_lock(chan);
685                         ast_framehook_detach(chan, refer->progress->framehook);
686                         ast_channel_unlock(chan);
687
688                         ao2_cleanup(refer->progress);
689                 } else {
690                         stasis_subscription_accept_message_type(refer->progress->bridge_sub, ast_channel_entered_bridge_type());
691                         stasis_subscription_accept_message_type(refer->progress->bridge_sub, stasis_subscription_change_type());
692                         stasis_subscription_set_filter(refer->progress->bridge_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
693                 }
694         }
695
696         pbx_builtin_setvar_helper(chan, "SIPREFERRINGCONTEXT", S_OR(refer->context, NULL));
697
698         referred_by = pjsip_msg_find_hdr_by_names(refer->rdata->msg_info.msg,
699                 &str_referred_by, &str_referred_by_s, NULL);
700         if (referred_by) {
701                 size_t uri_size = pj_strlen(&referred_by->hvalue) + 1;
702                 char *uri = ast_alloca(uri_size);
703
704                 ast_copy_pj_str(uri, &referred_by->hvalue, uri_size);
705                 pbx_builtin_setvar_helper(chan, "__SIPREFERREDBYHDR", S_OR(uri, NULL));
706         } else {
707                 pbx_builtin_setvar_helper(chan, "SIPREFERREDBYHDR", NULL);
708         }
709
710         if (refer->replaces) {
711                 char replaces[512];
712                 char *replaces_val = NULL;
713                 int len;
714
715                 len = pjsip_hdr_print_on(refer->replaces, replaces, sizeof(replaces) - 1);
716                 if (len != -1) {
717                         /* pjsip_hdr_print_on does not NULL terminate the buffer */
718                         replaces[len] = '\0';
719                         replaces_val = replaces + sizeof("Replaces:");
720                 }
721                 pbx_builtin_setvar_helper(chan, "__SIPREPLACESHDR", replaces_val);
722         } else {
723                 pbx_builtin_setvar_helper(chan, "SIPREPLACESHDR", NULL);
724         }
725
726         if (refer->refer_to) {
727                 char refer_to[PJSIP_MAX_URL_SIZE];
728
729                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, refer->refer_to, refer_to, sizeof(refer_to));
730                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", S_OR(refer_to, NULL));
731         } else {
732                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", NULL);
733         }
734 }
735
736 /*!
737  * \internal
738  * \brief Set the passed in context variable to the determined transfer context.
739  * \since 13.3.0
740  *
741  * \param context Set to the determined transfer context.
742  * \param session INVITE dialog SIP session.
743  */
744 #define DETERMINE_TRANSFER_CONTEXT(context, session)                                                                    \
745         do {                                                                                                                                                            \
746                 ast_channel_lock((session)->channel);                                                                                   \
747                 context = pbx_builtin_getvar_helper((session)->channel, "TRANSFER_CONTEXT");    \
748                 if (ast_strlen_zero(context)) {                                                                                                 \
749                         context = (session)->endpoint->context;                                                                         \
750                 } else {                                                                                                                                                \
751                         context = ast_strdupa(context);                                                                                         \
752                 }                                                                                                                                                               \
753                 ast_channel_unlock((session)->channel);                                                                                 \
754         } while (0)                                                                                                                                                     \
755
756 static int refer_incoming_attended_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target_uri,
757         pjsip_param *replaces_param, struct refer_progress *progress)
758 {
759         const pj_str_t str_replaces = { "Replaces", 8 };
760         pj_str_t replaces_content;
761         pjsip_replaces_hdr *replaces;
762         int parsed_len;
763         pjsip_dialog *dlg;
764
765         pj_strdup_with_null(rdata->tp_info.pool, &replaces_content, &replaces_param->value);
766
767         /* Parsing the parameter as a Replaces header easily grabs the needed information */
768         if (!(replaces = pjsip_parse_hdr(rdata->tp_info.pool, &str_replaces, replaces_content.ptr,
769                 pj_strlen(&replaces_content), &parsed_len))) {
770                 ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' with invalid Replaces header, rejecting\n",
771                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
772                 return 400;
773         }
774
775         /* See if the dialog is local, or remote */
776         if ((dlg = pjsip_ua_find_dialog(&replaces->call_id, &replaces->to_tag, &replaces->from_tag, PJ_TRUE))) {
777                 RAII_VAR(struct ast_sip_session *, other_session, ast_sip_dialog_get_session(dlg), ao2_cleanup);
778                 struct refer_attended *attended;
779
780                 pjsip_dlg_dec_lock(dlg);
781
782                 if (!other_session) {
783                         ast_debug(3, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but no session exists on it\n",
784                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
785                         return 603;
786                 }
787
788                 /* We defer actually doing the attended transfer to the other session so no deadlock can occur */
789                 if (!(attended = refer_attended_alloc(session, other_session, progress))) {
790                         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",
791                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
792                         return 500;
793                 }
794
795                 if (ast_sip_session_defer_termination(session)) {
796                         ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but could not defer termination, rejecting\n",
797                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
798                         ao2_cleanup(attended);
799                         return 500;
800                 }
801
802                 /* Push it to the other session, which will have both channels with minimal locking */
803                 if (ast_sip_push_task(other_session->serializer, refer_attended_task, attended)) {
804                         ast_sip_session_end_if_deferred(session);
805                         ast_sip_session_defer_termination_cancel(session);
806                         ao2_cleanup(attended);
807                         return 500;
808                 }
809
810                 ast_debug(3, "Attended transfer from '%s' pushed to second channel serializer\n",
811                         ast_channel_name(session->channel));
812
813                 return 200;
814         } else {
815                 const char *context;
816                 struct refer_blind refer = { 0, };
817                 int response;
818
819                 DETERMINE_TRANSFER_CONTEXT(context, session);
820
821                 if (!ast_exists_extension(NULL, context, "external_replaces", 1, NULL)) {
822                         ast_log(LOG_ERROR, "Received REFER for remote session on channel '%s' from endpoint '%s' but 'external_replaces' extension not found in context %s\n",
823                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
824                         return 404;
825                 }
826
827                 refer.context = context;
828                 refer.progress = progress;
829                 refer.rdata = rdata;
830                 refer.replaces = replaces;
831                 refer.refer_to = target_uri;
832                 refer.attended = 1;
833
834                 if (ast_sip_session_defer_termination(session)) {
835                         ast_log(LOG_ERROR, "Received REFER for remote session on channel '%s' from endpoint '%s' but could not defer termination, rejecting\n",
836                                 ast_channel_name(session->channel),
837                                 ast_sorcery_object_get_id(session->endpoint));
838                         return 500;
839                 }
840
841                 response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
842                         "external_replaces", context, refer_blind_callback, &refer));
843
844                 ast_sip_session_end_if_deferred(session);
845                 if (response != 200) {
846                         ast_sip_session_defer_termination_cancel(session);
847                 }
848
849                 return response;
850         }
851 }
852
853 static int refer_incoming_blind_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target,
854         struct refer_progress *progress)
855 {
856         const char *context;
857         char exten[AST_MAX_EXTENSION];
858         struct refer_blind refer = { 0, };
859         int response;
860
861         /* If no explicit transfer context has been provided use their configured context */
862         DETERMINE_TRANSFER_CONTEXT(context, session);
863
864         /* Using the user portion of the target URI see if it exists as a valid extension in their context */
865         ast_copy_pj_str(exten, &target->user, sizeof(exten));
866
867         /*
868          * We may want to match in the dialplan without any user
869          * options getting in the way.
870          */
871         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(exten);
872
873         /* Uri without exten */
874         if (ast_strlen_zero(exten)) {
875                 ast_copy_string(exten, "s", sizeof(exten));
876                 ast_debug(3, "Channel '%s' from endpoint '%s' attempted blind transfer to a target without extension. Target was set to 's@%s'\n",
877                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
878         }
879
880         if (!ast_exists_extension(NULL, context, exten, 1, NULL)) {
881                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer to '%s@%s' but target does not exist\n",
882                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), exten, context);
883                 return 404;
884         }
885
886         refer.context = context;
887         refer.progress = progress;
888         refer.rdata = rdata;
889         refer.refer_to = target;
890         refer.attended = 0;
891
892         if (ast_sip_session_defer_termination(session)) {
893                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer but could not defer termination, rejecting\n",
894                         ast_channel_name(session->channel),
895                         ast_sorcery_object_get_id(session->endpoint));
896                 return 500;
897         }
898
899         response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
900                 exten, context, refer_blind_callback, &refer));
901
902         ast_sip_session_end_if_deferred(session);
903         if (response != 200) {
904                 ast_sip_session_defer_termination_cancel(session);
905         }
906
907         return response;
908 }
909
910 /*! \brief Structure used to retrieve channel from another session */
911 struct invite_replaces {
912         /*! \brief Session we want the channel from */
913         struct ast_sip_session *session;
914         /*! \brief Channel from the session (with reference) */
915         struct ast_channel *channel;
916         /*! \brief Bridge the channel is in */
917         struct ast_bridge *bridge;
918 };
919
920 /*! \brief Task for invite replaces */
921 static int invite_replaces(void *data)
922 {
923         struct invite_replaces *invite = data;
924
925         if (!invite->session->channel) {
926                 return -1;
927         }
928
929         ast_channel_ref(invite->session->channel);
930         invite->channel = invite->session->channel;
931
932         invite->bridge = ast_bridge_transfer_acquire_bridge(invite->channel);
933         return 0;
934 }
935
936 static int refer_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
937 {
938         pjsip_dialog *other_dlg = NULL;
939         pjsip_tx_data *packet;
940         int response = 0;
941         RAII_VAR(struct ast_sip_session *, other_session, NULL, ao2_cleanup);
942         struct invite_replaces invite;
943
944         /* If a Replaces header is present make sure it is valid */
945         if (pjsip_replaces_verify_request(rdata, &other_dlg, PJ_TRUE, &packet) != PJ_SUCCESS) {
946                 response = packet->msg->line.status.code;
947                 ast_assert(response != 0);
948                 pjsip_tx_data_dec_ref(packet);
949                 goto inv_replace_failed;
950         }
951
952         /* If no other dialog exists then this INVITE request does not have a Replaces header */
953         if (!other_dlg) {
954                 return 0;
955         }
956
957         other_session = ast_sip_dialog_get_session(other_dlg);
958         pjsip_dlg_dec_lock(other_dlg);
959
960         /* Don't accept an in-dialog INVITE with Replaces as it does not make much sense */
961         if (session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
962                 response = 488;
963                 goto inv_replace_failed;
964         }
965
966         if (!other_session) {
967                 ast_debug(3, "INVITE with Replaces received on channel '%s' from endpoint '%s', but requested session does not exist\n",
968                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
969                 response = 481;
970                 goto inv_replace_failed;
971         }
972
973         invite.session = other_session;
974
975         if (ast_sip_push_task_wait_serializer(other_session->serializer, invite_replaces,
976                 &invite)) {
977                 response = 481;
978                 goto inv_replace_failed;
979         }
980
981         ast_channel_lock(session->channel);
982         ast_setstate(session->channel, AST_STATE_RING);
983         ast_channel_unlock(session->channel);
984         ast_raw_answer(session->channel);
985
986         ast_debug(3, "INVITE with Replaces being attempted.  '%s' --> '%s'\n",
987                 ast_channel_name(session->channel), ast_channel_name(invite.channel));
988
989         if (!invite.bridge) {
990                 struct ast_channel *chan = session->channel;
991
992                 /*
993                  * This will use a synchronous task but we aren't operating in
994                  * the serializer at this point in time, so it won't deadlock.
995                  */
996                 if (!ast_channel_move(invite.channel, chan)) {
997                         /*
998                          * We can't directly use session->channel because ast_channel_move()
999                          * does a masquerade which changes session->channel to a different
1000                          * channel.  To ensure we work on the right channel we store a
1001                          * pointer locally before we begin so it remains valid.
1002                          */
1003                         ast_hangup(chan);
1004                 } else {
1005                         response = AST_CAUSE_FAILURE;
1006                 }
1007         } else {
1008                 if (ast_bridge_impart(invite.bridge, session->channel, invite.channel, NULL,
1009                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
1010                         response = AST_CAUSE_FAILURE;
1011                 }
1012         }
1013
1014         ast_channel_unref(invite.channel);
1015         ao2_cleanup(invite.bridge);
1016
1017         if (!response) {
1018                 /*
1019                  * On success we cannot use session->channel in the debug message.
1020                  * This thread either no longer has a ref to session->channel or
1021                  * session->channel is no longer the original channel.
1022                  */
1023                 ast_debug(3, "INVITE with Replaces successfully completed.\n");
1024         } else {
1025                 ast_debug(3, "INVITE with Replaces failed on channel '%s', hanging up with cause '%d'\n",
1026                         ast_channel_name(session->channel), response);
1027                 ast_channel_lock(session->channel);
1028                 ast_channel_hangupcause_set(session->channel, response);
1029                 ast_channel_unlock(session->channel);
1030                 ast_hangup(session->channel);
1031         }
1032
1033         return 1;
1034
1035 inv_replace_failed:
1036         if (session->inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1037                 ast_debug(3, "INVITE with Replaces failed on channel '%s', sending response of '%d'\n",
1038                         ast_channel_name(session->channel), response);
1039                 session->defer_terminate = 1;
1040                 ast_hangup(session->channel);
1041
1042                 if (pjsip_inv_end_session(session->inv_session, response, NULL, &packet) == PJ_SUCCESS
1043                         && packet) {
1044                         ast_sip_session_send_response(session, packet);
1045                 }
1046         } else {
1047                 ast_debug(3, "INVITE with Replaces in-dialog on channel '%s', hanging up\n",
1048                         ast_channel_name(session->channel));
1049                 ast_queue_hangup(session->channel);
1050         }
1051
1052         return 1;
1053 }
1054
1055 static int refer_incoming_refer_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1056 {
1057         pjsip_generic_string_hdr *refer_to;
1058         char *uri;
1059         size_t uri_size;
1060         pjsip_uri *target;
1061         pjsip_sip_uri *target_uri;
1062         RAII_VAR(struct refer_progress *, progress, NULL, ao2_cleanup);
1063         pjsip_param *replaces;
1064         int response;
1065
1066         static const pj_str_t str_refer_to = { "Refer-To", 8 };
1067         static const pj_str_t str_refer_to_s = { "r", 1 };
1068         static const pj_str_t str_replaces = { "Replaces", 8 };
1069
1070         if (!session->channel) {
1071                 /* No channel to refer.  Likely because the call was just hung up. */
1072                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 404, NULL, NULL, NULL);
1073                 ast_debug(3, "Received a REFER on a session with no channel from endpoint '%s'.\n",
1074                         ast_sorcery_object_get_id(session->endpoint));
1075                 return 0;
1076         }
1077
1078         if (!session->endpoint->allowtransfer) {
1079                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 603, NULL, NULL, NULL);
1080                 ast_log(LOG_WARNING, "Endpoint %s transfer attempt blocked due to configuration\n",
1081                                 ast_sorcery_object_get_id(session->endpoint));
1082                 return 0;
1083         }
1084
1085         /* A Refer-To header is required */
1086         refer_to = pjsip_msg_find_hdr_by_names(rdata->msg_info.msg, &str_refer_to, &str_refer_to_s, NULL);
1087         if (!refer_to) {
1088                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1089                 ast_debug(3, "Received a REFER without Refer-To on channel '%s' from endpoint '%s'\n",
1090                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1091                 return 0;
1092         }
1093
1094         /* The ast_copy_pj_str to uri is needed because it puts the NULL terminator to the uri
1095          * as pjsip_parse_uri require a NULL terminated uri
1096          */
1097
1098         uri_size = pj_strlen(&refer_to->hvalue) + 1;
1099         uri = ast_alloca(uri_size);
1100         ast_copy_pj_str(uri, &refer_to->hvalue, uri_size);
1101
1102         target = pjsip_parse_uri(rdata->tp_info.pool, uri, uri_size - 1, 0);
1103
1104         if (!target
1105                 || (!PJSIP_URI_SCHEME_IS_SIP(target)
1106                         && !PJSIP_URI_SCHEME_IS_SIPS(target))) {
1107
1108                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1109                 ast_debug(3, "Received a REFER without a parseable Refer-To ('%s') on channel '%s' from endpoint '%s'\n",
1110                         uri, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1111                 return 0;
1112         }
1113         target_uri = pjsip_uri_get_uri(target);
1114
1115         /* Set up REFER progress subscription if requested/possible */
1116         if (refer_progress_alloc(session, rdata, &progress)) {
1117                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 500, NULL, NULL, NULL);
1118                 ast_debug(3, "Could not set up subscription for REFER on channel '%s' from endpoint '%s'\n",
1119                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1120                 return 0;
1121         }
1122
1123         /* Determine if this is an attended or blind transfer */
1124         if ((replaces = pjsip_param_find(&target_uri->header_param, &str_replaces)) ||
1125                 (replaces = pjsip_param_find(&target_uri->other_param, &str_replaces))) {
1126                 response = refer_incoming_attended_request(session, rdata, target_uri, replaces, progress);
1127         } else {
1128                 response = refer_incoming_blind_request(session, rdata, target_uri, progress);
1129         }
1130
1131         if (!progress) {
1132                 /* The transferer has requested no subscription, so send a final response immediately */
1133                 pjsip_tx_data *tdata;
1134                 const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
1135                 const pj_str_t str_false = { "false", 5 };
1136                 pjsip_hdr *hdr;
1137
1138                 ast_debug(3, "Progress monitoring not requested for REFER on channel '%s' from endpoint '%s', sending immediate response of '%d'\n",
1139                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), response);
1140
1141                 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, response, NULL, &tdata) != PJ_SUCCESS) {
1142                         pjsip_dlg_respond(session->inv_session->dlg, rdata, response, NULL, NULL, NULL);
1143                         return 0;
1144                 }
1145
1146                 hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub, &str_false);
1147                 pjsip_msg_add_hdr(tdata->msg, hdr);
1148
1149                 pjsip_dlg_send_response(session->inv_session->dlg, pjsip_rdata_get_tsx(rdata), tdata);
1150         } else if (response != 200) {
1151                 /* Since this failed we can send a final NOTIFY now and terminate the subscription */
1152                 struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, response, PJSIP_EVSUB_STATE_TERMINATED);
1153
1154                 if (notification) {
1155                         /* The refer_progress_notify function will call ao2_cleanup on this for us */
1156                         refer_progress_notify(notification);
1157                 }
1158         }
1159
1160         return 0;
1161 }
1162
1163 static int refer_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
1164 {
1165         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_refer_method())) {
1166                 return refer_incoming_refer_request(session, rdata);
1167         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_invite_method)) {
1168                 return refer_incoming_invite_request(session, rdata);
1169         } else {
1170                 return 0;
1171         }
1172 }
1173
1174 /*!
1175  * \brief Use the value of a channel variable as the value of a SIP header
1176  *
1177  * This looks up a variable name on a channel, then takes that value and adds
1178  * it to an outgoing SIP request. If the header already exists on the message,
1179  * then no action is taken.
1180  *
1181  * \pre chan is locked.
1182  *
1183  * \param chan The channel on which to find the variable.
1184  * \param var_name The name of the channel variable to use.
1185  * \param header_name The name of the SIP header to add to the outgoing message.
1186  * \param tdata The outgoing SIP message on which to add the header
1187  */
1188 static void add_header_from_channel_var(struct ast_channel *chan, const char *var_name, const char *header_name, pjsip_tx_data *tdata)
1189 {
1190         const char *var_value;
1191         pj_str_t pj_header_name;
1192         pjsip_hdr *header;
1193
1194         var_value = pbx_builtin_getvar_helper(chan, var_name);
1195         if (ast_strlen_zero(var_value)) {
1196                 return;
1197         }
1198
1199         pj_cstr(&pj_header_name, header_name);
1200         header = pjsip_msg_find_hdr_by_name(tdata->msg, &pj_header_name, NULL);
1201         if (header) {
1202                 return;
1203         }
1204         ast_sip_add_header(tdata, header_name, var_value);
1205 }
1206
1207 static void refer_outgoing_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
1208 {
1209         if (pjsip_method_cmp(&tdata->msg->line.req.method, &pjsip_invite_method)
1210                 || !session->channel
1211                 || session->inv_session->state != PJSIP_INV_STATE_NULL) {
1212                 return;
1213         }
1214
1215         ast_channel_lock(session->channel);
1216         add_header_from_channel_var(session->channel, "SIPREPLACESHDR", "Replaces", tdata);
1217         add_header_from_channel_var(session->channel, "SIPREFERREDBYHDR", "Referred-By", tdata);
1218         ast_channel_unlock(session->channel);
1219 }
1220
1221 static struct ast_sip_session_supplement refer_supplement = {
1222         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
1223         .incoming_request = refer_incoming_request,
1224         .outgoing_request = refer_outgoing_request,
1225 };
1226
1227 static int load_module(void)
1228 {
1229         const pj_str_t str_norefersub = { "norefersub", 10 };
1230
1231         pjsip_replaces_init_module(ast_sip_get_pjsip_endpoint());
1232         pjsip_xfer_init_module(ast_sip_get_pjsip_endpoint());
1233         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_SUPPORTED, NULL, 1, &str_norefersub);
1234
1235         ast_sip_register_service(&refer_progress_module);
1236         ast_sip_session_register_supplement(&refer_supplement);
1237
1238         ast_module_shutdown_ref(ast_module_info->self);
1239
1240         return AST_MODULE_LOAD_SUCCESS;
1241 }
1242
1243 static int unload_module(void)
1244 {
1245         ast_sip_session_unregister_supplement(&refer_supplement);
1246         ast_sip_unregister_service(&refer_progress_module);
1247
1248         return 0;
1249 }
1250
1251 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Blind and Attended Transfer Support",
1252         .support_level = AST_MODULE_SUPPORT_CORE,
1253         .load = load_module,
1254         .unload = unload_module,
1255         .load_pri = AST_MODPRI_APP_DEPEND,
1256         .requires = "res_pjsip,res_pjsip_session,res_pjsip_pubsub",
1257 );