res_pjsip_refer/session: Calls dropped during transfer
[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         ast_sip_session_end_if_deferred(attended->transferer);
547         if (response != 200) {
548                 if (!ast_sip_push_task(attended->transferer->serializer,
549                         defer_termination_cancel, attended->transferer)) {
550                         /* Gave the ref to the pushed task. */
551                         attended->transferer = NULL;
552                 }
553         }
554
555         ao2_ref(attended, -1);
556         return 0;
557 }
558
559 /*! \brief Structure for blind transfer callback details */
560 struct refer_blind {
561         /*! \brief Context being used for transfer */
562         const char *context;
563         /*! \brief Optional progress structure */
564         struct refer_progress *progress;
565         /*! \brief REFER message */
566         pjsip_rx_data *rdata;
567         /*! \brief Optional Replaces header */
568         pjsip_replaces_hdr *replaces;
569         /*! \brief Optional Refer-To header */
570         pjsip_sip_uri *refer_to;
571         /*! \brief Attended transfer flag */
572         unsigned int attended:1;
573 };
574
575 /*! \brief Blind transfer callback function */
576 static void refer_blind_callback(struct ast_channel *chan, struct transfer_channel_data *user_data_wrapper,
577         enum ast_transfer_type transfer_type)
578 {
579         struct refer_blind *refer = user_data_wrapper->data;
580         pjsip_generic_string_hdr *referred_by;
581
582         static const pj_str_t str_referred_by = { "Referred-By", 11 };
583         static const pj_str_t str_referred_by_s = { "b", 1 };
584
585         pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
586
587         if (refer->progress && !refer->attended && !refer->progress->refer_blind_progress) {
588                 /* If blind transfer and endpoint doesn't want to receive all the progress details */
589                 struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
590                         PJSIP_EVSUB_STATE_TERMINATED);
591
592                 if (notification) {
593                         refer_progress_notify(notification);
594                 }
595         } else if (refer->progress) {
596                 /* If attended transfer and progress monitoring is being done attach a frame hook so we can monitor it */
597                 struct ast_framehook_interface hook = {
598                         .version = AST_FRAMEHOOK_INTERFACE_VERSION,
599                         .event_cb = refer_progress_framehook,
600                         .destroy_cb = refer_progress_framehook_destroy,
601                         .data = refer->progress,
602                         .disable_inheritance = 1,
603                 };
604
605                 refer->progress->transferee = ast_strdup(ast_channel_uniqueid(chan));
606                 if (!refer->progress->transferee) {
607                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
608                                 PJSIP_EVSUB_STATE_TERMINATED);
609
610                         ast_log(LOG_WARNING, "Could not copy channel name '%s' during transfer - assuming success\n",
611                                 ast_channel_name(chan));
612
613                         if (notification) {
614                                 refer_progress_notify(notification);
615                         }
616                 }
617
618                 /* Progress needs a reference to the transfer_channel_data so that it can track the completed status of the transfer */
619                 ao2_ref(user_data_wrapper, +1);
620                 refer->progress->transfer_data = user_data_wrapper;
621
622                 /* We need to bump the reference count up on the progress structure since it is in the frame hook now */
623                 ao2_ref(refer->progress, +1);
624
625                 /* If we can't attach a frame hook for whatever reason send a notification of success immediately */
626                 ast_channel_lock(chan);
627                 refer->progress->framehook = ast_framehook_attach(chan, &hook);
628                 ast_channel_unlock(chan);
629                 if (refer->progress->framehook < 0) {
630                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
631                                 PJSIP_EVSUB_STATE_TERMINATED);
632
633                         ast_log(LOG_WARNING, "Could not attach REFER transfer progress monitoring hook to channel '%s' - assuming success\n",
634                                 ast_channel_name(chan));
635
636                         if (notification) {
637                                 refer_progress_notify(notification);
638                         }
639
640                         ao2_cleanup(refer->progress);
641                 }
642
643                 /* We need to bump the reference count for the stasis subscription */
644                 ao2_ref(refer->progress, +1);
645                 /* We also will need to detect if the transferee enters a bridge. This is currently the only reliable way to
646                  * detect if the transfer target has answered the call
647                  */
648                 refer->progress->bridge_sub = stasis_subscribe_pool(ast_bridge_topic_all(), refer_progress_bridge, refer->progress);
649                 if (!refer->progress->bridge_sub) {
650                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
651                                 PJSIP_EVSUB_STATE_TERMINATED);
652
653                         ast_log(LOG_WARNING, "Could not create bridge stasis subscription for monitoring progress on transfer of channel '%s' - assuming success\n",
654                                         ast_channel_name(chan));
655
656                         if (notification) {
657                                 refer_progress_notify(notification);
658                         }
659
660                         ast_channel_lock(chan);
661                         ast_framehook_detach(chan, refer->progress->framehook);
662                         ast_channel_unlock(chan);
663
664                         ao2_cleanup(refer->progress);
665                 }
666         }
667
668         pbx_builtin_setvar_helper(chan, "SIPREFERRINGCONTEXT", S_OR(refer->context, NULL));
669
670         referred_by = pjsip_msg_find_hdr_by_names(refer->rdata->msg_info.msg,
671                 &str_referred_by, &str_referred_by_s, NULL);
672         if (referred_by) {
673                 size_t uri_size = pj_strlen(&referred_by->hvalue) + 1;
674                 char *uri = ast_alloca(uri_size);
675
676                 ast_copy_pj_str(uri, &referred_by->hvalue, uri_size);
677                 pbx_builtin_setvar_helper(chan, "__SIPREFERREDBYHDR", S_OR(uri, NULL));
678         } else {
679                 pbx_builtin_setvar_helper(chan, "SIPREFERREDBYHDR", NULL);
680         }
681
682         if (refer->replaces) {
683                 char replaces[512];
684                 char *replaces_val = NULL;
685                 int len;
686
687                 len = pjsip_hdr_print_on(refer->replaces, replaces, sizeof(replaces) - 1);
688                 if (len != -1) {
689                         /* pjsip_hdr_print_on does not NULL terminate the buffer */
690                         replaces[len] = '\0';
691                         replaces_val = replaces + sizeof("Replaces:");
692                 }
693                 pbx_builtin_setvar_helper(chan, "__SIPREPLACESHDR", replaces_val);
694         } else {
695                 pbx_builtin_setvar_helper(chan, "SIPREPLACESHDR", NULL);
696         }
697
698         if (refer->refer_to) {
699                 char refer_to[PJSIP_MAX_URL_SIZE];
700
701                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, refer->refer_to, refer_to, sizeof(refer_to));
702                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", S_OR(refer_to, NULL));
703         } else {
704                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", NULL);
705         }
706 }
707
708 /*!
709  * \internal
710  * \brief Set the passed in context variable to the determined transfer context.
711  * \since 13.3.0
712  *
713  * \param context Set to the determined transfer context.
714  * \param session INVITE dialog SIP session.
715  */
716 #define DETERMINE_TRANSFER_CONTEXT(context, session)                                                                    \
717         do {                                                                                                                                                            \
718                 ast_channel_lock((session)->channel);                                                                                   \
719                 context = pbx_builtin_getvar_helper((session)->channel, "TRANSFER_CONTEXT");    \
720                 if (ast_strlen_zero(context)) {                                                                                                 \
721                         context = (session)->endpoint->context;                                                                         \
722                 } else {                                                                                                                                                \
723                         context = ast_strdupa(context);                                                                                         \
724                 }                                                                                                                                                               \
725                 ast_channel_unlock((session)->channel);                                                                                 \
726         } while (0)                                                                                                                                                     \
727
728 static int refer_incoming_attended_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target_uri,
729         pjsip_param *replaces_param, struct refer_progress *progress)
730 {
731         const pj_str_t str_replaces = { "Replaces", 8 };
732         pj_str_t replaces_content;
733         pjsip_replaces_hdr *replaces;
734         int parsed_len;
735         pjsip_dialog *dlg;
736
737         pj_strdup_with_null(rdata->tp_info.pool, &replaces_content, &replaces_param->value);
738
739         /* Parsing the parameter as a Replaces header easily grabs the needed information */
740         if (!(replaces = pjsip_parse_hdr(rdata->tp_info.pool, &str_replaces, replaces_content.ptr,
741                 pj_strlen(&replaces_content), &parsed_len))) {
742                 ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' with invalid Replaces header, rejecting\n",
743                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
744                 return 400;
745         }
746
747         /* See if the dialog is local, or remote */
748         if ((dlg = pjsip_ua_find_dialog(&replaces->call_id, &replaces->to_tag, &replaces->from_tag, PJ_TRUE))) {
749                 RAII_VAR(struct ast_sip_session *, other_session, ast_sip_dialog_get_session(dlg), ao2_cleanup);
750                 struct refer_attended *attended;
751
752                 pjsip_dlg_dec_lock(dlg);
753
754                 if (!other_session) {
755                         ast_debug(3, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but no session exists on it\n",
756                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
757                         return 603;
758                 }
759
760                 /* We defer actually doing the attended transfer to the other session so no deadlock can occur */
761                 if (!(attended = refer_attended_alloc(session, other_session, progress))) {
762                         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",
763                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
764                         return 500;
765                 }
766
767                 if (ast_sip_session_defer_termination(session)) {
768                         ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but could not defer termination, rejecting\n",
769                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
770                         ao2_cleanup(attended);
771                         return 500;
772                 }
773
774                 /* Push it to the other session, which will have both channels with minimal locking */
775                 if (ast_sip_push_task(other_session->serializer, refer_attended_task, attended)) {
776                         ast_sip_session_end_if_deferred(session);
777                         ast_sip_session_defer_termination_cancel(session);
778                         ao2_cleanup(attended);
779                         return 500;
780                 }
781
782                 ast_debug(3, "Attended transfer from '%s' pushed to second channel serializer\n",
783                         ast_channel_name(session->channel));
784
785                 return 200;
786         } else {
787                 const char *context;
788                 struct refer_blind refer = { 0, };
789                 int response;
790
791                 DETERMINE_TRANSFER_CONTEXT(context, session);
792
793                 if (!ast_exists_extension(NULL, context, "external_replaces", 1, NULL)) {
794                         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",
795                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
796                         return 404;
797                 }
798
799                 refer.context = context;
800                 refer.progress = progress;
801                 refer.rdata = rdata;
802                 refer.replaces = replaces;
803                 refer.refer_to = target_uri;
804                 refer.attended = 1;
805
806                 if (ast_sip_session_defer_termination(session)) {
807                         ast_log(LOG_ERROR, "Received REFER for remote session on channel '%s' from endpoint '%s' but could not defer termination, rejecting\n",
808                                 ast_channel_name(session->channel),
809                                 ast_sorcery_object_get_id(session->endpoint));
810                         return 500;
811                 }
812
813                 response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
814                         "external_replaces", context, refer_blind_callback, &refer));
815
816                 ast_sip_session_end_if_deferred(session);
817                 if (response != 200) {
818                         ast_sip_session_defer_termination_cancel(session);
819                 }
820
821                 return response;
822         }
823 }
824
825 static int refer_incoming_blind_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target,
826         struct refer_progress *progress)
827 {
828         const char *context;
829         char exten[AST_MAX_EXTENSION];
830         struct refer_blind refer = { 0, };
831         int response;
832
833         /* If no explicit transfer context has been provided use their configured context */
834         DETERMINE_TRANSFER_CONTEXT(context, session);
835
836         /* Using the user portion of the target URI see if it exists as a valid extension in their context */
837         ast_copy_pj_str(exten, &target->user, sizeof(exten));
838
839         /*
840          * We may want to match in the dialplan without any user
841          * options getting in the way.
842          */
843         AST_SIP_USER_OPTIONS_TRUNCATE_CHECK(exten);
844
845         /* Uri without exten */
846         if (ast_strlen_zero(exten)) {
847                 ast_copy_string(exten, "s", sizeof(exten));
848                 ast_debug(3, "Channel '%s' from endpoint '%s' attempted blind transfer to a target without extension. Target was set to 's@%s'\n",
849                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), context);
850         }
851
852         if (!ast_exists_extension(NULL, context, exten, 1, NULL)) {
853                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer to '%s@%s' but target does not exist\n",
854                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), exten, context);
855                 return 404;
856         }
857
858         refer.context = context;
859         refer.progress = progress;
860         refer.rdata = rdata;
861         refer.refer_to = target;
862         refer.attended = 0;
863
864         if (ast_sip_session_defer_termination(session)) {
865                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer but could not defer termination, rejecting\n",
866                         ast_channel_name(session->channel),
867                         ast_sorcery_object_get_id(session->endpoint));
868                 return 500;
869         }
870
871         response = xfer_response_code2sip(ast_bridge_transfer_blind(1, session->channel,
872                 exten, context, refer_blind_callback, &refer));
873
874         ast_sip_session_end_if_deferred(session);
875         if (response != 200) {
876                 ast_sip_session_defer_termination_cancel(session);
877         }
878
879         return response;
880 }
881
882 /*! \brief Structure used to retrieve channel from another session */
883 struct invite_replaces {
884         /*! \brief Session we want the channel from */
885         struct ast_sip_session *session;
886         /*! \brief Channel from the session (with reference) */
887         struct ast_channel *channel;
888         /*! \brief Bridge the channel is in */
889         struct ast_bridge *bridge;
890 };
891
892 /*! \brief Task for invite replaces */
893 static int invite_replaces(void *data)
894 {
895         struct invite_replaces *invite = data;
896
897         if (!invite->session->channel) {
898                 return -1;
899         }
900
901         ast_channel_ref(invite->session->channel);
902         invite->channel = invite->session->channel;
903
904         ast_channel_lock(invite->channel);
905         invite->bridge = ast_channel_get_bridge(invite->channel);
906         ast_channel_unlock(invite->channel);
907
908         return 0;
909 }
910
911 static int refer_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
912 {
913         pjsip_dialog *other_dlg = NULL;
914         pjsip_tx_data *packet;
915         int response = 0;
916         RAII_VAR(struct ast_sip_session *, other_session, NULL, ao2_cleanup);
917         struct invite_replaces invite;
918
919         /* If a Replaces header is present make sure it is valid */
920         if (pjsip_replaces_verify_request(rdata, &other_dlg, PJ_TRUE, &packet) != PJ_SUCCESS) {
921                 response = packet->msg->line.status.code;
922                 ast_assert(response != 0);
923                 pjsip_tx_data_dec_ref(packet);
924                 goto inv_replace_failed;
925         }
926
927         /* If no other dialog exists then this INVITE request does not have a Replaces header */
928         if (!other_dlg) {
929                 return 0;
930         }
931
932         other_session = ast_sip_dialog_get_session(other_dlg);
933         pjsip_dlg_dec_lock(other_dlg);
934
935         /* Don't accept an in-dialog INVITE with Replaces as it does not make much sense */
936         if (session->inv_session->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED) {
937                 response = 488;
938                 goto inv_replace_failed;
939         }
940
941         if (!other_session) {
942                 ast_debug(3, "INVITE with Replaces received on channel '%s' from endpoint '%s', but requested session does not exist\n",
943                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
944                 response = 481;
945                 goto inv_replace_failed;
946         }
947
948         invite.session = other_session;
949
950         if (ast_sip_push_task_synchronous(other_session->serializer, invite_replaces, &invite)) {
951                 response = 481;
952                 goto inv_replace_failed;
953         }
954
955         ast_channel_lock(session->channel);
956         ast_setstate(session->channel, AST_STATE_RING);
957         ast_channel_unlock(session->channel);
958         ast_raw_answer(session->channel);
959
960         ast_debug(3, "INVITE with Replaces being attempted.  '%s' --> '%s'\n",
961                 ast_channel_name(session->channel), ast_channel_name(invite.channel));
962
963         if (!invite.bridge) {
964                 struct ast_channel *chan = session->channel;
965
966                 /*
967                  * This will use a synchronous task but we aren't operating in
968                  * the serializer at this point in time, so it won't deadlock.
969                  */
970                 if (!ast_channel_move(invite.channel, chan)) {
971                         /*
972                          * We can't directly use session->channel because ast_channel_move()
973                          * does a masquerade which changes session->channel to a different
974                          * channel.  To ensure we work on the right channel we store a
975                          * pointer locally before we begin so it remains valid.
976                          */
977                         ast_hangup(chan);
978                 } else {
979                         response = AST_CAUSE_FAILURE;
980                 }
981         } else {
982                 if (ast_bridge_impart(invite.bridge, session->channel, invite.channel, NULL,
983                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
984                         response = AST_CAUSE_FAILURE;
985                 }
986         }
987
988         ast_channel_unref(invite.channel);
989         ao2_cleanup(invite.bridge);
990
991         if (!response) {
992                 /*
993                  * On success we cannot use session->channel in the debug message.
994                  * This thread either no longer has a ref to session->channel or
995                  * session->channel is no longer the original channel.
996                  */
997                 ast_debug(3, "INVITE with Replaces successfully completed.\n");
998         } else {
999                 ast_debug(3, "INVITE with Replaces failed on channel '%s', hanging up with cause '%d'\n",
1000                         ast_channel_name(session->channel), response);
1001                 ast_channel_lock(session->channel);
1002                 ast_channel_hangupcause_set(session->channel, response);
1003                 ast_channel_unlock(session->channel);
1004                 ast_hangup(session->channel);
1005         }
1006
1007         return 1;
1008
1009 inv_replace_failed:
1010         if (session->inv_session->dlg->state != PJSIP_DIALOG_STATE_ESTABLISHED) {
1011                 ast_debug(3, "INVITE with Replaces failed on channel '%s', sending response of '%d'\n",
1012                         ast_channel_name(session->channel), response);
1013                 session->defer_terminate = 1;
1014                 ast_hangup(session->channel);
1015
1016                 if (pjsip_inv_end_session(session->inv_session, response, NULL, &packet) == PJ_SUCCESS
1017                         && packet) {
1018                         ast_sip_session_send_response(session, packet);
1019                 }
1020         } else {
1021                 ast_debug(3, "INVITE with Replaces in-dialog on channel '%s', hanging up\n",
1022                         ast_channel_name(session->channel));
1023                 ast_queue_hangup(session->channel);
1024         }
1025
1026         return 1;
1027 }
1028
1029 static int refer_incoming_refer_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
1030 {
1031         pjsip_generic_string_hdr *refer_to;
1032         char *uri;
1033         size_t uri_size;
1034         pjsip_uri *target;
1035         pjsip_sip_uri *target_uri;
1036         RAII_VAR(struct refer_progress *, progress, NULL, ao2_cleanup);
1037         pjsip_param *replaces;
1038         int response;
1039
1040         static const pj_str_t str_refer_to = { "Refer-To", 8 };
1041         static const pj_str_t str_refer_to_s = { "r", 1 };
1042         static const pj_str_t str_replaces = { "Replaces", 8 };
1043
1044         if (!session->channel) {
1045                 /* No channel to refer.  Likely because the call was just hung up. */
1046                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 404, NULL, NULL, NULL);
1047                 ast_debug(3, "Received a REFER on a session with no channel from endpoint '%s'.\n",
1048                         ast_sorcery_object_get_id(session->endpoint));
1049                 return 0;
1050         }
1051
1052         if (!session->endpoint->allowtransfer) {
1053                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 603, NULL, NULL, NULL);
1054                 ast_log(LOG_WARNING, "Endpoint %s transfer attempt blocked due to configuration\n",
1055                                 ast_sorcery_object_get_id(session->endpoint));
1056                 return 0;
1057         }
1058
1059         /* A Refer-To header is required */
1060         refer_to = pjsip_msg_find_hdr_by_names(rdata->msg_info.msg, &str_refer_to, &str_refer_to_s, NULL);
1061         if (!refer_to) {
1062                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1063                 ast_debug(3, "Received a REFER without Refer-To on channel '%s' from endpoint '%s'\n",
1064                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1065                 return 0;
1066         }
1067
1068         /* The ast_copy_pj_str to uri is needed because it puts the NULL terminator to the uri
1069          * as pjsip_parse_uri require a NULL terminated uri
1070          */
1071
1072         uri_size = pj_strlen(&refer_to->hvalue) + 1;
1073         uri = ast_alloca(uri_size);
1074         ast_copy_pj_str(uri, &refer_to->hvalue, uri_size);
1075
1076         target = pjsip_parse_uri(rdata->tp_info.pool, uri, uri_size - 1, 0);
1077
1078         if (!target
1079                 || (!PJSIP_URI_SCHEME_IS_SIP(target)
1080                         && !PJSIP_URI_SCHEME_IS_SIPS(target))) {
1081
1082                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
1083                 ast_debug(3, "Received a REFER without a parseable Refer-To ('%s') on channel '%s' from endpoint '%s'\n",
1084                         uri, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1085                 return 0;
1086         }
1087         target_uri = pjsip_uri_get_uri(target);
1088
1089         /* Set up REFER progress subscription if requested/possible */
1090         if (refer_progress_alloc(session, rdata, &progress)) {
1091                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 500, NULL, NULL, NULL);
1092                 ast_debug(3, "Could not set up subscription for REFER on channel '%s' from endpoint '%s'\n",
1093                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
1094                 return 0;
1095         }
1096
1097         /* Determine if this is an attended or blind transfer */
1098         if ((replaces = pjsip_param_find(&target_uri->header_param, &str_replaces)) ||
1099                 (replaces = pjsip_param_find(&target_uri->other_param, &str_replaces))) {
1100                 response = refer_incoming_attended_request(session, rdata, target_uri, replaces, progress);
1101         } else {
1102                 response = refer_incoming_blind_request(session, rdata, target_uri, progress);
1103         }
1104
1105         if (!progress) {
1106                 /* The transferer has requested no subscription, so send a final response immediately */
1107                 pjsip_tx_data *tdata;
1108                 const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
1109                 const pj_str_t str_false = { "false", 5 };
1110                 pjsip_hdr *hdr;
1111
1112                 ast_debug(3, "Progress monitoring not requested for REFER on channel '%s' from endpoint '%s', sending immediate response of '%d'\n",
1113                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), response);
1114
1115                 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, response, NULL, &tdata) != PJ_SUCCESS) {
1116                         pjsip_dlg_respond(session->inv_session->dlg, rdata, response, NULL, NULL, NULL);
1117                         return 0;
1118                 }
1119
1120                 hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub, &str_false);
1121                 pjsip_msg_add_hdr(tdata->msg, hdr);
1122
1123                 pjsip_dlg_send_response(session->inv_session->dlg, pjsip_rdata_get_tsx(rdata), tdata);
1124         } else if (response != 200) {
1125                 /* Since this failed we can send a final NOTIFY now and terminate the subscription */
1126                 struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, response, PJSIP_EVSUB_STATE_TERMINATED);
1127
1128                 if (notification) {
1129                         /* The refer_progress_notify function will call ao2_cleanup on this for us */
1130                         refer_progress_notify(notification);
1131                 }
1132         }
1133
1134         return 0;
1135 }
1136
1137 static int refer_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
1138 {
1139         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_refer_method())) {
1140                 return refer_incoming_refer_request(session, rdata);
1141         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_invite_method)) {
1142                 return refer_incoming_invite_request(session, rdata);
1143         } else {
1144                 return 0;
1145         }
1146 }
1147
1148 /*!
1149  * \brief Use the value of a channel variable as the value of a SIP header
1150  *
1151  * This looks up a variable name on a channel, then takes that value and adds
1152  * it to an outgoing SIP request. If the header already exists on the message,
1153  * then no action is taken.
1154  *
1155  * \pre chan is locked.
1156  *
1157  * \param chan The channel on which to find the variable.
1158  * \param var_name The name of the channel variable to use.
1159  * \param header_name The name of the SIP header to add to the outgoing message.
1160  * \param tdata The outgoing SIP message on which to add the header
1161  */
1162 static void add_header_from_channel_var(struct ast_channel *chan, const char *var_name, const char *header_name, pjsip_tx_data *tdata)
1163 {
1164         const char *var_value;
1165         pj_str_t pj_header_name;
1166         pjsip_hdr *header;
1167
1168         var_value = pbx_builtin_getvar_helper(chan, var_name);
1169         if (ast_strlen_zero(var_value)) {
1170                 return;
1171         }
1172
1173         pj_cstr(&pj_header_name, header_name);
1174         header = pjsip_msg_find_hdr_by_name(tdata->msg, &pj_header_name, NULL);
1175         if (header) {
1176                 return;
1177         }
1178         ast_sip_add_header(tdata, header_name, var_value);
1179 }
1180
1181 static void refer_outgoing_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
1182 {
1183         if (pjsip_method_cmp(&tdata->msg->line.req.method, &pjsip_invite_method)
1184                 || !session->channel
1185                 || session->inv_session->state != PJSIP_INV_STATE_NULL) {
1186                 return;
1187         }
1188
1189         ast_channel_lock(session->channel);
1190         add_header_from_channel_var(session->channel, "SIPREPLACESHDR", "Replaces", tdata);
1191         add_header_from_channel_var(session->channel, "SIPREFERREDBYHDR", "Referred-By", tdata);
1192         ast_channel_unlock(session->channel);
1193 }
1194
1195 static struct ast_sip_session_supplement refer_supplement = {
1196         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
1197         .incoming_request = refer_incoming_request,
1198         .outgoing_request = refer_outgoing_request,
1199 };
1200
1201 static int load_module(void)
1202 {
1203         const pj_str_t str_norefersub = { "norefersub", 10 };
1204
1205         CHECK_PJSIP_SESSION_MODULE_LOADED();
1206
1207         pjsip_replaces_init_module(ast_sip_get_pjsip_endpoint());
1208         pjsip_xfer_init_module(ast_sip_get_pjsip_endpoint());
1209         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_SUPPORTED, NULL, 1, &str_norefersub);
1210
1211         ast_sip_register_service(&refer_progress_module);
1212         ast_sip_session_register_supplement(&refer_supplement);
1213
1214         return AST_MODULE_LOAD_SUCCESS;
1215 }
1216
1217 static int unload_module(void)
1218 {
1219         ast_sip_session_unregister_supplement(&refer_supplement);
1220         ast_sip_unregister_service(&refer_progress_module);
1221
1222         return 0;
1223 }
1224
1225 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Blind and Attended Transfer Support",
1226         .support_level = AST_MODULE_SUPPORT_CORE,
1227         .load = load_module,
1228         .unload = unload_module,
1229         .load_pri = AST_MODPRI_APP_DEPEND,
1230 );