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