security_events: Fix error caused by DTD validation error
[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         ast_debug(3, "Performing a REFER attended transfer - Transferer #1: %s Transferer #2: %s\n",
425                 ast_channel_name(attended->transferer_chan), ast_channel_name(attended->transferer_second->channel));
426
427         switch (ast_bridge_transfer_attended(attended->transferer_chan, attended->transferer_second->channel)) {
428         case AST_BRIDGE_TRANSFER_INVALID:
429                 response = 400;
430                 break;
431         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
432                 response = 403;
433                 break;
434         case AST_BRIDGE_TRANSFER_FAIL:
435                 response = 500;
436                 break;
437         case AST_BRIDGE_TRANSFER_SUCCESS:
438                 response = 200;
439                 ast_sip_session_defer_termination(attended->transferer);
440                 break;
441         }
442
443         ast_debug(3, "Final response for REFER attended transfer - Transferer #1: %s Transferer #2: %s is '%d'\n",
444                 ast_channel_name(attended->transferer_chan), ast_channel_name(attended->transferer_second->channel), response);
445
446         if (attended->progress && response) {
447                 struct refer_progress_notification *notification = refer_progress_notification_alloc(attended->progress, response, PJSIP_EVSUB_STATE_TERMINATED);
448
449                 if (notification) {
450                         refer_progress_notify(notification);
451                 }
452         }
453
454         return 0;
455 }
456
457 /*! \brief Structure for blind transfer callback details */
458 struct refer_blind {
459         /*! \brief Context being used for transfer */
460         const char *context;
461         /*! \brief Optional progress structure */
462         struct refer_progress *progress;
463         /*! \brief REFER message */
464         pjsip_rx_data *rdata;
465         /*! \brief Optional Replaces header */
466         pjsip_replaces_hdr *replaces;
467         /*! \brief Optional Refer-To header */
468         pjsip_sip_uri *refer_to;
469 };
470
471 /*! \brief Blind transfer callback function */
472 static void refer_blind_callback(struct ast_channel *chan, void *user_data, enum ast_transfer_type transfer_type)
473 {
474         struct refer_blind *refer = user_data;
475         const pj_str_t str_referred_by = { "Referred-By", 11 };
476         pjsip_generic_string_hdr *referred_by = pjsip_msg_find_hdr_by_name(refer->rdata->msg_info.msg, &str_referred_by, NULL);
477
478         pbx_builtin_setvar_helper(chan, "SIPTRANSFER", "yes");
479
480         /* If progress monitoring is being done attach a frame hook so we can monitor it */
481         if (refer->progress) {
482                 struct ast_framehook_interface hook = {
483                         .version = AST_FRAMEHOOK_INTERFACE_VERSION,
484                         .event_cb = refer_progress_framehook,
485                         .destroy_cb = refer_progress_framehook_destroy,
486                         .data = refer->progress,
487                 };
488
489                 refer->progress->transferee = ast_strdup(ast_channel_uniqueid(chan));
490                 if (!refer->progress->transferee) {
491                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
492                                 PJSIP_EVSUB_STATE_TERMINATED);
493
494                         ast_log(LOG_WARNING, "Could not copy channel name '%s' during transfer - assuming success\n",
495                                 ast_channel_name(chan));
496
497                         if (notification) {
498                                 refer_progress_notify(notification);
499                         }
500                 }
501
502                 /* We need to bump the reference count up on the progress structure since it is in the frame hook now */
503                 ao2_ref(refer->progress, +1);
504
505                 /* If we can't attach a frame hook for whatever reason send a notification of success immediately */
506                 if ((refer->progress->framehook = ast_framehook_attach(chan, &hook)) < 0) {
507                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
508                                 PJSIP_EVSUB_STATE_TERMINATED);
509
510                         ast_log(LOG_WARNING, "Could not attach REFER transfer progress monitoring hook to channel '%s' - assuming success\n",
511                                 ast_channel_name(chan));
512
513                         if (notification) {
514                                 refer_progress_notify(notification);
515                         }
516
517                         ao2_cleanup(refer->progress);
518                 }
519
520                 /* We need to bump the reference count for the stasis subscription */
521                 ao2_ref(refer->progress, +1);
522                 /* We also will need to detect if the transferee enters a bridge. This is currently the only reliable way to
523                  * detect if the transfer target has answered the call
524                  */
525                 refer->progress->bridge_sub = stasis_subscribe(ast_bridge_topic_all(), refer_progress_bridge, refer->progress);
526                 if (!refer->progress->bridge_sub) {
527                         struct refer_progress_notification *notification = refer_progress_notification_alloc(refer->progress, 200,
528                                 PJSIP_EVSUB_STATE_TERMINATED);
529
530                         ast_log(LOG_WARNING, "Could not create bridge stasis subscription for monitoring progress on transfer of channel '%s' - assuming success\n",
531                                         ast_channel_name(chan));
532
533                         if (notification) {
534                                 refer_progress_notify(notification);
535                         }
536
537                         ast_framehook_detach(chan, refer->progress->framehook);
538
539                         ao2_cleanup(refer->progress);
540                 }
541         }
542
543         if (!ast_strlen_zero(refer->context)) {
544                 pbx_builtin_setvar_helper(chan, "SIPREFERRINGCONTEXT", refer->context);
545         }
546
547         if (referred_by) {
548                 char *uri = referred_by->hvalue.ptr;
549
550                 uri[referred_by->hvalue.slen] = '\0';
551                 pbx_builtin_setvar_helper(chan, "SIPREFERREDBYHDR", uri);
552         }
553
554         if (refer->replaces) {
555                 char replaces[512];
556
557                 pjsip_hdr_print_on(refer->replaces, replaces, sizeof(replaces));
558                 pbx_builtin_setvar_helper(chan, "SIPREPLACESHDR", replaces);
559         }
560
561         if (refer->refer_to) {
562                 char refer_to[PJSIP_MAX_URL_SIZE];
563
564                 pjsip_uri_print(PJSIP_URI_IN_REQ_URI, refer->refer_to, refer_to, sizeof(refer_to));
565                 pbx_builtin_setvar_helper(chan, "SIPREFERTOHDR", refer_to);
566         }
567 }
568
569 static int refer_incoming_attended_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target_uri,
570         pjsip_param *replaces_param, struct refer_progress *progress)
571 {
572         const pj_str_t str_replaces = { "Replaces", 8 };
573         pj_str_t replaces_content;
574         pjsip_replaces_hdr *replaces;
575         int parsed_len;
576         pjsip_dialog *dlg;
577
578         pj_strdup_with_null(rdata->tp_info.pool, &replaces_content, &replaces_param->value);
579
580         /* Parsing the parameter as a Replaces header easily grabs the needed information */
581         if (!(replaces = pjsip_parse_hdr(rdata->tp_info.pool, &str_replaces, replaces_content.ptr,
582                 pj_strlen(&replaces_content), &parsed_len))) {
583                 ast_log(LOG_ERROR, "Received REFER request on channel '%s' from endpoint '%s' with invalid Replaces header, rejecting\n",
584                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
585                 return 400;
586         }
587
588         /* See if the dialog is local, or remote */
589         if ((dlg = pjsip_ua_find_dialog(&replaces->call_id, &replaces->to_tag, &replaces->from_tag, PJ_TRUE))) {
590                 RAII_VAR(struct ast_sip_session *, other_session, ast_sip_dialog_get_session(dlg), ao2_cleanup);
591                 struct refer_attended *attended;
592
593                 pjsip_dlg_dec_lock(dlg);
594
595                 if (!other_session) {
596                         ast_debug(3, "Received REFER request on channel '%s' from endpoint '%s' for local dialog but no session exists on it\n",
597                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
598                         return 603;
599                 }
600
601                 /* We defer actually doing the attended transfer to the other session so no deadlock can occur */
602                 if (!(attended = refer_attended_alloc(session, other_session, progress))) {
603                         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",
604                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
605                         return 500;
606                 }
607
608                 /* Push it to the other session, which will have both channels with minimal locking */
609                 if (ast_sip_push_task(other_session->serializer, refer_attended, attended)) {
610                         ao2_cleanup(attended);
611                         return 500;
612                 }
613
614                 ast_debug(3, "Attended transfer from '%s' pushed to second channel serializer\n",
615                         ast_channel_name(session->channel));
616
617                 return 200;
618         } else {
619                 const char *context = (session->channel ? pbx_builtin_getvar_helper(session->channel, "TRANSFER_CONTEXT") : "");
620                 struct refer_blind refer = { 0, };
621
622                 if (ast_strlen_zero(context)) {
623                         context = session->endpoint->context;
624                 }
625
626                 if (!ast_exists_extension(NULL, context, "external_replaces", 1, NULL)) {
627                         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",
628                                 ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
629                         return 404;
630                 }
631
632                 refer.context = context;
633                 refer.progress = progress;
634                 refer.rdata = rdata;
635                 refer.replaces = replaces;
636                 refer.refer_to = target_uri;
637
638                 switch (ast_bridge_transfer_blind(1, session->channel, "external_replaces", context, refer_blind_callback, &refer)) {
639                 case AST_BRIDGE_TRANSFER_INVALID:
640                         return 400;
641                 case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
642                         return 403;
643                 case AST_BRIDGE_TRANSFER_FAIL:
644                         return 500;
645                 case AST_BRIDGE_TRANSFER_SUCCESS:
646                         ast_sip_session_defer_termination(session);
647                         return 200;
648                 }
649
650                 return 503;
651         }
652
653         return 0;
654 }
655
656 static int refer_incoming_blind_request(struct ast_sip_session *session, pjsip_rx_data *rdata, pjsip_sip_uri *target,
657         struct refer_progress *progress)
658 {
659         const char *context = (session->channel ? pbx_builtin_getvar_helper(session->channel, "TRANSFER_CONTEXT") : "");
660         char exten[AST_MAX_EXTENSION];
661         struct refer_blind refer = { 0, };
662
663         /* If no explicit transfer context has been provided use their configured context */
664         if (ast_strlen_zero(context)) {
665                 context = session->endpoint->context;
666         }
667
668         /* Using the user portion of the target URI see if it exists as a valid extension in their context */
669         ast_copy_pj_str(exten, &target->user, sizeof(exten));
670         if (!ast_exists_extension(NULL, context, exten, 1, NULL)) {
671                 ast_log(LOG_ERROR, "Channel '%s' from endpoint '%s' attempted blind transfer to '%s@%s' but target does not exist\n",
672                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), exten, context);
673                 return 404;
674         }
675
676         refer.context = context;
677         refer.progress = progress;
678         refer.rdata = rdata;
679
680         switch (ast_bridge_transfer_blind(1, session->channel, exten, context, refer_blind_callback, &refer)) {
681         case AST_BRIDGE_TRANSFER_INVALID:
682                 return 400;
683         case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
684                 return 403;
685         case AST_BRIDGE_TRANSFER_FAIL:
686                 return 500;
687         case AST_BRIDGE_TRANSFER_SUCCESS:
688                 ast_sip_session_defer_termination(session);
689                 return 200;
690         }
691
692         return 503;
693 }
694
695 /*! \brief Structure used to retrieve channel from another session */
696 struct invite_replaces {
697         /*! \brief Session we want the channel from */
698         struct ast_sip_session *session;
699         /*! \brief Channel from the session (with reference) */
700         struct ast_channel *channel;
701         /*! \brief Bridge the channel is in */
702         struct ast_bridge *bridge;
703 };
704
705 /*! \brief Task for invite replaces */
706 static int invite_replaces(void *data)
707 {
708         struct invite_replaces *invite = data;
709
710         if (!invite->session->channel) {
711                 return -1;
712         }
713
714         ast_channel_ref(invite->session->channel);
715         invite->channel = invite->session->channel;
716
717         ast_channel_lock(invite->channel);
718         invite->bridge = ast_channel_get_bridge(invite->channel);
719         ast_channel_unlock(invite->channel);
720
721         return 0;
722 }
723
724 static int refer_incoming_invite_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
725 {
726         pjsip_dialog *other_dlg = NULL;
727         pjsip_tx_data *packet;
728         int response = 0;
729         RAII_VAR(struct ast_sip_session *, other_session, NULL, ao2_cleanup);
730         struct invite_replaces invite;
731         RAII_VAR(struct ast_bridge *, bridge, NULL, ao2_cleanup);
732
733         /* If a Replaces header is present make sure it is valid */
734         if (pjsip_replaces_verify_request(rdata, &other_dlg, PJ_TRUE, &packet) != PJ_SUCCESS) {
735                 response = packet->msg->line.status.code;
736                 pjsip_tx_data_dec_ref(packet);
737                 goto end;
738         }
739
740         /* If no other dialog exists then this INVITE request does not have a Replaces header */
741         if (!other_dlg) {
742                 return 0;
743         }
744
745         other_session = ast_sip_dialog_get_session(other_dlg);
746         pjsip_dlg_dec_lock(other_dlg);
747
748         if (!other_session) {
749                 response = 481;
750                 ast_debug(3, "INVITE with Replaces received on channel '%s' from endpoint '%s', but requested session does not exist\n",
751                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
752                 goto end;
753         }
754
755         invite.session = other_session;
756
757         if (ast_sip_push_task_synchronous(other_session->serializer, invite_replaces, &invite)) {
758                 response = 481;
759                 goto end;
760         }
761
762         ast_channel_lock(session->channel);
763         ast_setstate(session->channel, AST_STATE_RING);
764         ast_channel_unlock(session->channel);
765         ast_raw_answer(session->channel);
766
767         if (!invite.bridge) {
768                 struct ast_channel *chan = session->channel;
769
770                 /* This will use a synchronous task but we aren't operating in the serializer at this point in time, so it
771                  * won't deadlock */
772                 if (!ast_channel_move(invite.channel, session->channel)) {
773                         ast_hangup(chan);
774                 } else {
775                         response = 500;
776                 }
777         } else {
778                 if (ast_bridge_impart(invite.bridge, session->channel, invite.channel, NULL,
779                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
780                         response = 500;
781                 }
782         }
783
784         if (!response) {
785                 ast_debug(3, "INVITE with Replaces successfully completed on channels '%s' and '%s'\n",
786                         ast_channel_name(session->channel), ast_channel_name(invite.channel));
787         }
788
789         ast_channel_unref(invite.channel);
790         ao2_cleanup(invite.bridge);
791
792 end:
793         if (response) {
794                 ast_debug(3, "INVITE with Replaces failed on channel '%s', sending response of '%d'\n",
795                         ast_channel_name(session->channel), response);
796                 session->defer_terminate = 1;
797                 ast_hangup(session->channel);
798                 session->channel = NULL;
799
800                 if (pjsip_inv_end_session(session->inv_session, response, NULL, &packet) == PJ_SUCCESS) {
801                         ast_sip_session_send_response(session, packet);
802                 }
803         }
804
805         return 1;
806 }
807
808 static int refer_incoming_refer_request(struct ast_sip_session *session, struct pjsip_rx_data *rdata)
809 {
810         const pj_str_t str_refer_to = { "Refer-To", 8 };
811         pjsip_generic_string_hdr *refer_to;
812         char *uri;
813         const pj_str_t str_to = { "To", 2 };
814         pjsip_fromto_hdr *target;
815         pjsip_sip_uri *target_uri;
816         RAII_VAR(struct refer_progress *, progress, NULL, ao2_cleanup);
817         const pj_str_t str_replaces = { "Replaces", 8 };
818         pjsip_param *replaces;
819         int response;
820
821         if (!session->endpoint->allowtransfer) {
822                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 603, NULL, NULL, NULL);
823                 ast_log(LOG_WARNING, "Endpoint %s transfer attempt blocked due to configuration\n",
824                                 ast_sorcery_object_get_id(session->endpoint));
825                 return 0;
826         }
827
828         /* A Refer-To header is required */
829         if (!(refer_to = pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &str_refer_to, NULL))) {
830                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
831                 ast_debug(3, "Received a REFER without Refer-To on channel '%s' from endpoint '%s'\n",
832                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
833                 return 0;
834         }
835         uri = refer_to->hvalue.ptr;
836         uri[refer_to->hvalue.slen] = '\0';
837
838         /* Parse the provided URI string as a To header so we can get the target */
839         if (!(target = pjsip_parse_hdr(rdata->tp_info.pool, &str_to, refer_to->hvalue.ptr, refer_to->hvalue.slen, NULL)) ||
840                 (!PJSIP_URI_SCHEME_IS_SIP(target->uri) && !PJSIP_URI_SCHEME_IS_SIPS(target->uri))) {
841                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 400, NULL, NULL, NULL);
842                 ast_debug(3, "Received a REFER without a parseable Refer-To ('%s') on channel '%s' from endpoint '%s'\n",
843                         uri, ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
844                 return 0;
845         }
846         target_uri = pjsip_uri_get_uri(target->uri);
847
848         /* Set up REFER progress subscription if requested/possible */
849         if (refer_progress_alloc(session, rdata, &progress)) {
850                 pjsip_dlg_respond(session->inv_session->dlg, rdata, 500, NULL, NULL, NULL);
851                 ast_debug(3, "Could not set up subscription for REFER on channel '%s' from endpoint '%s'\n",
852                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint));
853                 return 0;
854         }
855
856         /* Determine if this is an attended or blind transfer */
857         if ((replaces = pjsip_param_find(&target_uri->header_param, &str_replaces)) ||
858                 (replaces = pjsip_param_find(&target_uri->other_param, &str_replaces))) {
859                 response = refer_incoming_attended_request(session, rdata, target_uri, replaces, progress);
860         } else {
861                 response = refer_incoming_blind_request(session, rdata, target_uri, progress);
862         }
863
864         if (!progress) {
865                 /* The transferer has requested no subscription, so send a final response immediately */
866                 pjsip_tx_data *tdata;
867                 const pj_str_t str_refer_sub = { "Refer-Sub", 9 };
868                 const pj_str_t str_false = { "false", 5 };
869                 pjsip_hdr *hdr;
870
871                 ast_debug(3, "Progress monitoring not requested for REFER on channel '%s' from endpoint '%s', sending immediate response of '%d'\n",
872                         ast_channel_name(session->channel), ast_sorcery_object_get_id(session->endpoint), response);
873
874                 if (pjsip_dlg_create_response(session->inv_session->dlg, rdata, response, NULL, &tdata) != PJ_SUCCESS) {
875                         pjsip_dlg_respond(session->inv_session->dlg, rdata, response, NULL, NULL, NULL);
876                         return 0;
877                 }
878
879                 hdr = (pjsip_hdr*)pjsip_generic_string_hdr_create(tdata->pool, &str_refer_sub, &str_false);
880                 pjsip_msg_add_hdr(tdata->msg, hdr);
881
882                 pjsip_dlg_send_response(session->inv_session->dlg, pjsip_rdata_get_tsx(rdata), tdata);
883         } else if (response != 200) {
884                 /* Since this failed we can send a final NOTIFY now and terminate the subscription */
885                 struct refer_progress_notification *notification = refer_progress_notification_alloc(progress, response, PJSIP_EVSUB_STATE_TERMINATED);
886
887                 if (notification) {
888                         /* The refer_progress_notify function will call ao2_cleanup on this for us */
889                         refer_progress_notify(notification);
890                 }
891         }
892
893         return 0;
894 }
895
896 static int refer_incoming_request(struct ast_sip_session *session, pjsip_rx_data *rdata)
897 {
898         if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, pjsip_get_refer_method())) {
899                 return refer_incoming_refer_request(session, rdata);
900         } else if (!pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, &pjsip_invite_method)) {
901                 return refer_incoming_invite_request(session, rdata);
902         } else {
903                 return 0;
904         }
905 }
906
907 static void refer_outgoing_request(struct ast_sip_session *session, struct pjsip_tx_data *tdata)
908 {
909         const char *replaces;
910
911         if (pjsip_method_cmp(&tdata->msg->line.req.method, &pjsip_invite_method) ||
912                 !session->channel ||
913                 (session->inv_session->state != PJSIP_INV_STATE_CALLING) ||
914                 !(replaces = pbx_builtin_getvar_helper(session->channel, "SIPREPLACESHDR"))) {
915                 return;
916         }
917
918         ast_sip_add_header(tdata, "Replaces", replaces);
919 }
920
921 static struct ast_sip_session_supplement refer_supplement = {
922         .priority = AST_SIP_SUPPLEMENT_PRIORITY_CHANNEL + 1,
923         .incoming_request = refer_incoming_request,
924         .outgoing_request = refer_outgoing_request,
925 };
926
927 static int load_module(void)
928 {
929         const pj_str_t str_norefersub = { "norefersub", 10 };
930
931         pjsip_replaces_init_module(ast_sip_get_pjsip_endpoint());
932         pjsip_xfer_init_module(ast_sip_get_pjsip_endpoint());
933         pjsip_endpt_add_capability(ast_sip_get_pjsip_endpoint(), NULL, PJSIP_H_SUPPORTED, NULL, 1, &str_norefersub);
934
935         ast_sip_register_service(&refer_progress_module);
936         ast_sip_session_register_supplement(&refer_supplement);
937
938         return AST_MODULE_LOAD_SUCCESS;
939 }
940
941 static int unload_module(void)
942 {
943         ast_sip_session_unregister_supplement(&refer_supplement);
944         ast_sip_unregister_service(&refer_progress_module);
945
946         return 0;
947 }
948
949 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "PJSIP Blind and Attended Transfer Support",
950                 .load = load_module,
951                 .unload = unload_module,
952                 .load_pri = AST_MODPRI_APP_DEPEND,
953                    );