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