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