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