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