Merge "res_pjsip: New endpoint option "refer_blind_progress""
[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->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                 ast_sip_push_task_synchronous(progress->serializer, refer_progress_terminate, progress);
320                 pjsip_dlg_inc_lock(progress->dlg);
321                 ao2_ref(progress, -1);
322
323                 ast_debug(3, "Subscription '%p' removed from progress monitor '%p'\n", sub, progress);
324
325                 /* Since it was unlocked it is possible for this to have been removed already, so check again */
326                 if (pjsip_evsub_get_mod_data(sub, refer_progress_module.id)) {
327                         pjsip_evsub_set_mod_data(sub, refer_progress_module.id, NULL);
328                         ao2_cleanup(progress);
329                 }
330         }
331 }
332
333 /*! \brief Callback structure for subscription */
334 static pjsip_evsub_user refer_progress_evsub_cb = {
335         .on_evsub_state = refer_progress_on_evsub_state,
336 };
337
338 /*! \brief Destructor for REFER progress sutrcture */
339 static void refer_progress_destroy(void *obj)
340 {
341         struct refer_progress *progress = obj;
342
343         if (progress->bridge_sub) {
344                 progress->bridge_sub = stasis_unsubscribe(progress->bridge_sub);
345         }
346
347         ao2_cleanup(progress->transfer_data);
348
349         ast_free(progress->transferee);
350         ast_taskprocessor_unreference(progress->serializer);
351 }
352
353 /*! \brief Internal helper function which sets up a refer progress structure if needed */
354 static int refer_progress_alloc(struct ast_sip_session *session, pjsip_rx_data *rdata, struct refer_progress **progress)
355 {
356         const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
357         pjsip_generic_string_hdr *refer_sub = NULL;
358         const pj_str_t str_true = { "true", 4 };
359         pjsip_hdr hdr_list;
360         char tps_name[AST_TASKPROCESSOR_MAX_NAME + 1];
361
362         *progress = NULL;
363
364         /* Grab the optional Refer-Sub header, it can be used to suppress the implicit subscription */
365         refer_sub = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_sub, NULL);
366         if ((refer_sub && pj_strnicmp(&refer_sub->hvalue, &str_true, 4))) {
367                 return 0;
368         }
369
370         if (!(*progress = ao2_alloc(sizeof(struct refer_progress), refer_progress_destroy))) {
371                 return -1;
372         }
373
374         ast_debug(3, "Created progress monitor '%p' for transfer occurring from channel '%s' and endpoint '%s'\n",
375                 progress, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
376
377         (*progress)->refer_blind_progress = session->endpoint->refer_blind_progress;
378
379         (*progress)->framehook = -1;
380
381         /* To prevent a potential deadlock we need the dialog so we can lock/unlock */
382         (*progress)->dlg = session->inv_session->dlg;
383
384         /* Create name with seq number appended. */
385         ast_taskprocessor_build_name(tps_name, sizeof(tps_name), "pjsip/refer/%s",
386                 ast_sorcery_object_get_id(session->endpoint));
387
388         if (!((*progress)->serializer = ast_sip_create_serializer(tps_name))) {
389                 goto error;
390         }
391
392         /* Create the implicit subscription for monitoring of this transfer */
393         if (pjsip_xfer_create_uas(session->inv_session->dlg, &refer_progress_evsub_cb, rdata, &(*progress)->sub) != PJ_SUCCESS) {
394                 goto error;
395         }
396
397         /* Associate the REFER progress structure with the subscription */
398         ao2_ref(*progress, +1);
399         pjsip_evsub_set_mod_data((*progress)->sub, refer_progress_module.id, *progress);
400
401         pj_list_init(&hdr_list);
402         if (refer_sub) {
403                 pjsip_hdr *hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(session->inv_session->dlg->pool, &str_refer_sub, &str_true);
404
405                 pj_list_push_back(&hdr_list, hdr);
406         }
407
408         /* Accept the REFER request */
409         ast_debug(3, "Accepting REFER request for progress monitor '%p'\n", *progress);
410         pjsip_xfer_accept((*progress)->sub, rdata, 202, &hdr_list);
411
412         return 0;
413
414 error:
415         ao2_cleanup(*progress);
416         *progress = NULL;
417         return -1;
418 }
419
420 /*! \brief Structure for attended transfer task */
421 struct refer_attended {
422         /*! \brief Transferer session */
423         struct ast_sip_session *transferer;
424         /*! \brief Transferer channel */
425         struct ast_channel *transferer_chan;
426         /*! \brief Second transferer session */
427         struct ast_sip_session *transferer_second;
428         /*! \brief Optional refer progress structure */
429         struct refer_progress *progress;
430 };
431
432 /*! \brief Destructor for attended transfer task */
433 static void refer_attended_destroy(void *obj)
434 {
435         struct refer_attended *attended = obj;
436
437         ao2_cleanup(attended->transferer);
438         ast_channel_cleanup(attended->transferer_chan);
439         ao2_cleanup(attended->transferer_second);
440         ao2_cleanup(attended->progress);
441 }
442
443 /*! \brief Allocator for attended transfer task */
444 static struct refer_attended *refer_attended_alloc(struct ast_sip_session *transferer,
445         struct ast_sip_session *transferer_second,
446         struct refer_progress *progress)
447 {
448         struct refer_attended *attended;
449
450         attended = ao2_alloc_options(sizeof(*attended), refer_attended_destroy,
451                 AO2_ALLOC_OPT_LOCK_NOLOCK);
452         if (!attended) {
453                 return NULL;
454         }
455
456         ao2_ref(transferer, +1);
457         attended->transferer = transferer;
458         ast_channel_ref(transferer->channel);
459         attended->transferer_chan = transferer->channel;
460         ao2_ref(transferer_second, +1);
461         attended->transferer_second = transferer_second;
462
463         if (progress) {
464                 ao2_ref(progress, +1);
465                 attended->progress = progress;
466         }
467
468         return attended;
469 }
470
471 static int defer_termination_cancel(void *data)
472 {
473         struct ast_sip_session *session = data;
474
475         ast_sip_session_defer_termination_cancel(session);
476         ao2_ref(session, -1);
477         return 0;
478 }
479
480 /*!
481  * \internal
482  * \brief Convert transfer enum to SIP response code.
483  * \since 13.3.0
484  *
485  * \param xfer_code Core transfer function enum result.
486  *
487  * \return SIP response code
488  */
489 static int xfer_response_code2sip(enum ast_transfer_result xfer_code)
490 {
491         int response;
492
493         response = 503;
494         switch (xfer_code) {
495         case AST_BRIDGE_TRANSFER_INVALID:
496                 response = 400;
497                 break;
498         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
499                 response = 403;
500                 break;
501         case AST_BRIDGE_TRANSFER_FAIL:
502                 response = 500;
503                 break;
504         case AST_BRIDGE_TRANSFER_SUCCESS:
505                 response = 200;
506                 break;
507         }
508         return response;
509 }
510
511 /*! \brief Task for attended transfer executed by attended->transferer_second serializer */
512 static int refer_attended_task(void *data)
513 {
514         struct refer_attended *attended = data;
515         int response;
516
517         if (attended->transferer_second->channel) {
518                 ast_debug(3, "Performing a REFER attended transfer - Transferer #1: %s Transferer #2: %s\n",
519                         ast_channel_name(attended->transferer_chan),
520                         ast_channel_name(attended->transferer_second->channel));
521
522                 response = xfer_response_code2sip(ast_bridge_transfer_attended(
523                         attended->transferer_chan,
524                         attended->transferer_second->channel));
525
526                 ast_debug(3, "Final response for REFER attended transfer - Transferer #1: %s Transferer #2: %s is '%d'\n",
527                         ast_channel_name(attended->transferer_chan),
528                         ast_channel_name(attended->transferer_second->channel),
529                         response);
530         } else {
531                 ast_debug(3, "Received REFER request on channel '%s' but other channel has gone.\n",
532                         ast_channel_name(attended->transferer_chan));
533                 response = 603;
534         }
535
536         if (attended->progress) {
537                 struct refer_progress_notification *notification;
538
539                 notification = refer_progress_notification_alloc(attended->progress, response,
540                         PJSIP_EVSUB_STATE_TERMINATED);
541                 if (notification) {
542                         refer_progress_notify(notification);
543                 }
544         }
545
546         if (response != 200) {
547                 if (!ast_sip_push_task(attended->transferer->serializer,
548                         defer_termination_cancel, attended->transferer)) {
549                         /* Gave the ref to the pushed task. */
550                         attended->transferer = NULL;
551                 }
552         }
553
554         ao2_ref(attended, -1);
555         return 0;
556 }
557
558 /*! \brief Structure for blind transfer callback details */
559 struct refer_blind {
560         /*! \brief Context being used for transfer */
561         const char *context;
562         /*! \brief Optional progress structure */
563         struct refer_progress *progress;
564         /*! \brief REFER message */
565         pjsip_rx_data *rdata;
566         /*! \brief Optional Replaces header */
567         pjsip_replaces_hdr *replaces;
568         /*! \brief Optional Refer-To header */
569         pjsip_sip_uri *refer_to;
570         /*! \brief Attended transfer flag */
571         unsigned int attended:1;
572 };
573
574 /*! \brief Blind transfer callback function */
575 static void refer_blind_callback(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
576         enum ast_transfer_type transfer_type)
577 {
578         struct refer_blind *refer = user_data_wrapper->data;
579         pjsip_generic_string_hdr *referred_by;
580
581         static const pj_str_t str_referred_by = { "Referred-By", 11 };
582         static const pj_str_t str_referred_by_s = { "b", 1 };
583
584         pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
585
586         if (refer->progress && !refer->attended && !refer->progress->refer_blind_progress) {
587                 /* If blind transfer and endpoint doesn't want to receive all the progress details */
588                 struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
589                         PJSIP_EVSUB_STATE_TERMINATED);
590
591                 if (notification) {
592                         refer_progress_notify(notification);
593                 }
594         } else if (refer->progress) {
595                 /* If attended transfer and progress monitoring is being done attach a frame hook so we can monitor it */
596                 struct ast_framehook_interface hook = {
597                         .version = AST_FRAMEHOOK_INTERFACE_VERSION,
598                         .event_cb = refer_progress_framehook,
599                         .destroy_cb = refer_progress_framehook_destroy,
600                         .data = refer->progress,
601                         .disable_inheritance = 1,
602                 };
603
604                 refer->progress->transferee = ast_strdup(ast_channel_uniqueid(chan));
605                 if (!refer->progress->transferee) {
606                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
607                                 PJSIP_EVSUB_STATE_TERMINATED);
608
609                         ast_log(LOG_WARNING, "Could not copy channel name '%s' during transfer - assuming success\n",
610                                 ast_channel_name(chan));
611
612                         if (notification) {
613                                 refer_progress_notify(notification);
614                         }
615                 }
616
617                 /* Progress needs a reference to the transfer_channel_data so that it can track the completed status of the transfer */
618                 ao2_ref(user_data_wrapper, +1);
619                 refer->progress->transfer_data = user_data_wrapper;
620
621                 /* We need to bump the reference count up on the progress structure since it is in the frame hook now */
622                 ao2_ref(refer->progress, +1);
623
624                 /* If we can't attach a frame hook for whatever reason send a notification of success immediately */
625                 ast_channel_lock(chan);
626                 refer->progress->framehook = ast_framehook_attach(chan, &hook);
627                 ast_channel_unlock(chan);
628                 if (refer->progress->framehook < 0) {
629                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
630                                 PJSIP_EVSUB_STATE_TERMINATED);
631
632                         ast_log(LOG_WARNING, "Could not attach REFER transfer progress monitoring hook to channel '%s' - assuming success\n",
633                                 ast_channel_name(chan));
634
635                         if (notification) {
636                                 refer_progress_notify(notification);
637                         }
638
639                         ao2_cleanup(refer->progress);
640                 }
641
642                 /* We need to bump the reference count for the stasis subscription */
643                 ao2_ref(refer->progress, +1);
644                 /* We also will need to detect if the transferee enters a bridge. This is currently the only reliable way to
645                  * detect if the transfer target has answered the call
646                  */
647                 refer->progress->bridge_sub = stasis_subscribe_pool(ast_bridge_topic_all(), refer_progress_bridge, refer->progress);
648                 if (!refer->progress->bridge_sub) {
649                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
650                                 PJSIP_EVSUB_STATE_TERMINATED);
651
652                         ast_log(LOG_WARNING, "Could not create bridge stasis subscription for monitoring progress on transfer of channel '%s' - assuming success\n",
653                                         ast_channel_name(chan));
654
655                         if (notification) {
656                                 refer_progress_notify(notification);
657                         }
658
659                         ast_channel_lock(chan);
660                         ast_framehook_detach(chan, refer->progress->framehook);
661                         ast_channel_unlock(chan);
662
663                         ao2_cleanup(refer->progress);
664                 }
665         }
666
667         pbx_builtin_setvar_helper(chan, "SIPREFERRINGCONTEXT", S_OR(refer->context, NULL));
668
669         referred_by = pjsip_msg_find_hdr_by_names(refer->rdata->msg_info.msg,
670                 &str_referred_by, &str_referred_by_s, NULL);
671         if (referred_by) {
672                 size_t uri_size = pj_strlen(&referred_by->hvalue) + 1;
673                 char *uri = ast_alloca(uri_size);
674
675                 ast_copy_pj_str(uri, &referred_by->hvalue, uri_size);
676                 pbx_builtin_setvar_helper(chan, "__SIPREFERREDBYHDR", S_OR(uri, NULL));
677         } else {
678                 pbx_builtin_setvar_helper(chan, "SIPREFERREDBYHDR", NULL);
679         }
680
681         if (refer->replaces) {
682                 char replaces[512];
683                 char *replaces_val = NULL;
684                 int len;
685
686                 len = pjsip_hdr_print_on(refer->replaces, replaces, sizeof(replaces) - 1);
687                 if (len != -1) {
688                         /* pjsip_hdr_print_on does not NULL terminate the buffer */
689                         replaces[len] = '\0';
690                         replaces_val = replaces + sizeof("Replaces:");
691                 }
692                 pbx_builtin_setvar_helper(chan, "__SIPREPLACESHDR", replaces_val);
693         } else {
694                 pbx_builtin_setvar_helper(chan, "SIPREPLACESHDR", NULL);
695         }
696
697         if (refer->refer_to) {
698                 char refer_to[PJSIP_MAX_URL_SIZE];
699
700                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, refer->refer_to, refer_to, sizeof(refer_to));
701                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", S_OR(refer_to, NULL));
702         } else {
703                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", NULL);
704         }
705 }
706
707 /*!
708  * \internal
709  * \brief Set the passed in context variable to the determined transfer context.
710  * \since 13.3.0
711  *
712  * \param context Set to the determined transfer context.
713  * \param session INVITE dialog SIP session.
714  */
715 #define DETERMINE_TRANSFER_CONTEXT(context, session)                                                                    \
716         do {                                                                                                                                                            \
717                 ast_channel_lock((session)->channel);                                                                                   \
718                 context = pbx_builtin_getvar_helper((session)->channel, "TRANSFER_CONTEXT");    \
719                 if (ast_strlen_zero(context)) {                                                                                                 \
720                         context = (session)->endpoint->context;                                                                         \
721                 } else {                                                                                                                                                \
722                         context = ast_strdupa(context);                                                                                         \
723                 }                                                                                                                                                               \
724                 ast_channel_unlock((session)->channel);                                                                                 \
725         } while (0)                                                                                                                                                     \
726
727 static int refer_incoming_attended_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target_uri,
728         pjsip_param *replaces_param, struct refer_progress *progress)
729 {
730         const pj_str_t str_replaces = { "Replaces", 8 };
731         pj_str_t replaces_content;
732         pjsip_replaces_hdr *replaces;
733         int parsed_len;
734         pjsip_dialog *dlg;
735
736         pj_strdup_with_null(rdata->tp_info.pool, &replaces_content, &replaces_param->value);
737
738         /* Parsing the parameter as a Replaces header easily grabs the needed information */
739         if (!(replaces = pjsip_parse_hdr(rdata->tp_info.pool, &str_replaces, replaces_content.ptr,
740                 pj_strlen(&replaces_content), &parsed_len))) {
741                 ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' with invalid Replaces header, rejecting\n",
742                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
743                 return 400;
744         }
745
746         /* See if the dialog is local, or remote */
747         if ((dlg = pjsip_ua_find_dialog(&replaces->call_id, &replaces->to_tag, &replaces->from_tag, PJ_TRUE))) {
748                 RAII_VAR(struct ast_sip_session *, other_session, ast_sip_dialog_get_session(dlg), ao2_cleanup);
749                 struct refer_attended *attended;
750
751                 pjsip_dlg_dec_lock(dlg);
752
753                 if (!other_session) {
754                         ast_debug(3, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but no session exists on it\n",
755                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
756                         return 603;
757                 }
758
759                 /* We defer actually doing the attended transfer to the other session so no deadlock can occur */
760                 if (!(attended = refer_attended_alloc(session, other_session, progress))) {
761                         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",
762                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
763                         return 500;
764                 }
765
766                 if (ast_sip_session_defer_termination(session)) {
767                         ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but could not defer termination, rejecting\n",
768                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
769                         ao2_cleanup(attended);
770                         return 500;
771                 }
772
773                 /* Push it to the other session, which will have both channels with minimal locking */
774                 if (ast_sip_push_task(other_session->serializer, refer_attended_task, attended)) {
775                         ast_sip_session_defer_termination_cancel(session);
776                         ao2_cleanup(attended);
777                         return 500;
778                 }
779
780                 ast_debug(3, "Attended transfer from '%s' pushed to second channel serializer\n",
781                         ast_channel_name(session->channel));
782
783                 return 200;
784         } else {
785                 const char *context;
786                 struct refer_blind refer = { 0, };
787                 int response;
788
789                 DETERMINE_TRANSFER_CONTEXT(context, session);
790
791                 if (!ast_exists_extension(NULL, context, "external_replaces", 1, NULL)) {
792                         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",
793                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
794                         return 404;
795                 }
796
797                 refer.context = context;
798                 refer.progress = progress;
799                 refer.rdata = rdata;
800                 refer.replaces = replaces;
801                 refer.refer_to = target_uri;
802                 refer.attended = 1;
803
804                 if (ast_sip_session_defer_termination(session)) {
805                         ast_log(LOG_ERROR, "Received REFER for remote session on channel '%s' from endpoint '%s' but could not defer termination, rejecting\n",
806                                 ast_channel_name(session->channel),
807                                 ast_sorcery_object_get_id(session->endpoint));
808                         return 500;
809                 }
810
811                 response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
812                         "external_replaces", context, refer_blind_callback, &refer));
813                 if (response != 200) {
814                         ast_sip_session_defer_termination_cancel(session);
815                 }
816                 return response;
817         }
818 }
819
820 static int refer_incoming_blind_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target,
821         struct refer_progress *progress)
822 {
823         const char *context;
824         char exten[AST_MAX_EXTENSION];
825         struct refer_blind refer = { 0, };
826         int response;
827
828         /* If no explicit transfer context has been provided use their configured context */
829         DETERMINE_TRANSFER_CONTEXT(context, session);
830
831         /* Using the user portion of the target URI see if it exists as a valid extension in their context */
832         ast_copy_pj_str(exten, &target->user, sizeof(exten));
833
834         /*
835          * We may want to match in the dialplan without any user
836          * options getting in the way.
837          */
838         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(exten);
839
840         /* Uri without exten */
841         if (ast_strlen_zero(exten)) {
842                 ast_copy_string(exten, "s", sizeof(exten));
843                 ast_debug(3, "Channel '%s' from endpoint '%s' attempted blind transfer to a target without extension. Target was set to 's@%s'\n",
844                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
845         }
846
847         if (!ast_exists_extension(NULL, context, exten, 1, NULL)) {
848                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer to '%s@%s' but target does not exist\n",
849                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), exten, context);
850                 return 404;
851         }
852
853         refer.context = context;
854         refer.progress = progress;
855         refer.rdata = rdata;
856         refer.refer_to = target;
857         refer.attended = 0;
858
859         if (ast_sip_session_defer_termination(session)) {
860                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer but could not defer termination, rejecting\n",
861                         ast_channel_name(session->channel),
862                         ast_sorcery_object_get_id(session->endpoint));
863                 return 500;
864         }
865
866         response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
867                 exten, context, refer_blind_callback, &refer));
868         if (response != 200) {
869                 ast_sip_session_defer_termination_cancel(session);
870         }
871         return response;
872 }
873
874 /*! \brief Structure used to retrieve channel from another session */
875 struct invite_replaces {
876         /*! \brief Session we want the channel from */
877         struct ast_sip_session *session;
878         /*! \brief Channel from the session (with reference) */
879         struct ast_channel *channel;
880         /*! \brief Bridge the channel is in */
881         struct ast_bridge *bridge;
882 };
883
884 /*! \brief Task for invite replaces */
885 static int invite_replaces(void *data)
886 {
887         struct invite_replaces *invite = data;
888
889         if (!invite->session->channel) {
890                 return -1;
891         }
892
893         ast_channel_ref(invite->session->channel);
894         invite->channel = invite->session->channel;
895
896         ast_channel_lock(invite->channel);
897         invite->bridge = ast_channel_get_bridge(invite->channel);
898         ast_channel_unlock(invite->channel);
899
900         return 0;
901 }
902
903 static int refer_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
904 {
905         pjsip_dialog *other_dlg = NULL;
906         pjsip_tx_data *packet;
907         int response = 0;
908         RAII_VAR(struct ast_sip_session *, other_session, NULL, ao2_cleanup);
909         struct invite_replaces invite;
910
911         /* If a Replaces header is present make sure it is valid */
912         if (pjsip_replaces_verify_request(rdata, &other_dlg, PJ_TRUE, &packet) != PJ_SUCCESS) {
913                 response = packet->msg->line.status.code;
914                 ast_assert(response != 0);
915                 pjsip_tx_data_dec_ref(packet);
916                 goto inv_replace_failed;
917         }
918
919         /* If no other dialog exists then this INVITE request does not have a Replaces header */
920         if (!other_dlg) {
921                 return 0;
922         }
923
924         other_session = ast_sip_dialog_get_session(other_dlg);
925         pjsip_dlg_dec_lock(other_dlg);
926
927         /* Don't accept an in-dialog INVITE with Replaces as it does not make much sense */
928         if (session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
929                 response = 488;
930                 goto inv_replace_failed;
931         }
932
933         if (!other_session) {
934                 ast_debug(3, "INVITE with Replaces received on channel '%s' from endpoint '%s', but requested session does not exist\n",
935                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
936                 response = 481;
937                 goto inv_replace_failed;
938         }
939
940         invite.session = other_session;
941
942         if (ast_sip_push_task_synchronous(other_session->serializer, invite_replaces, &invite)) {
943                 response = 481;
944                 goto inv_replace_failed;
945         }
946
947         ast_channel_lock(session->channel);
948         ast_setstate(session->channel, AST_STATE_RING);
949         ast_channel_unlock(session->channel);
950         ast_raw_answer(session->channel);
951
952         ast_debug(3, "INVITE with Replaces being attempted.  '%s' --> '%s'\n",
953                 ast_channel_name(session->channel), ast_channel_name(invite.channel));
954
955         if (!invite.bridge) {
956                 struct ast_channel *chan = session->channel;
957
958                 /*
959                  * This will use a synchronous task but we aren't operating in
960                  * the serializer at this point in time, so it won't deadlock.
961                  */
962                 if (!ast_channel_move(invite.channel, chan)) {
963                         /*
964                          * We can't directly use session->channel because ast_channel_move()
965                          * does a masquerade which changes session->channel to a different
966                          * channel.  To ensure we work on the right channel we store a
967                          * pointer locally before we begin so it remains valid.
968                          */
969                         ast_hangup(chan);
970                 } else {
971                         response = AST_CAUSE_FAILURE;
972                 }
973         } else {
974                 if (ast_bridge_impart(invite.bridge, session->channel, invite.channel, NULL,
975                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
976                         response = AST_CAUSE_FAILURE;
977                 }
978         }
979
980         ast_channel_unref(invite.channel);
981         ao2_cleanup(invite.bridge);
982
983         if (!response) {
984                 /*
985                  * On success we cannot use session->channel in the debug message.
986                  * This thread either no longer has a ref to session->channel or
987                  * session->channel is no longer the original channel.
988                  */
989                 ast_debug(3, "INVITE with Replaces successfully completed.\n");
990         } else {
991                 ast_debug(3, "INVITE with Replaces failed on channel '%s', hanging up with cause '%d'\n",
992                         ast_channel_name(session->channel), response);
993                 ast_channel_lock(session->channel);
994                 ast_channel_hangupcause_set(session->channel, response);
995                 ast_channel_unlock(session->channel);
996                 ast_hangup(session->channel);
997         }
998
999         return 1;
1000
1001 inv_replace_failed:
1002         if (session->inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1003                 ast_debug(3, "INVITE with Replaces failed on channel '%s', sending response of '%d'\n",
1004                         ast_channel_name(session->channel), response);
1005                 session->defer_terminate = 1;
1006                 ast_hangup(session->channel);
1007
1008                 if (pjsip_inv_end_session(session->inv_session, response, NULL, &packet) == PJ_SUCCESS
1009                         && packet) {
1010                         ast_sip_session_send_response(session, packet);
1011                 }
1012         } else {
1013                 ast_debug(3, "INVITE with Replaces in-dialog on channel '%s', hanging up\n",
1014                         ast_channel_name(session->channel));
1015                 ast_queue_hangup(session->channel);
1016         }
1017
1018         return 1;
1019 }
1020
1021 static int refer_incoming_refer_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1022 {
1023         pjsip_generic_string_hdr *refer_to;
1024         char *uri;
1025         size_t uri_size;
1026         pjsip_uri *target;
1027         pjsip_sip_uri *target_uri;
1028         RAII_VAR(struct refer_progress *, progress, NULL, ao2_cleanup);
1029         pjsip_param *replaces;
1030         int response;
1031
1032         static const pj_str_t str_refer_to = { "Refer-To", 8 };
1033         static const pj_str_t str_refer_to_s = { "r", 1 };
1034         static const pj_str_t str_replaces = { "Replaces", 8 };
1035
1036         if (!session->channel) {
1037                 /* No channel to refer.  Likely because the call was just hung up. */
1038                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 404, NULL, NULL, NULL);
1039                 ast_debug(3, "Received a REFER on a session with no channel from endpoint '%s'.\n",
1040                         ast_sorcery_object_get_id(session->endpoint));
1041                 return 0;
1042         }
1043
1044         if (!session->endpoint->allowtransfer) {
1045                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 603, NULL, NULL, NULL);
1046                 ast_log(LOG_WARNING, "Endpoint %s transfer attempt blocked due to configuration\n",
1047                                 ast_sorcery_object_get_id(session->endpoint));
1048                 return 0;
1049         }
1050
1051         /* A Refer-To header is required */
1052         refer_to = pjsip_msg_find_hdr_by_names(rdata->msg_info.msg, &str_refer_to, &str_refer_to_s, NULL);
1053         if (!refer_to) {
1054                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1055                 ast_debug(3, "Received a REFER without Refer-To on channel '%s' from endpoint '%s'\n",
1056                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1057                 return 0;
1058         }
1059
1060         /* The ast_copy_pj_str to uri is needed because it puts the NULL terminator to the uri
1061          * as pjsip_parse_uri require a NULL terminated uri
1062          */
1063
1064         uri_size = pj_strlen(&refer_to->hvalue) + 1;
1065         uri = ast_alloca(uri_size);
1066         ast_copy_pj_str(uri, &refer_to->hvalue, uri_size);
1067
1068         target = pjsip_parse_uri(rdata->tp_info.pool, uri, uri_size - 1, 0);
1069
1070         if (!target
1071                 || (!PJSIP_URI_SCHEME_IS_SIP(target)
1072                         && !PJSIP_URI_SCHEME_IS_SIPS(target))) {
1073
1074                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1075                 ast_debug(3, "Received a REFER without a parseable Refer-To ('%s') on channel '%s' from endpoint '%s'\n",
1076                         uri, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1077                 return 0;
1078         }
1079         target_uri = pjsip_uri_get_uri(target);
1080
1081         /* Set up REFER progress subscription if requested/possible */
1082         if (refer_progress_alloc(session, rdata, &progress)) {
1083                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 500, NULL, NULL, NULL);
1084                 ast_debug(3, "Could not set up subscription for REFER on channel '%s' from endpoint '%s'\n",
1085                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1086                 return 0;
1087         }
1088
1089         /* Determine if this is an attended or blind transfer */
1090         if ((replaces = pjsip_param_find(&target_uri->header_param, &str_replaces)) ||
1091                 (replaces = pjsip_param_find(&target_uri->other_param, &str_replaces))) {
1092                 response = refer_incoming_attended_request(session, rdata, target_uri, replaces, progress);
1093         } else {
1094                 response = refer_incoming_blind_request(session, rdata, target_uri, progress);
1095         }
1096
1097         if (!progress) {
1098                 /* The transferer has requested no subscription, so send a final response immediately */
1099                 pjsip_tx_data *tdata;
1100                 const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
1101                 const pj_str_t str_false = { "false", 5 };
1102                 pjsip_hdr *hdr;
1103
1104                 ast_debug(3, "Progress monitoring not requested for REFER on channel '%s' from endpoint '%s', sending immediate response of '%d'\n",
1105                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), response);
1106
1107                 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, response, NULL, &tdata) != PJ_SUCCESS) {
1108                         pjsip_dlg_respond(session->inv_session->dlg, rdata, response, NULL, NULL, NULL);
1109                         return 0;
1110                 }
1111
1112                 hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub, &str_false);
1113                 pjsip_msg_add_hdr(tdata->msg, hdr);
1114
1115                 pjsip_dlg_send_response(session->inv_session->dlg, pjsip_rdata_get_tsx(rdata), tdata);
1116         } else if (response != 200) {
1117                 /* Since this failed we can send a final NOTIFY now and terminate the subscription */
1118                 struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, response, PJSIP_EVSUB_STATE_TERMINATED);
1119
1120                 if (notification) {
1121                         /* The refer_progress_notify function will call ao2_cleanup on this for us */
1122                         refer_progress_notify(notification);
1123                 }
1124         }
1125
1126         return 0;
1127 }
1128
1129 static int refer_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
1130 {
1131         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_refer_method())) {
1132                 return refer_incoming_refer_request(session, rdata);
1133         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_invite_method)) {
1134                 return refer_incoming_invite_request(session, rdata);
1135         } else {
1136                 return 0;
1137         }
1138 }
1139
1140 /*!
1141  * \brief Use the value of a channel variable as the value of a SIP header
1142  *
1143  * This looks up a variable name on a channel, then takes that value and adds
1144  * it to an outgoing SIP request. If the header already exists on the message,
1145  * then no action is taken.
1146  *
1147  * \pre chan is locked.
1148  *
1149  * \param chan The channel on which to find the variable.
1150  * \param var_name The name of the channel variable to use.
1151  * \param header_name The name of the SIP header to add to the outgoing message.
1152  * \param tdata The outgoing SIP message on which to add the header
1153  */
1154 static void add_header_from_channel_var(struct ast_channel *chan, const char *var_name, const char *header_name, pjsip_tx_data *tdata)
1155 {
1156         const char *var_value;
1157         pj_str_t pj_header_name;
1158         pjsip_hdr *header;
1159
1160         var_value = pbx_builtin_getvar_helper(chan, var_name);
1161         if (ast_strlen_zero(var_value)) {
1162                 return;
1163         }
1164
1165         pj_cstr(&pj_header_name, header_name);
1166         header = pjsip_msg_find_hdr_by_name(tdata->msg, &pj_header_name, NULL);
1167         if (header) {
1168                 return;
1169         }
1170         ast_sip_add_header(tdata, header_name, var_value);
1171 }
1172
1173 static void refer_outgoing_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
1174 {
1175         if (pjsip_method_cmp(&tdata->msg->line.req.method, &pjsip_invite_method)
1176                 || !session->channel
1177                 || session->inv_session->state != PJSIP_INV_STATE_NULL) {
1178                 return;
1179         }
1180
1181         ast_channel_lock(session->channel);
1182         add_header_from_channel_var(session->channel, "SIPREPLACESHDR", "Replaces", tdata);
1183         add_header_from_channel_var(session->channel, "SIPREFERREDBYHDR", "Referred-By", tdata);
1184         ast_channel_unlock(session->channel);
1185 }
1186
1187 static struct ast_sip_session_supplement refer_supplement = {
1188         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
1189         .incoming_request = refer_incoming_request,
1190         .outgoing_request = refer_outgoing_request,
1191 };
1192
1193 static int load_module(void)
1194 {
1195         const pj_str_t str_norefersub = { "norefersub", 10 };
1196
1197         CHECK_PJSIP_SESSION_MODULE_LOADED();
1198
1199         pjsip_replaces_init_module(ast_sip_get_pjsip_endpoint());
1200         pjsip_xfer_init_module(ast_sip_get_pjsip_endpoint());
1201         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_SUPPORTED, NULL, 1, &str_norefersub);
1202
1203         ast_sip_register_service(&refer_progress_module);
1204         ast_sip_session_register_supplement(&refer_supplement);
1205
1206         return AST_MODULE_LOAD_SUCCESS;
1207 }
1208
1209 static int unload_module(void)
1210 {
1211         ast_sip_session_unregister_supplement(&refer_supplement);
1212         ast_sip_unregister_service(&refer_progress_module);
1213
1214         return 0;
1215 }
1216
1217 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Blind and Attended Transfer Support",
1218         .support_level = AST_MODULE_SUPPORT_CORE,
1219         .load = load_module,
1220         .unload = unload_module,
1221         .load_pri = AST_MODPRI_APP_DEPEND,
1222 );