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