diff options
author | David M. Lee <dlee@digium.com> | 2013-01-07 14:24:28 -0600 |
---|---|---|
committer | David M. Lee <dlee@digium.com> | 2013-01-07 14:24:28 -0600 |
commit | f3ab456a17af1c89a6e3be4d20c5944853df1cb0 (patch) | |
tree | d00e1a332cd038a6d906a1ea0ac91e1a4458e617 /pjsip/src/pjsip-ua |
Import pjproject-2.0.1
Diffstat (limited to 'pjsip/src/pjsip-ua')
-rw-r--r-- | pjsip/src/pjsip-ua/sip_100rel.c | 905 | ||||
-rw-r--r-- | pjsip/src/pjsip-ua/sip_inv.c | 4491 | ||||
-rw-r--r-- | pjsip/src/pjsip-ua/sip_reg.c | 1333 | ||||
-rw-r--r-- | pjsip/src/pjsip-ua/sip_replaces.c | 384 | ||||
-rw-r--r-- | pjsip/src/pjsip-ua/sip_timer.c | 1062 | ||||
-rw-r--r-- | pjsip/src/pjsip-ua/sip_xfer.c | 630 |
6 files changed, 8805 insertions, 0 deletions
diff --git a/pjsip/src/pjsip-ua/sip_100rel.c b/pjsip/src/pjsip-ua/sip_100rel.c new file mode 100644 index 0000000..07122c4 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_100rel.c @@ -0,0 +1,905 @@ +/* $Id: sip_100rel.c 3841 2011-10-24 09:28:13Z ming $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_100rel.h> +#include <pjsip/sip_endpoint.h> +#include <pjsip/sip_event.h> +#include <pjsip/sip_module.h> +#include <pjsip/sip_transaction.h> +#include <pj/assert.h> +#include <pj/ctype.h> +#include <pj/log.h> +#include <pj/os.h> +#include <pj/pool.h> +#include <pj/rand.h> +#include <pj/string.h> + +#define THIS_FILE "sip_100rel.c" + +/* PRACK method */ +PJ_DEF_DATA(const pjsip_method) pjsip_prack_method = +{ + PJSIP_OTHER_METHOD, + { "PRACK", 5 } +}; + +typedef struct dlg_data dlg_data; + +/* + * Static prototypes. + */ +static pj_status_t mod_100rel_load(pjsip_endpoint *endpt); + +static void on_retransmit(pj_timer_heap_t *timer_heap, + struct pj_timer_entry *entry); + + +const pj_str_t tag_100rel = { "100rel", 6 }; +const pj_str_t RSEQ = { "RSeq", 4 }; +const pj_str_t RACK = { "RAck", 4 }; + + +/* 100rel module */ +static struct mod_100rel +{ + pjsip_module mod; + pjsip_endpoint *endpt; +} mod_100rel = +{ + { + NULL, NULL, /* prev, next. */ + { "mod-100rel", 10 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + &mod_100rel_load, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ + } + +}; + +/* List of pending transmission (may include the final response as well) */ +typedef struct tx_data_list_t +{ + PJ_DECL_LIST_MEMBER(struct tx_data_list_t); + pj_uint32_t rseq; + pjsip_tx_data *tdata; +} tx_data_list_t; + + +/* Below, UAS and UAC roles are of the INVITE transaction */ + +/* UAS state. */ +typedef struct uas_state_t +{ + pj_int32_t cseq; + pj_uint32_t rseq; /* Initialized to -1 */ + tx_data_list_t tx_data_list; + unsigned retransmit_count; + pj_timer_entry retransmit_timer; +} uas_state_t; + + +/* UAC state */ +typedef struct uac_state_t +{ + pj_str_t tag; /* To tag */ + pj_int32_t cseq; + pj_uint32_t rseq; /* Initialized to -1 */ + struct uac_state_t *next; /* next call leg */ +} uac_state_t; + + +/* State attached to each dialog. */ +struct dlg_data +{ + pjsip_inv_session *inv; + uas_state_t *uas_state; + uac_state_t *uac_state_list; +}; + + +/***************************************************************************** + ** + ** Module + ** + ***************************************************************************** + */ +static pj_status_t mod_100rel_load(pjsip_endpoint *endpt) +{ + mod_100rel.endpt = endpt; + pjsip_endpt_add_capability(endpt, &mod_100rel.mod, + PJSIP_H_ALLOW, NULL, + 1, &pjsip_prack_method.name); + pjsip_endpt_add_capability(endpt, &mod_100rel.mod, + PJSIP_H_SUPPORTED, NULL, + 1, &tag_100rel); + + return PJ_SUCCESS; +} + +static pjsip_require_hdr *find_req_hdr(pjsip_msg *msg) +{ + pjsip_require_hdr *hreq; + + hreq = (pjsip_require_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); + + while (hreq) { + unsigned i; + for (i=0; i<hreq->count; ++i) { + if (!pj_stricmp(&hreq->values[i], &tag_100rel)) { + return hreq; + } + } + + if ((void*)hreq->next == (void*)&msg->hdr) + return NULL; + + hreq = (pjsip_require_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, hreq->next); + + } + + return NULL; +} + + +/* + * Get PRACK method constant. + */ +PJ_DEF(const pjsip_method*) pjsip_get_prack_method(void) +{ + return &pjsip_prack_method; +} + + +/* + * init module + */ +PJ_DEF(pj_status_t) pjsip_100rel_init_module(pjsip_endpoint *endpt) +{ + if (mod_100rel.mod.id != -1) + return PJ_SUCCESS; + + return pjsip_endpt_register_module(endpt, &mod_100rel.mod); +} + + +/* + * API: attach 100rel support in invite session. Called by + * sip_inv.c + */ +PJ_DEF(pj_status_t) pjsip_100rel_attach(pjsip_inv_session *inv) +{ + dlg_data *dd; + + /* Check that 100rel module has been initialized */ + PJ_ASSERT_RETURN(mod_100rel.mod.id >= 0, PJ_EINVALIDOP); + + /* Create and attach as dialog usage */ + dd = PJ_POOL_ZALLOC_T(inv->dlg->pool, dlg_data); + dd->inv = inv; + pjsip_dlg_add_usage(inv->dlg, &mod_100rel.mod, (void*)dd); + + PJ_LOG(5,(dd->inv->dlg->obj_name, "100rel module attached")); + + return PJ_SUCCESS; +} + + +/* + * Check if incoming response has reliable provisional response feature. + */ +PJ_DEF(pj_bool_t) pjsip_100rel_is_reliable(pjsip_rx_data *rdata) +{ + pjsip_msg *msg = rdata->msg_info.msg; + + PJ_ASSERT_RETURN(msg->type == PJSIP_RESPONSE_MSG, PJ_FALSE); + + return msg->line.status.code > 100 && msg->line.status.code < 200 && + rdata->msg_info.require != NULL && + find_req_hdr(msg) != NULL; +} + + +/* + * Create PRACK request for the incoming reliable provisional response. + */ +PJ_DEF(pj_status_t) pjsip_100rel_create_prack( pjsip_inv_session *inv, + pjsip_rx_data *rdata, + pjsip_tx_data **p_tdata) +{ + dlg_data *dd; + uac_state_t *uac_state = NULL; + const pj_str_t *to_tag = &rdata->msg_info.to->tag; + pjsip_transaction *tsx; + pjsip_msg *msg; + pjsip_generic_string_hdr *rseq_hdr; + pjsip_generic_string_hdr *rack_hdr; + unsigned rseq; + pj_str_t rack; + char rack_buf[80]; + pjsip_tx_data *tdata; + pj_status_t status; + + *p_tdata = NULL; + + dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; + PJ_ASSERT_RETURN(dd != NULL, PJSIP_ENOTINITIALIZED); + + tsx = pjsip_rdata_get_tsx(rdata); + msg = rdata->msg_info.msg; + + /* Check our assumptions */ + pj_assert( tsx->role == PJSIP_ROLE_UAC && + tsx->method.id == PJSIP_INVITE_METHOD && + msg->line.status.code > 100 && + msg->line.status.code < 200); + + + /* Get the RSeq header */ + rseq_hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(msg, &RSEQ, NULL); + if (rseq_hdr == NULL) { + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response with no RSeq header")); + return PJSIP_EMISSINGHDR; + } + rseq = (pj_uint32_t) pj_strtoul(&rseq_hdr->hvalue); + + /* Find UAC state for the specified call leg */ + uac_state = dd->uac_state_list; + while (uac_state) { + if (pj_strcmp(&uac_state->tag, to_tag)==0) + break; + uac_state = uac_state->next; + } + + /* Create new UAC state if we don't have one */ + if (uac_state == NULL) { + uac_state = PJ_POOL_ZALLOC_T(dd->inv->dlg->pool, uac_state_t); + uac_state->cseq = rdata->msg_info.cseq->cseq; + uac_state->rseq = rseq - 1; + pj_strdup(dd->inv->dlg->pool, &uac_state->tag, to_tag); + uac_state->next = dd->uac_state_list; + dd->uac_state_list = uac_state; + } + + /* If this is from new INVITE transaction, reset UAC state. */ + if (rdata->msg_info.cseq->cseq != uac_state->cseq) { + uac_state->cseq = rdata->msg_info.cseq->cseq; + uac_state->rseq = rseq - 1; + } + + /* Ignore provisional response retransmission */ + if (rseq <= uac_state->rseq) { + /* This should have been handled before */ + return PJ_EIGNORED; + + /* Ignore provisional response with out-of-order RSeq */ + } else if (rseq != uac_state->rseq + 1) { + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response because RSeq jump " + "(expecting %u, got %u)", + uac_state->rseq+1, rseq)); + return PJ_EIGNORED; + } + + /* Update our RSeq */ + uac_state->rseq = rseq; + + /* Create PRACK */ + status = pjsip_dlg_create_request(dd->inv->dlg, &pjsip_prack_method, + -1, &tdata); + if (status != PJ_SUCCESS) + return status; + + /* If this response is a forked response from a different call-leg, + * update the req URI (https://trac.pjsip.org/repos/ticket/1364) + */ + if (pj_strcmp(&uac_state->tag, &dd->inv->dlg->remote.info->tag)) { + const pjsip_contact_hdr *mhdr; + + mhdr = (const pjsip_contact_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_CONTACT, NULL); + if (!mhdr || !mhdr->uri) { + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Ignoring 100rel response with no or " + "invalid Contact header")); + pjsip_tx_data_dec_ref(tdata); + return PJ_EIGNORED; + } + tdata->msg->line.req.uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, mhdr->uri); + } + + /* Create RAck header */ + rack.ptr = rack_buf; + rack.slen = pj_ansi_snprintf(rack.ptr, sizeof(rack_buf), + "%u %u %.*s", + rseq, rdata->msg_info.cseq->cseq, + (int)tsx->method.name.slen, + tsx->method.name.ptr); + rack_hdr = pjsip_generic_string_hdr_create(tdata->pool, &RACK, &rack); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) rack_hdr); + + /* Done */ + *p_tdata = tdata; + + return PJ_SUCCESS; +} + + +/* + * Send PRACK request. + */ +PJ_DEF(pj_status_t) pjsip_100rel_send_prack( pjsip_inv_session *inv, + pjsip_tx_data *tdata) +{ + dlg_data *dd; + + dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; + PJ_ASSERT_ON_FAIL(dd != NULL, + {pjsip_tx_data_dec_ref(tdata); return PJSIP_ENOTINITIALIZED; }); + + return pjsip_dlg_send_request(inv->dlg, tdata, + mod_100rel.mod.id, (void*) dd); + +} + + +/* + * Notify 100rel module that the invite session has been disconnected. + */ +PJ_DEF(pj_status_t) pjsip_100rel_end_session(pjsip_inv_session *inv) +{ + dlg_data *dd; + + dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; + if (!dd) + return PJ_SUCCESS; + + /* Make sure we don't have pending transmission */ + if (dd->uas_state) { + pj_assert(!dd->uas_state->retransmit_timer.id); + pj_assert(pj_list_empty(&dd->uas_state->tx_data_list)); + } + + return PJ_SUCCESS; +} + + +static void parse_rack(const pj_str_t *rack, + pj_uint32_t *p_rseq, pj_int32_t *p_seq, + pj_str_t *p_method) +{ + const char *p = rack->ptr, *end = p + rack->slen; + pj_str_t token; + + token.ptr = (char*)p; + while (p < end && pj_isdigit(*p)) + ++p; + token.slen = p - token.ptr; + *p_rseq = pj_strtoul(&token); + + ++p; + token.ptr = (char*)p; + while (p < end && pj_isdigit(*p)) + ++p; + token.slen = p - token.ptr; + *p_seq = pj_strtoul(&token); + + ++p; + if (p < end) { + p_method->ptr = (char*)p; + p_method->slen = end - p; + } else { + p_method->ptr = NULL; + p_method->slen = 0; + } +} + +/* Clear all responses in the transmission list */ +static void clear_all_responses(dlg_data *dd) +{ + tx_data_list_t *tl; + + tl = dd->uas_state->tx_data_list.next; + while (tl != &dd->uas_state->tx_data_list) { + pjsip_tx_data_dec_ref(tl->tdata); + tl = tl->next; + } + pj_list_init(&dd->uas_state->tx_data_list); +} + + +/* + * Handle incoming PRACK request. + */ +PJ_DEF(pj_status_t) pjsip_100rel_on_rx_prack( pjsip_inv_session *inv, + pjsip_rx_data *rdata) +{ + dlg_data *dd; + pjsip_transaction *tsx; + pjsip_msg *msg; + pjsip_generic_string_hdr *rack_hdr; + pjsip_tx_data *tdata; + pj_uint32_t rseq; + pj_int32_t cseq; + pj_str_t method; + pj_status_t status; + + tsx = pjsip_rdata_get_tsx(rdata); + pj_assert(tsx != NULL); + + msg = rdata->msg_info.msg; + + dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; + if (dd == NULL) { + /* UAC sends us PRACK while we didn't send reliable provisional + * response. Respond with 400 (?) + */ + const pj_str_t reason = pj_str("Unexpected PRACK"); + + status = pjsip_dlg_create_response(inv->dlg, rdata, 400, + &reason, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); + } + return PJSIP_ENOTINITIALIZED; + } + + /* Always reply with 200/OK for PRACK */ + status = pjsip_dlg_create_response(inv->dlg, rdata, 200, NULL, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_dlg_send_response(inv->dlg, tsx, tdata); + } + + /* Ignore if we don't have pending transmission */ + if (dd->uas_state == NULL || pj_list_empty(&dd->uas_state->tx_data_list)) { + PJ_LOG(4,(dd->inv->dlg->obj_name, + "PRACK ignored - no pending response")); + return PJ_EIGNORED; + } + + /* Find RAck header */ + rack_hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(msg, &RACK, NULL); + if (!rack_hdr) { + /* RAck header not found */ + PJ_LOG(4,(dd->inv->dlg->obj_name, "No RAck header")); + return PJSIP_EMISSINGHDR; + } + + /* Parse RAck header */ + parse_rack(&rack_hdr->hvalue, &rseq, &cseq, &method); + + + /* Match RAck against outgoing transmission */ + if (rseq == dd->uas_state->tx_data_list.next->rseq && + cseq == dd->uas_state->cseq) + { + /* + * Yes this PRACK matches outgoing transmission. + */ + tx_data_list_t *tl = dd->uas_state->tx_data_list.next; + + if (dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + } + + /* Remove from the list */ + if (tl != &dd->uas_state->tx_data_list) { + pj_list_erase(tl); + + /* Destroy the response */ + pjsip_tx_data_dec_ref(tl->tdata); + } + + /* Schedule next packet */ + dd->uas_state->retransmit_count = 0; + if (!pj_list_empty(&dd->uas_state->tx_data_list)) { + on_retransmit(NULL, &dd->uas_state->retransmit_timer); + } + + } else { + /* No it doesn't match */ + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Rx PRACK with no matching reliable response")); + return PJ_EIGNORED; + } + + return PJ_SUCCESS; +} + + +/* + * This is retransmit timer callback, called initially to send the response, + * and subsequently when the retransmission time elapses. + */ +static void on_retransmit(pj_timer_heap_t *timer_heap, + struct pj_timer_entry *entry) +{ + dlg_data *dd; + tx_data_list_t *tl; + pjsip_tx_data *tdata; + pj_bool_t final; + pj_time_val delay; + + PJ_UNUSED_ARG(timer_heap); + + dd = (dlg_data*) entry->user_data; + + entry->id = PJ_FALSE; + + ++dd->uas_state->retransmit_count; + if (dd->uas_state->retransmit_count >= 7) { + /* If a reliable provisional response is retransmitted for + 64*T1 seconds without reception of a corresponding PRACK, + the UAS SHOULD reject the original request with a 5xx + response. + */ + pj_str_t reason = pj_str("Reliable response timed out"); + pj_status_t status; + + /* Clear all pending responses */ + clear_all_responses(dd); + + /* Send 500 response */ + status = pjsip_inv_end_session(dd->inv, 500, &reason, &tdata); + if (status == PJ_SUCCESS) { + pjsip_dlg_send_response(dd->inv->dlg, + dd->inv->invite_tsx, + tdata); + } + return; + } + + pj_assert(!pj_list_empty(&dd->uas_state->tx_data_list)); + tl = dd->uas_state->tx_data_list.next; + tdata = tl->tdata; + + pjsip_tx_data_add_ref(tdata); + final = tdata->msg->line.status.code >= 200; + + if (dd->uas_state->retransmit_count == 1) { + pjsip_tsx_send_msg(dd->inv->invite_tsx, tdata); + } else { + pjsip_tsx_retransmit_no_state(dd->inv->invite_tsx, tdata); + } + + if (final) { + /* This is final response, which will be retransmitted by + * UA layer. There's no more task to do, so clear the + * transmission list and bail out. + */ + clear_all_responses(dd); + return; + } + + /* Schedule next retransmission */ + if (dd->uas_state->retransmit_count < 6) { + delay.sec = 0; + delay.msec = (1 << dd->uas_state->retransmit_count) * + pjsip_cfg()->tsx.t1; + pj_time_val_normalize(&delay); + } else { + delay.sec = 1; + delay.msec = 500; + } + + + pjsip_endpt_schedule_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer, + &delay); + + entry->id = PJ_TRUE; +} + + +/* Clone response. */ +static pjsip_tx_data *clone_tdata(dlg_data *dd, + const pjsip_tx_data *src) +{ + pjsip_tx_data *dst; + const pjsip_hdr *hsrc; + pjsip_msg *msg; + pj_status_t status; + + status = pjsip_endpt_create_tdata(dd->inv->dlg->endpt, &dst); + if (status != PJ_SUCCESS) + return NULL; + + msg = pjsip_msg_create(dst->pool, PJSIP_RESPONSE_MSG); + dst->msg = msg; + pjsip_tx_data_add_ref(dst); + + /* Duplicate status line */ + msg->line.status.code = src->msg->line.status.code; + pj_strdup(dst->pool, &msg->line.status.reason, + &src->msg->line.status.reason); + + /* Duplicate all headers */ + hsrc = src->msg->hdr.next; + while (hsrc != &src->msg->hdr) { + pjsip_hdr *h = (pjsip_hdr*) pjsip_hdr_clone(dst->pool, hsrc); + pjsip_msg_add_hdr(msg, h); + hsrc = hsrc->next; + } + + /* Duplicate message body */ + if (src->msg->body) + msg->body = pjsip_msg_body_clone(dst->pool, src->msg->body); + + PJ_LOG(5,(dd->inv->dlg->obj_name, + "Reliable response %s created", + pjsip_tx_data_get_info(dst))); + + return dst; +} + + +/* Check if any pending response in transmission list has SDP */ +static pj_bool_t has_sdp(dlg_data *dd) +{ + tx_data_list_t *tl; + + tl = dd->uas_state->tx_data_list.next; + while (tl != &dd->uas_state->tx_data_list) { + if (tl->tdata->msg->body) + return PJ_TRUE; + tl = tl->next; + } + + return PJ_FALSE; +} + + +/* Send response reliably */ +PJ_DEF(pj_status_t) pjsip_100rel_tx_response(pjsip_inv_session *inv, + pjsip_tx_data *tdata) +{ + pjsip_cseq_hdr *cseq_hdr; + pjsip_generic_string_hdr *rseq_hdr; + pjsip_require_hdr *req_hdr; + int status_code; + dlg_data *dd; + pjsip_tx_data *old_tdata; + pj_status_t status; + + PJ_ASSERT_RETURN(tdata->msg->type == PJSIP_RESPONSE_MSG, + PJSIP_ENOTRESPONSEMSG); + + status_code = tdata->msg->line.status.code; + + /* 100 response doesn't need PRACK */ + if (status_code == 100) + return pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + + + /* Get the 100rel data attached to this dialog */ + dd = (dlg_data*) inv->dlg->mod_data[mod_100rel.mod.id]; + PJ_ASSERT_RETURN(dd != NULL, PJ_EINVALIDOP); + + + /* Clone tdata. + * We need to clone tdata because we may need to keep it in our + * retransmission list, while the original dialog may modify it + * if it wants to send another response. + */ + old_tdata = tdata; + tdata = clone_tdata(dd, old_tdata); + pjsip_tx_data_dec_ref(old_tdata); + + + /* Get CSeq header, and make sure this is INVITE response */ + cseq_hdr = (pjsip_cseq_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); + PJ_ASSERT_RETURN(cseq_hdr != NULL, PJ_EBUG); + PJ_ASSERT_RETURN(cseq_hdr->method.id == PJSIP_INVITE_METHOD, + PJ_EINVALIDOP); + + /* Remove existing Require header */ + req_hdr = find_req_hdr(tdata->msg); + if (req_hdr) { + pj_list_erase(req_hdr); + } + + /* Remove existing RSeq header */ + rseq_hdr = (pjsip_generic_string_hdr*) + pjsip_msg_find_hdr_by_name(tdata->msg, &RSEQ, NULL); + if (rseq_hdr) + pj_list_erase(rseq_hdr); + + /* Different treatment for provisional and final response */ + if (status_code/100 == 2) { + + /* RFC 3262 Section 3: UAS Behavior: + + The UAS MAY send a final response to the initial request + before having received PRACKs for all unacknowledged + reliable provisional responses, unless the final response + is 2xx and any of the unacknowledged reliable provisional + responses contained a session description. In that case, + it MUST NOT send a final response until those provisional + responses are acknowledged. + */ + + if (dd->uas_state && has_sdp(dd)) { + /* Yes we have transmitted 1xx with SDP reliably. + * In this case, must queue the 2xx response. + */ + tx_data_list_t *tl; + + tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); + tl->tdata = tdata; + tl->rseq = (pj_uint32_t)-1; + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + + /* Will send later */ + status = PJ_SUCCESS; + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "2xx response will be sent after PRACK")); + + } else if (dd->uas_state) { + /* + RFC 3262 Section 3: UAS Behavior: + + If the UAS does send a final response when reliable + responses are still unacknowledged, it SHOULD NOT + continue to retransmit the unacknowledged reliable + provisional responses, but it MUST be prepared to + process PRACK requests for those outstanding + responses. + */ + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "No SDP sent so far, sending 2xx now")); + + /* Cancel the retransmit timer */ + if (dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + } + + /* Clear all pending responses (drop 'em) */ + clear_all_responses(dd); + + /* And transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + + } else { + /* We didn't send any reliable provisional response */ + + /* Transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + } + + } else if (status_code >= 300) { + + /* + RFC 3262 Section 3: UAS Behavior: + + If the UAS does send a final response when reliable + responses are still unacknowledged, it SHOULD NOT + continue to retransmit the unacknowledged reliable + provisional responses, but it MUST be prepared to + process PRACK requests for those outstanding + responses. + */ + + /* Cancel the retransmit timer */ + if (dd->uas_state && dd->uas_state->retransmit_timer.id) { + pjsip_endpt_cancel_timer(dd->inv->dlg->endpt, + &dd->uas_state->retransmit_timer); + dd->uas_state->retransmit_timer.id = PJ_FALSE; + + /* Clear all pending responses (drop 'em) */ + clear_all_responses(dd); + } + + /* And transmit the 2xx response */ + status=pjsip_dlg_send_response(inv->dlg, + inv->invite_tsx, tdata); + + } else { + /* + * This is provisional response. + */ + char rseq_str[32]; + pj_str_t rseq; + tx_data_list_t *tl; + + /* Create UAS state if we don't have one */ + if (dd->uas_state == NULL) { + dd->uas_state = PJ_POOL_ZALLOC_T(inv->dlg->pool, + uas_state_t); + dd->uas_state->cseq = cseq_hdr->cseq; + dd->uas_state->rseq = pj_rand() % 0x7FFF; + pj_list_init(&dd->uas_state->tx_data_list); + dd->uas_state->retransmit_timer.user_data = dd; + dd->uas_state->retransmit_timer.cb = &on_retransmit; + } + + /* Check that CSeq match */ + PJ_ASSERT_RETURN(cseq_hdr->cseq == dd->uas_state->cseq, + PJ_EINVALIDOP); + + /* Add Require header */ + req_hdr = pjsip_require_hdr_create(tdata->pool); + req_hdr->count = 1; + req_hdr->values[0] = tag_100rel; + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)req_hdr); + + /* Add RSeq header */ + pj_ansi_snprintf(rseq_str, sizeof(rseq_str), "%u", + dd->uas_state->rseq); + rseq = pj_str(rseq_str); + rseq_hdr = pjsip_generic_string_hdr_create(tdata->pool, + &RSEQ, &rseq); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)rseq_hdr); + + /* Create list entry for this response */ + tl = PJ_POOL_ZALLOC_T(tdata->pool, tx_data_list_t); + tl->tdata = tdata; + tl->rseq = dd->uas_state->rseq++; + + /* Add to queue if there's pending response, otherwise + * transmit immediately. + */ + if (!pj_list_empty(&dd->uas_state->tx_data_list)) { + + int code = tdata->msg->line.status.code; + + /* Will send later */ + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + status = PJ_SUCCESS; + + PJ_LOG(4,(dd->inv->dlg->obj_name, + "Reliable %d response enqueued (%d pending)", + code, pj_list_size(&dd->uas_state->tx_data_list))); + + } else { + pj_list_push_back(&dd->uas_state->tx_data_list, tl); + + dd->uas_state->retransmit_count = 0; + on_retransmit(NULL, &dd->uas_state->retransmit_timer); + status = PJ_SUCCESS; + } + + } + + return status; +} + + diff --git a/pjsip/src/pjsip-ua/sip_inv.c b/pjsip/src/pjsip-ua/sip_inv.c new file mode 100644 index 0000000..8db5308 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_inv.c @@ -0,0 +1,4491 @@ +/* $Id: sip_inv.c 4156 2012-06-06 07:24:08Z bennylp $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_inv.h> +#include <pjsip-ua/sip_100rel.h> +#include <pjsip-ua/sip_timer.h> +#include <pjsip/sip_module.h> +#include <pjsip/sip_endpoint.h> +#include <pjsip/sip_event.h> +#include <pjsip/sip_multipart.h> +#include <pjsip/sip_transaction.h> +#include <pjmedia/sdp.h> +#include <pjmedia/sdp_neg.h> +#include <pjmedia/errno.h> +#include <pj/string.h> +#include <pj/pool.h> +#include <pj/assert.h> +#include <pj/os.h> +#include <pj/log.h> +#include <pj/rand.h> + +/* + * Note on offer/answer: + * + * The offer/answer framework in this implementation assumes the occurence + * of SDP in a particular request/response according to this table: + + offer answer Note: + ======================================================================== + INVITE X INVITE may contain offer + 18x/INVITE X X Response may contain offer or answer + 2xx/INVITE X X Response may contain offer or answer + ACK X ACK may contain answer + + PRACK X PRACK can only contain answer + 2xx/PRACK Response may not have offer nor answer + + UPDATE X UPDATE may only contain offer + 2xx/UPDATE X Response may only contain answer + ======================================================================== + + * + */ + +#define THIS_FILE "sip_inv.c" + +static const char *inv_state_names[] = +{ + "NULL", + "CALLING", + "INCOMING", + "EARLY", + "CONNECTING", + "CONFIRMED", + "DISCONNCTD", + "TERMINATED", +}; + +/* UPDATE method */ +static const pjsip_method pjsip_update_method = +{ + PJSIP_OTHER_METHOD, + { "UPDATE", 6 } +}; + +#define POOL_INIT_SIZE 256 +#define POOL_INC_SIZE 256 + +/* + * Static prototypes. + */ +static pj_status_t mod_inv_load(pjsip_endpoint *endpt); +static pj_status_t mod_inv_unload(void); +static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata); +static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata); +static void mod_inv_on_tsx_state(pjsip_transaction*, pjsip_event*); + +static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e); +static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e); + +static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, + pjsip_transaction *tsx, + pjsip_rx_data *rdata); +static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ); +static pjsip_msg_body *create_sdp_body(pj_pool_t *pool, + const pjmedia_sdp_session *c_sdp); +static pj_status_t process_answer( pjsip_inv_session *inv, + int st_code, + pjsip_tx_data *tdata, + const pjmedia_sdp_session *local_sdp); + +static pj_status_t handle_timer_response(pjsip_inv_session *inv, + const pjsip_rx_data *rdata, + pj_bool_t end_sess_on_failure); + +static void (*inv_state_handler[])( pjsip_inv_session *inv, pjsip_event *e) = +{ + &inv_on_state_null, + &inv_on_state_calling, + &inv_on_state_incoming, + &inv_on_state_early, + &inv_on_state_connecting, + &inv_on_state_confirmed, + &inv_on_state_disconnected, +}; + +static struct mod_inv +{ + pjsip_module mod; + pjsip_endpoint *endpt; + pjsip_inv_callback cb; +} mod_inv = +{ + { + NULL, NULL, /* prev, next. */ + { "mod-invite", 10 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + &mod_inv_load, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + &mod_inv_unload, /* unload() */ + &mod_inv_on_rx_request, /* on_rx_request() */ + &mod_inv_on_rx_response, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + &mod_inv_on_tsx_state, /* on_tsx_state() */ + } +}; + + +/* Invite session data to be attached to transaction. */ +struct tsx_inv_data +{ + pjsip_inv_session *inv; /* The invite session */ + pj_bool_t sdp_done; /* SDP negotiation done for this tsx? */ + pj_bool_t retrying; /* Resend (e.g. due to 401/407) */ + pj_str_t done_tag; /* To tag in RX response with answer */ + pj_bool_t done_early;/* Negotiation was done for early med? */ +}; + +/* + * Module load() + */ +static pj_status_t mod_inv_load(pjsip_endpoint *endpt) +{ + pj_str_t allowed[] = {{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6}, + { "UPDATE", 6}}; + pj_str_t accepted = { "application/sdp", 15 }; + + /* Register supported methods: INVITE, ACK, BYE, CANCEL, UPDATE */ + pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ALLOW, NULL, + PJ_ARRAY_SIZE(allowed), allowed); + + /* Register "application/sdp" in Accept header */ + pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ACCEPT, NULL, + 1, &accepted); + + return PJ_SUCCESS; +} + +/* + * Module unload() + */ +static pj_status_t mod_inv_unload(void) +{ + /* Should remove capability here */ + return PJ_SUCCESS; +} + +/* + * Set session state. + */ +void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state, + pjsip_event *e) +{ + pjsip_inv_state prev_state = inv->state; + pj_bool_t dont_notify = PJ_FALSE; + pj_status_t status; + + /* Prevent STATE_CALLING from being reported more than once because + * of authentication + * https://trac.pjsip.org/repos/ticket/1318 + */ + if (state==PJSIP_INV_STATE_CALLING && + (inv->cb_called & (1 << PJSIP_INV_STATE_CALLING)) != 0) + { + dont_notify = PJ_TRUE; + } + + /* If state is confirmed, check that SDP negotiation is done, + * otherwise disconnect the session. + */ + if (state == PJSIP_INV_STATE_CONFIRMED) { + struct tsx_inv_data *tsx_inv_data = NULL; + + if (inv->invite_tsx) { + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; + } + + if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE && + (tsx_inv_data && !tsx_inv_data->sdp_done) ) + { + pjsip_tx_data *bye; + + PJ_LOG(4,(inv->obj_name, "SDP offer/answer incomplete, ending the " + "session")); + + status = pjsip_inv_end_session(inv, PJSIP_SC_NOT_ACCEPTABLE, + NULL, &bye); + if (status == PJ_SUCCESS && bye) + status = pjsip_inv_send_msg(inv, bye); + + return; + } + } + + /* Set state. */ + inv->state = state; + + /* If state is DISCONNECTED, cause code MUST have been set. */ + pj_assert(inv->state != PJSIP_INV_STATE_DISCONNECTED || + inv->cause != 0); + + /* Mark the callback as called for this state */ + inv->cb_called |= (1 << state); + + /* Call on_state_changed() callback. */ + if (mod_inv.cb.on_state_changed && inv->notify && !dont_notify) + (*mod_inv.cb.on_state_changed)(inv, e); + + /* Only decrement when previous state is not already DISCONNECTED */ + if (inv->state == PJSIP_INV_STATE_DISCONNECTED && + prev_state != PJSIP_INV_STATE_DISCONNECTED) + { + if (inv->last_ack) { + pjsip_tx_data_dec_ref(inv->last_ack); + inv->last_ack = NULL; + } + if (inv->invite_req) { + pjsip_tx_data_dec_ref(inv->invite_req); + inv->invite_req = NULL; + } + pjsip_100rel_end_session(inv); + pjsip_timer_end_session(inv); + pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod); + + /* Release the flip-flop pools */ + pj_pool_release(inv->pool_prov); + inv->pool_prov = NULL; + pj_pool_release(inv->pool_active); + inv->pool_active = NULL; + } +} + + +/* + * Set cause code. + */ +void inv_set_cause(pjsip_inv_session *inv, int cause_code, + const pj_str_t *cause_text) +{ + if (cause_code > inv->cause) { + inv->cause = (pjsip_status_code) cause_code; + if (cause_text) + pj_strdup(inv->pool, &inv->cause_text, cause_text); + else if (cause_code/100 == 2) + inv->cause_text = pj_str("Normal call clearing"); + else + inv->cause_text = *pjsip_get_status_text(cause_code); + } +} + + +/* + * Check if outgoing request needs to have SDP answer. + * This applies for both ACK and PRACK requests. + */ +static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv, + pjsip_transaction *tsx) +{ + pjmedia_sdp_neg_state neg_state; + const pjmedia_sdp_session *sdp = NULL; + pj_status_t status; + + /* If SDP negotiator is ready, start negotiation. */ + + /* Start nego when appropriate. */ + neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) : + PJMEDIA_SDP_NEG_STATE_NULL; + + if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) { + + /* Nothing to do */ + + } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && + pjmedia_sdp_neg_has_local_answer(inv->neg) ) + { + struct tsx_inv_data *tsx_inv_data; + struct tsx_inv_data dummy; + + /* Get invite session's transaction data. + * Note that tsx may be NULL, for example when application sends + * delayed ACK request (at this time, the original INVITE + * transaction may have been destroyed. + */ + if (tsx) { + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + } else { + tsx_inv_data = &dummy; + pj_bzero(&dummy, sizeof(dummy)); + dummy.inv = inv; + } + + status = inv_negotiate_sdp(inv); + if (status != PJ_SUCCESS) + return NULL; + + /* Mark this transaction has having SDP offer/answer done. */ + tsx_inv_data->sdp_done = 1; + + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + + } else { + /* This remark is only valid for ACK. + PJ_LOG(4,(inv->dlg->obj_name, + "FYI, the SDP negotiator state (%s) is in a mess " + "when sending this ACK/PRACK request", + pjmedia_sdp_neg_state_str(neg_state))); + */ + } + + return sdp; +} + + +/* + * Send ACK for 2xx response. + */ +static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_rx_data *rdata; + pjsip_event ack_e; + pj_status_t status; + + if (e->type == PJSIP_EVENT_TSX_STATE) + rdata = e->body.tsx_state.src.rdata; + else if (e->type == PJSIP_EVENT_RX_MSG) + rdata = e->body.rx_msg.rdata; + else { + pj_assert(!"Unsupported event type"); + return PJ_EBUG; + } + + PJ_LOG(5,(inv->obj_name, "Received %s, sending ACK", + pjsip_rx_data_get_info(rdata))); + + /* Check if we have cached ACK request. Must not use the cached ACK + * if it's still marked as pending by transport (#1011) + */ + if (inv->last_ack && rdata->msg_info.cseq->cseq == inv->last_ack_cseq && + !inv->last_ack->is_pending) + { + pjsip_tx_data_add_ref(inv->last_ack); + + } else if (mod_inv.cb.on_send_ack) { + /* If application handles ACK transmission manually, just notify the + * callback + */ + PJ_LOG(5,(inv->obj_name, "Received %s, notifying application callback", + pjsip_rx_data_get_info(rdata))); + + (*mod_inv.cb.on_send_ack)(inv, rdata); + return PJ_SUCCESS; + + } else { + status = pjsip_inv_create_ack(inv, rdata->msg_info.cseq->cseq, + &inv->last_ack); + if (status != PJ_SUCCESS) + return status; + } + + PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack); + + /* Send ACK */ + status = pjsip_dlg_send_request(inv->dlg, inv->last_ack, -1, NULL); + if (status != PJ_SUCCESS) { + /* Better luck next time */ + pj_assert(!"Unable to send ACK!"); + return status; + } + + + /* Set state to CONFIRMED (if we're not in CONFIRMED yet). + * But don't set it to CONFIRMED if we're already DISCONNECTED + * (this may have been a late 200/OK response. + */ + if (inv->state < PJSIP_INV_STATE_CONFIRMED) { + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e); + } + + return PJ_SUCCESS; +} + +/* + * Module on_rx_request() + * + * This callback is called for these events: + * - endpoint receives request which was unhandled by higher priority + * modules (e.g. transaction layer, dialog layer). + * - dialog distributes incoming request to its usages. + */ +static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata) +{ + pjsip_method *method; + pjsip_dialog *dlg; + pjsip_inv_session *inv; + + /* Only wants to receive request from a dialog. */ + dlg = pjsip_rdata_get_dlg(rdata); + if (dlg == NULL) + return PJ_FALSE; + + inv = (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id]; + + /* Report to dialog that we handle INVITE, CANCEL, BYE, ACK. + * If we need to send response, it will be sent in the state + * handlers. + */ + method = &rdata->msg_info.msg->line.req.method; + + if (method->id == PJSIP_INVITE_METHOD) { + return PJ_TRUE; + } + + /* BYE and CANCEL must have existing invite session */ + if (method->id == PJSIP_BYE_METHOD || + method->id == PJSIP_CANCEL_METHOD) + { + if (inv == NULL) + return PJ_FALSE; + + return PJ_TRUE; + } + + /* On receipt ACK request, when state is CONNECTING, + * move state to CONFIRMED. + */ + if (method->id == PJSIP_ACK_METHOD && inv) { + + /* Ignore if we don't have INVITE in progress */ + if (!inv->invite_tsx) { + return PJ_TRUE; + } + + /* Ignore ACK if pending INVITE transaction has not finished. */ + if (inv->invite_tsx->state < PJSIP_TSX_STATE_COMPLETED) { + return PJ_TRUE; + } + + /* Ignore ACK with different CSeq + * https://trac.pjsip.org/repos/ticket/1391 + */ + if (rdata->msg_info.cseq->cseq != inv->invite_tsx->cseq) { + return PJ_TRUE; + } + + /* Terminate INVITE transaction, if it's still present. */ + if (inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) { + /* Before we terminate INVITE transaction, process the SDP + * in the ACK request, if any. + * Only do this when invite state is not already disconnected + * (http://trac.pjsip.org/repos/ticket/640). + */ + if (inv->state < PJSIP_INV_STATE_DISCONNECTED) { + inv_check_sdp_in_incoming_msg(inv, inv->invite_tsx, rdata); + + /* Check if local offer got no SDP answer and INVITE session + * is in CONFIRMED state. + */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + inv->state==PJSIP_INV_STATE_CONFIRMED) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + } + + /* Now we can terminate the INVITE transaction */ + pj_assert(inv->invite_tsx->status_code >= 200); + pjsip_tsx_terminate(inv->invite_tsx, + inv->invite_tsx->status_code); + inv->invite_tsx = NULL; + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } + } + + /* On receipt of ACK, only set state to confirmed when state + * is CONNECTING (e.g. we don't want to set the state to confirmed + * when we receive ACK retransmission after sending non-2xx!) + */ + if (inv->state == PJSIP_INV_STATE_CONNECTING) { + pjsip_event event; + + PJSIP_EVENT_INIT_RX_MSG(event, rdata); + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &event); + } + } + + return PJ_FALSE; +} + +/* This function will process Session Timer headers in received + * 2xx or 422 response of INVITE/UPDATE request. + */ +static pj_status_t handle_timer_response(pjsip_inv_session *inv, + const pjsip_rx_data *rdata, + pj_bool_t end_sess_on_failure) +{ + pjsip_status_code st_code; + pj_status_t status; + + status = pjsip_timer_process_resp(inv, rdata, &st_code); + if (status != PJ_SUCCESS && end_sess_on_failure) { + pjsip_tx_data *tdata; + pj_status_t status2; + + status2 = pjsip_inv_end_session(inv, st_code, NULL, &tdata); + if (tdata && status2 == PJ_SUCCESS) + pjsip_inv_send_msg(inv, tdata); + } + + return status; +} + +/* + * Module on_rx_response(). + * + * This callback is called for these events: + * - dialog distributes incoming 2xx response to INVITE (outside + * transaction) to its usages. + * - endpoint distributes strayed responses. + */ +static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata) +{ + pjsip_dialog *dlg; + pjsip_inv_session *inv; + pjsip_msg *msg = rdata->msg_info.msg; + + dlg = pjsip_rdata_get_dlg(rdata); + + /* Ignore responses outside dialog */ + if (dlg == NULL) + return PJ_FALSE; + + /* Ignore responses not belonging to invite session */ + inv = pjsip_dlg_get_inv_session(dlg); + if (inv == NULL) + return PJ_FALSE; + + /* This MAY be retransmission of 2xx response to INVITE. + * If it is, we need to send ACK. + */ + if (msg->type == PJSIP_RESPONSE_MSG && msg->line.status.code/100==2 && + rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD && + inv->invite_tsx == NULL) + { + pjsip_event e; + + PJSIP_EVENT_INIT_RX_MSG(e, rdata); + inv_send_ack(inv, &e); + return PJ_TRUE; + + } + + /* No other processing needs to be done here. */ + return PJ_FALSE; +} + +/* + * Module on_tsx_state() + * + * This callback is called by dialog framework for all transactions + * inside the dialog for all its dialog usages. + */ +static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e) +{ + pjsip_dialog *dlg; + pjsip_inv_session *inv; + + dlg = pjsip_tsx_get_dlg(tsx); + if (dlg == NULL) + return; + + inv = pjsip_dlg_get_inv_session(dlg); + if (inv == NULL) + return; + + /* Call state handler for the invite session. */ + (*inv_state_handler[inv->state])(inv, e); + + /* Call on_tsx_state */ + if (mod_inv.cb.on_tsx_state_changed && inv->notify) + (*mod_inv.cb.on_tsx_state_changed)(inv, tsx, e); + + /* Clear invite transaction when tsx is confirmed. + * Previously we set invite_tsx to NULL only when transaction has + * terminated, but this didn't work when ACK has the same Via branch + * value as the INVITE (see http://www.pjsip.org/trac/ticket/113) + */ + if (tsx->state>=PJSIP_TSX_STATE_CONFIRMED && tsx == inv->invite_tsx) { + inv->invite_tsx = NULL; + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } + } +} + + +/* + * Initialize the invite module. + */ +PJ_DEF(pj_status_t) pjsip_inv_usage_init( pjsip_endpoint *endpt, + const pjsip_inv_callback *cb) +{ + pj_status_t status; + + /* Check arguments. */ + PJ_ASSERT_RETURN(endpt && cb, PJ_EINVAL); + + /* Some callbacks are mandatory */ + PJ_ASSERT_RETURN(cb->on_state_changed && cb->on_new_session, PJ_EINVAL); + + /* Check if module already registered. */ + PJ_ASSERT_RETURN(mod_inv.mod.id == -1, PJ_EINVALIDOP); + + /* Copy param. */ + pj_memcpy(&mod_inv.cb, cb, sizeof(pjsip_inv_callback)); + + mod_inv.endpt = endpt; + + /* Register the module. */ + status = pjsip_endpt_register_module(endpt, &mod_inv.mod); + if (status != PJ_SUCCESS) + return status; + + return PJ_SUCCESS; +} + +/* + * Get the instance of invite module. + */ +PJ_DEF(pjsip_module*) pjsip_inv_usage_instance(void) +{ + return &mod_inv.mod; +} + + + +/* + * Return the invite session for the specified dialog. + */ +PJ_DEF(pjsip_inv_session*) pjsip_dlg_get_inv_session(pjsip_dialog *dlg) +{ + return (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id]; +} + + +/* + * Get INVITE state name. + */ +PJ_DEF(const char *) pjsip_inv_state_name(pjsip_inv_state state) +{ + PJ_ASSERT_RETURN(state >= PJSIP_INV_STATE_NULL && + state <= PJSIP_INV_STATE_DISCONNECTED, + "??"); + + return inv_state_names[state]; +} + +/* + * Create UAC invite session. + */ +PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg, + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv) +{ + pjsip_inv_session *inv; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(dlg && p_inv, PJ_EINVAL); + + /* Must lock dialog first */ + pjsip_dlg_inc_lock(dlg); + + /* Normalize options */ + if (options & PJSIP_INV_REQUIRE_100REL) + options |= PJSIP_INV_SUPPORT_100REL; + if (options & PJSIP_INV_REQUIRE_TIMER) + options |= PJSIP_INV_SUPPORT_TIMER; + + /* Create the session */ + inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session); + pj_assert(inv != NULL); + + inv->pool = dlg->pool; + inv->role = PJSIP_ROLE_UAC; + inv->state = PJSIP_INV_STATE_NULL; + inv->dlg = dlg; + inv->options = options; + inv->notify = PJ_TRUE; + inv->cause = (pjsip_status_code) 0; + + /* Create flip-flop pool (see ticket #877) */ + /* (using inv->obj_name as temporary variable for pool names */ + pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool); + inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, + POOL_INIT_SIZE, POOL_INC_SIZE); + inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, + POOL_INIT_SIZE, POOL_INC_SIZE); + + /* Object name will use the same dialog pointer. */ + pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg); + + /* Create negotiator if local_sdp is specified. */ + if (local_sdp) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, &inv->neg); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } + } + + /* Register invite as dialog usage. */ + status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } + + /* Increment dialog session */ + pjsip_dlg_inc_session(dlg, &mod_inv.mod); + + /* Create 100rel handler */ + pjsip_100rel_attach(inv); + + /* Done */ + *p_inv = inv; + + pjsip_dlg_dec_lock(dlg); + + PJ_LOG(5,(inv->obj_name, "UAC invite session created for dialog %s", + dlg->obj_name)); + + return PJ_SUCCESS; +} + +PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info(pjsip_rx_data *rdata) +{ + pjsip_rdata_sdp_info *sdp_info; + pjsip_msg_body *body = rdata->msg_info.msg->body; + pjsip_ctype_hdr *ctype_hdr = rdata->msg_info.ctype; + pjsip_media_type app_sdp; + + sdp_info = (pjsip_rdata_sdp_info*) + rdata->endpt_info.mod_data[mod_inv.mod.id]; + if (sdp_info) + return sdp_info; + + sdp_info = PJ_POOL_ZALLOC_T(rdata->tp_info.pool, + pjsip_rdata_sdp_info); + PJ_ASSERT_RETURN(mod_inv.mod.id >= 0, sdp_info); + rdata->endpt_info.mod_data[mod_inv.mod.id] = sdp_info; + + pjsip_media_type_init2(&app_sdp, "application", "sdp"); + + if (body && ctype_hdr && + pj_stricmp(&ctype_hdr->media.type, &app_sdp.type)==0 && + pj_stricmp(&ctype_hdr->media.subtype, &app_sdp.subtype)==0) + { + sdp_info->body.ptr = (char*)body->data; + sdp_info->body.slen = body->len; + } else if (body && ctype_hdr && + pj_stricmp2(&ctype_hdr->media.type, "multipart")==0 && + (pj_stricmp2(&ctype_hdr->media.subtype, "mixed")==0 || + pj_stricmp2(&ctype_hdr->media.subtype, "alternative")==0)) + { + pjsip_multipart_part *part; + + part = pjsip_multipart_find_part(body, &app_sdp, NULL); + if (part) { + sdp_info->body.ptr = (char*)part->body->data; + sdp_info->body.slen = part->body->len; + } + } + + if (sdp_info->body.ptr) { + pj_status_t status; + status = pjmedia_sdp_parse(rdata->tp_info.pool, + sdp_info->body.ptr, + sdp_info->body.slen, + &sdp_info->sdp); + if (status == PJ_SUCCESS) + status = pjmedia_sdp_validate(sdp_info->sdp); + + if (status != PJ_SUCCESS) { + sdp_info->sdp = NULL; + PJ_PERROR(1,(THIS_FILE, status, + "Error parsing/validating SDP body")); + } + + sdp_info->sdp_err = status; + } + + return sdp_info; +} + + +/* + * Verify incoming INVITE request. + */ +PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata, + pj_pool_t *tmp_pool, + unsigned *options, + const pjmedia_sdp_session *r_sdp, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) +{ + pjsip_msg *msg = NULL; + pjsip_allow_hdr *allow = NULL; + pjsip_supported_hdr *sup_hdr = NULL; + pjsip_require_hdr *req_hdr = NULL; + pjsip_contact_hdr *c_hdr = NULL; + int code = 200; + unsigned rem_option = 0; + pj_status_t status = PJ_SUCCESS; + pjsip_hdr res_hdr_list; + pjsip_rdata_sdp_info *sdp_info; + + /* Init return arguments. */ + if (p_tdata) *p_tdata = NULL; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(tmp_pool != NULL && options != NULL, PJ_EINVAL); + + /* Normalize options */ + if (*options & PJSIP_INV_REQUIRE_100REL) + *options |= PJSIP_INV_SUPPORT_100REL; + if (*options & PJSIP_INV_REQUIRE_TIMER) + *options |= PJSIP_INV_SUPPORT_TIMER; + if (*options & PJSIP_INV_REQUIRE_ICE) + *options |= PJSIP_INV_SUPPORT_ICE; + + if (rdata) { + /* Get the message in rdata */ + msg = rdata->msg_info.msg; + + /* Must be INVITE request. */ + PJ_ASSERT_RETURN(msg && msg->type == PJSIP_REQUEST_MSG && + msg->line.req.method.id == PJSIP_INVITE_METHOD, + PJ_EINVAL); + } + + /* If tdata is specified, then either dlg or endpt must be specified */ + PJ_ASSERT_RETURN((!p_tdata) || (endpt || dlg), PJ_EINVAL); + + /* Get the endpoint */ + endpt = endpt ? endpt : dlg->endpt; + + /* Init response header list */ + pj_list_init(&res_hdr_list); + + /* Check the Contact header */ + if (msg) { + c_hdr = (pjsip_contact_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL); + } + if (msg && (!c_hdr || !c_hdr->uri)) { + /* Missing Contact header or Contact contains "*" */ + pjsip_warning_hdr *w; + pj_str_t warn_text; + + warn_text = pj_str("Bad/missing Contact header"); + w = pjsip_warning_hdr_create(tmp_pool, 399, + pjsip_endpt_name(endpt), + &warn_text); + if (w) { + pj_list_push_back(&res_hdr_list, w); + } + + code = PJSIP_SC_BAD_REQUEST; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + goto on_return; + } + + /* Check the request body, see if it's something that we support, + * only when the body hasn't been parsed before. + */ + if (r_sdp == NULL && rdata) { + sdp_info = pjsip_rdata_get_sdp_info(rdata); + } else { + sdp_info = NULL; + } + + if (r_sdp==NULL && msg && msg->body) { + + /* Check if body really contains SDP. */ + if (sdp_info->body.ptr == NULL) { + /* Couldn't find "application/sdp" */ + code = PJSIP_SC_UNSUPPORTED_MEDIA_TYPE; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + if (p_tdata) { + /* Add Accept header to response */ + pjsip_accept_hdr *acc; + + acc = pjsip_accept_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(acc, PJ_ENOMEM); + acc->values[acc->count++] = pj_str("application/sdp"); + pj_list_push_back(&res_hdr_list, acc); + } + + goto on_return; + } + + if (sdp_info->sdp_err != PJ_SUCCESS) { + /* Unparseable or invalid SDP */ + code = PJSIP_SC_BAD_REQUEST; + + if (p_tdata) { + /* Add Warning header. */ + pjsip_warning_hdr *w; + + w = pjsip_warning_hdr_create_from_status(tmp_pool, + pjsip_endpt_name(endpt), + sdp_info->sdp_err); + PJ_ASSERT_RETURN(w, PJ_ENOMEM); + + pj_list_push_back(&res_hdr_list, w); + } + + goto on_return; + } + + r_sdp = sdp_info->sdp; + } + + if (r_sdp) { + /* Negotiate with local SDP */ + if (l_sdp) { + pjmedia_sdp_neg *neg; + + /* Local SDP must be valid! */ + PJ_ASSERT_RETURN((status=pjmedia_sdp_validate(l_sdp))==PJ_SUCCESS, + status); + + /* Create SDP negotiator */ + status = pjmedia_sdp_neg_create_w_remote_offer( + tmp_pool, l_sdp, r_sdp, &neg); + PJ_ASSERT_RETURN(status == PJ_SUCCESS, status); + + /* Negotiate SDP */ + status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0); + if (status != PJ_SUCCESS) { + + /* Incompatible media */ + code = PJSIP_SC_NOT_ACCEPTABLE_HERE; + + if (p_tdata) { + pjsip_accept_hdr *acc; + pjsip_warning_hdr *w; + + /* Add Warning header. */ + w = pjsip_warning_hdr_create_from_status( + tmp_pool, + pjsip_endpt_name(endpt), status); + PJ_ASSERT_RETURN(w, PJ_ENOMEM); + + pj_list_push_back(&res_hdr_list, w); + + /* Add Accept header to response */ + acc = pjsip_accept_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(acc, PJ_ENOMEM); + acc->values[acc->count++] = pj_str("application/sdp"); + pj_list_push_back(&res_hdr_list, acc); + + } + + goto on_return; + } + } + } + + /* Check supported methods, see if peer supports UPDATE. + * We just assume that peer supports standard INVITE, ACK, CANCEL, and BYE + * implicitly by sending this INVITE. + */ + if (msg) { + allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_ALLOW, + NULL); + } + if (allow) { + unsigned i; + const pj_str_t STR_UPDATE = { "UPDATE", 6 }; + + for (i=0; i<allow->count; ++i) { + if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) + break; + } + + if (i != allow->count) { + /* UPDATE is present in Allow */ + rem_option |= PJSIP_INV_SUPPORT_UPDATE; + } + + } + + /* Check Supported header */ + if (msg) { + sup_hdr = (pjsip_supported_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_SUPPORTED, NULL); + } + if (sup_hdr) { + unsigned i; + const pj_str_t STR_100REL = { "100rel", 6}; + const pj_str_t STR_TIMER = { "timer", 5}; + const pj_str_t STR_ICE = { "ice", 3 }; + + for (i=0; i<sup_hdr->count; ++i) { + if (pj_stricmp(&sup_hdr->values[i], &STR_100REL)==0) + rem_option |= PJSIP_INV_SUPPORT_100REL; + else if (pj_stricmp(&sup_hdr->values[i], &STR_TIMER)==0) + rem_option |= PJSIP_INV_SUPPORT_TIMER; + else if (pj_stricmp(&sup_hdr->values[i], &STR_ICE)==0) + rem_option |= PJSIP_INV_SUPPORT_ICE; + } + } + + /* Check Require header */ + if (msg) { + req_hdr = (pjsip_require_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL); + } + if (req_hdr) { + unsigned i; + const pj_str_t STR_100REL = { "100rel", 6}; + const pj_str_t STR_REPLACES = { "replaces", 8 }; + const pj_str_t STR_TIMER = { "timer", 5 }; + const pj_str_t STR_ICE = { "ice", 3 }; + unsigned unsupp_cnt = 0; + pj_str_t unsupp_tags[PJSIP_GENERIC_ARRAY_MAX_COUNT]; + + for (i=0; i<req_hdr->count; ++i) { + if ((*options & PJSIP_INV_SUPPORT_100REL) && + pj_stricmp(&req_hdr->values[i], &STR_100REL)==0) + { + rem_option |= PJSIP_INV_REQUIRE_100REL; + + } else if ((*options & PJSIP_INV_SUPPORT_TIMER) && + pj_stricmp(&req_hdr->values[i], &STR_TIMER)==0) + { + rem_option |= PJSIP_INV_REQUIRE_TIMER; + + } else if (pj_stricmp(&req_hdr->values[i], &STR_REPLACES)==0) { + pj_bool_t supp; + + supp = pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, + NULL, &STR_REPLACES); + if (!supp) + unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; + } else if ((*options & PJSIP_INV_SUPPORT_ICE) && + pj_stricmp(&req_hdr->values[i], &STR_ICE)==0) + { + rem_option |= PJSIP_INV_REQUIRE_ICE; + + } else if (!pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED, + NULL, &req_hdr->values[i])) + { + /* Unknown/unsupported extension tag! */ + unsupp_tags[unsupp_cnt++] = req_hdr->values[i]; + } + } + + /* Check if there are required tags that we don't support */ + if (unsupp_cnt) { + + code = PJSIP_SC_BAD_EXTENSION; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + if (p_tdata) { + pjsip_unsupported_hdr *unsupp_hdr; + const pjsip_hdr *h; + + /* Add Unsupported header. */ + unsupp_hdr = pjsip_unsupported_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(unsupp_hdr != NULL, PJ_ENOMEM); + + unsupp_hdr->count = unsupp_cnt; + for (i=0; i<unsupp_cnt; ++i) + unsupp_hdr->values[i] = unsupp_tags[i]; + + pj_list_push_back(&res_hdr_list, unsupp_hdr); + + /* Add Supported header. */ + h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, + NULL); + pj_assert(h); + if (h) { + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_clone(tmp_pool, h); + pj_list_push_back(&res_hdr_list, sup_hdr); + } + } + + goto on_return; + } + } + + /* Check if there are local requirements that are not supported + * by peer. + */ + if ( msg && (((*options & PJSIP_INV_REQUIRE_100REL)!=0 && + (rem_option & PJSIP_INV_SUPPORT_100REL)==0) || + ((*options & PJSIP_INV_REQUIRE_TIMER)!=0 && + (rem_option & PJSIP_INV_SUPPORT_TIMER)==0))) + { + code = PJSIP_SC_EXTENSION_REQUIRED; + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + if (p_tdata) { + const pjsip_hdr *h; + + /* Add Require header. */ + req_hdr = pjsip_require_hdr_create(tmp_pool); + PJ_ASSERT_RETURN(req_hdr != NULL, PJ_ENOMEM); + + if (*options & PJSIP_INV_REQUIRE_100REL) + req_hdr->values[req_hdr->count++] = pj_str("100rel"); + if (*options & PJSIP_INV_REQUIRE_TIMER) + req_hdr->values[req_hdr->count++] = pj_str("timer"); + + pj_list_push_back(&res_hdr_list, req_hdr); + + /* Add Supported header. */ + h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED, + NULL); + pj_assert(h); + if (h) { + sup_hdr = (pjsip_supported_hdr*) + pjsip_hdr_clone(tmp_pool, h); + pj_list_push_back(&res_hdr_list, sup_hdr); + } + + } + + goto on_return; + } + + /* If remote Require something that we support, make us Require + * that feature too. + */ + if (rem_option & PJSIP_INV_REQUIRE_100REL) { + pj_assert(*options & PJSIP_INV_SUPPORT_100REL); + *options |= PJSIP_INV_REQUIRE_100REL; + } + if (rem_option & PJSIP_INV_REQUIRE_TIMER) { + pj_assert(*options & PJSIP_INV_SUPPORT_TIMER); + *options |= PJSIP_INV_REQUIRE_TIMER; + } + +on_return: + + /* Create response if necessary */ + if (code != 200 && p_tdata) { + pjsip_tx_data *tdata; + const pjsip_hdr *h; + + if (!rdata) { + return PJSIP_ERRNO_FROM_SIP_STATUS(code); + } + + if (dlg) { + status = pjsip_dlg_create_response(dlg, rdata, code, NULL, + &tdata); + } else { + status = pjsip_endpt_create_response(endpt, rdata, code, NULL, + &tdata); + } + + if (status != PJ_SUCCESS) + return status; + + /* Add response headers. */ + h = res_hdr_list.next; + while (h != &res_hdr_list) { + pjsip_hdr *cloned; + + cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); + PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); + + pjsip_msg_add_hdr(tdata->msg, cloned); + + h = h->next; + } + + *p_tdata = tdata; + + /* Can not return PJ_SUCCESS when response message is produced. + * Ref: PROTOS test ~#2490 + */ + if (status == PJ_SUCCESS) + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + } + + return status; +} + + +/* + * Verify incoming INVITE request. + */ +PJ_DEF(pj_status_t) pjsip_inv_verify_request2(pjsip_rx_data *rdata, + unsigned *options, + const pjmedia_sdp_session *r_sdp, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) +{ + return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool, + options, r_sdp, l_sdp, dlg, + endpt, p_tdata); +} + + +/* + * Verify incoming INVITE request. + */ +PJ_DEF(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata, + unsigned *options, + const pjmedia_sdp_session *l_sdp, + pjsip_dialog *dlg, + pjsip_endpoint *endpt, + pjsip_tx_data **p_tdata) +{ + return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool, + options, NULL, l_sdp, dlg, + endpt, p_tdata); +} + +/* + * Create UAS invite session. + */ +PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg, + pjsip_rx_data *rdata, + const pjmedia_sdp_session *local_sdp, + unsigned options, + pjsip_inv_session **p_inv) +{ + pjsip_inv_session *inv; + struct tsx_inv_data *tsx_inv_data; + pjsip_msg *msg; + pjsip_rdata_sdp_info *sdp_info; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(dlg && rdata && p_inv, PJ_EINVAL); + + /* Dialog MUST have been initialised. */ + PJ_ASSERT_RETURN(pjsip_rdata_get_tsx(rdata) != NULL, PJ_EINVALIDOP); + + msg = rdata->msg_info.msg; + + /* rdata MUST contain INVITE request */ + PJ_ASSERT_RETURN(msg->type == PJSIP_REQUEST_MSG && + msg->line.req.method.id == PJSIP_INVITE_METHOD, + PJ_EINVALIDOP); + + /* Lock dialog */ + pjsip_dlg_inc_lock(dlg); + + /* Normalize options */ + if (options & PJSIP_INV_REQUIRE_100REL) + options |= PJSIP_INV_SUPPORT_100REL; + if (options & PJSIP_INV_REQUIRE_TIMER) + options |= PJSIP_INV_SUPPORT_TIMER; + + /* Create the session */ + inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session); + pj_assert(inv != NULL); + + inv->pool = dlg->pool; + inv->role = PJSIP_ROLE_UAS; + inv->state = PJSIP_INV_STATE_NULL; + inv->dlg = dlg; + inv->options = options; + inv->notify = PJ_TRUE; + inv->cause = (pjsip_status_code) 0; + + /* Create flip-flop pool (see ticket #877) */ + /* (using inv->obj_name as temporary variable for pool names */ + pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool); + inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, + POOL_INIT_SIZE, POOL_INC_SIZE); + inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name, + POOL_INIT_SIZE, POOL_INC_SIZE); + + /* Object name will use the same dialog pointer. */ + pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg); + + /* Process SDP in message body, if present. */ + sdp_info = pjsip_rdata_get_sdp_info(rdata); + if (sdp_info->sdp_err) { + pjsip_dlg_dec_lock(dlg); + return sdp_info->sdp_err; + } + + /* Create negotiator. */ + if (sdp_info->sdp) { + status = pjmedia_sdp_neg_create_w_remote_offer(inv->pool, local_sdp, + sdp_info->sdp, + &inv->neg); + + } else if (local_sdp) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, &inv->neg); + } else { + status = PJ_SUCCESS; + } + + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } + + /* Register invite as dialog usage. */ + status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(dlg); + return status; + } + + /* Increment session in the dialog. */ + pjsip_dlg_inc_session(dlg, &mod_inv.mod); + + /* Save the invite transaction. */ + inv->invite_tsx = pjsip_rdata_get_tsx(rdata); + + /* Attach our data to the transaction. */ + tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, struct tsx_inv_data); + tsx_inv_data->inv = inv; + inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; + + /* Create 100rel handler */ + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + pjsip_100rel_attach(inv); + } + + /* Done */ + pjsip_dlg_dec_lock(dlg); + *p_inv = inv; + + PJ_LOG(5,(inv->obj_name, "UAS invite session created for dialog %s", + dlg->obj_name)); + + return PJ_SUCCESS; +} + +/* + * Forcefully terminate the session. + */ +PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv, + int st_code, + pj_bool_t notify) +{ + PJ_ASSERT_RETURN(inv, PJ_EINVAL); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(inv->dlg); + + /* Set callback notify flag. */ + inv->notify = notify; + + /* If there's pending transaction, terminate the transaction. + * This may subsequently set the INVITE session state to + * disconnected. + */ + if (inv->invite_tsx && + inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) + { + pjsip_tsx_terminate(inv->invite_tsx, st_code); + + } + + /* Set cause. */ + inv_set_cause(inv, st_code, NULL); + + /* Forcefully terminate the session if state is not DISCONNECTED */ + if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, NULL); + } + + /* Done. + * The dec_lock() below will actually destroys the dialog if it + * has no other session. + */ + pjsip_dlg_dec_lock(inv->dlg); + + return PJ_SUCCESS; +} + + +/* + * Restart UAC session, possibly because app or us wants to re-send the + * INVITE request due to 401/407 challenge or 3xx response. + */ +PJ_DEF(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv, + pj_bool_t new_offer) +{ + PJ_ASSERT_RETURN(inv, PJ_EINVAL); + + inv->state = PJSIP_INV_STATE_NULL; + inv->invite_tsx = NULL; + if (inv->last_answer) { + pjsip_tx_data_dec_ref(inv->last_answer); + inv->last_answer = NULL; + } + + if (new_offer && inv->neg) { + pjmedia_sdp_neg_state neg_state; + + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + } + + return PJ_SUCCESS; +} + + +static void *clone_sdp(pj_pool_t *pool, const void *data, unsigned len) +{ + PJ_UNUSED_ARG(len); + return pjmedia_sdp_session_clone(pool, (const pjmedia_sdp_session*)data); +} + +static int print_sdp(pjsip_msg_body *body, char *buf, pj_size_t len) +{ + return pjmedia_sdp_print((const pjmedia_sdp_session*)body->data, buf, len); +} + + +PJ_DEF(pj_status_t) pjsip_create_sdp_body( pj_pool_t *pool, + pjmedia_sdp_session *sdp, + pjsip_msg_body **p_body) +{ + const pj_str_t STR_APPLICATION = { "application", 11}; + const pj_str_t STR_SDP = { "sdp", 3 }; + pjsip_msg_body *body; + + body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body); + PJ_ASSERT_RETURN(body != NULL, PJ_ENOMEM); + + pjsip_media_type_init(&body->content_type, (pj_str_t*)&STR_APPLICATION, + (pj_str_t*)&STR_SDP); + body->data = sdp; + body->len = 0; + body->clone_data = &clone_sdp; + body->print_body = &print_sdp; + + *p_body = body; + + return PJ_SUCCESS; +} + +static pjsip_msg_body *create_sdp_body(pj_pool_t *pool, + const pjmedia_sdp_session *c_sdp) +{ + pjsip_msg_body *body; + pj_status_t status; + + status = pjsip_create_sdp_body(pool, + pjmedia_sdp_session_clone(pool, c_sdp), + &body); + + if (status != PJ_SUCCESS) + return NULL; + + return body; +} + +/* + * Create initial INVITE request. + */ +PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv, + pjsip_tx_data **p_tdata ) +{ + pjsip_tx_data *tdata; + const pjsip_hdr *hdr; + pj_bool_t has_sdp; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* State MUST be NULL or CONFIRMED. */ + PJ_ASSERT_RETURN(inv->state == PJSIP_INV_STATE_NULL || + inv->state == PJSIP_INV_STATE_CONFIRMED, + PJ_EINVALIDOP); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(inv->dlg); + + /* Create the INVITE request. */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_invite_method(), -1, + &tdata); + if (status != PJ_SUCCESS) + goto on_return; + + + /* If this is the first INVITE, then copy the headers from inv_hdr. + * These are the headers parsed from the request URI when the + * dialog was created. + */ + if (inv->state == PJSIP_INV_STATE_NULL) { + hdr = inv->dlg->inv_hdr.next; + + while (hdr != &inv->dlg->inv_hdr) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + hdr = hdr->next; + } + } + + /* See if we have SDP to send. */ + if (inv->neg) { + pjmedia_sdp_neg_state neg_state; + + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + + has_sdp = (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER || + (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && + pjmedia_sdp_neg_has_local_answer(inv->neg))); + + + } else { + has_sdp = PJ_FALSE; + } + + /* Add SDP, if any. */ + if (has_sdp) { + const pjmedia_sdp_session *offer; + + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } + + tdata->msg->body = create_sdp_body(tdata->pool, offer); + } + + /* Add Allow header. */ + if (inv->dlg->add_allow) { + hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_ALLOW, NULL); + if (hdr) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + } + } + + /* Add Supported header */ + hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL); + if (hdr) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + } + + /* Add Require header. */ + if ((inv->options & PJSIP_INV_REQUIRE_100REL) || + (inv->options & PJSIP_INV_REQUIRE_TIMER)) + { + pjsip_require_hdr *hreq; + + hreq = pjsip_require_hdr_create(tdata->pool); + + if (inv->options & PJSIP_INV_REQUIRE_100REL) + hreq->values[hreq->count++] = pj_str("100rel"); + if (inv->options & PJSIP_INV_REQUIRE_TIMER) + hreq->values[hreq->count++] = pj_str("timer"); + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hreq); + } + + status = pjsip_timer_update_req(inv, tdata); + if (status != PJ_SUCCESS) + goto on_return; + + /* Done. */ + *p_tdata = tdata; + + +on_return: + pjsip_dlg_dec_lock(inv->dlg); + return status; +} + + +/* Util: swap pool */ +static void swap_pool(pj_pool_t **p1, pj_pool_t **p2) +{ + pj_pool_t *tmp = *p1; + *p1 = *p2; + *p2 = tmp; +} + + +/* + * Initiate SDP negotiation in the SDP negotiator. + */ +static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv ) +{ + pj_status_t status; + + PJ_ASSERT_RETURN(pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_WAIT_NEGO, + PJMEDIA_SDPNEG_EINSTATE); + + status = pjmedia_sdp_neg_negotiate(inv->pool_prov, inv->neg, 0); + + PJ_LOG(5,(inv->obj_name, "SDP negotiation done, status=%d", status)); + + if (mod_inv.cb.on_media_update && inv->notify) + (*mod_inv.cb.on_media_update)(inv, status); + + /* Invite session may have been terminated by the application even + * after a successful SDP negotiation, for example when no audio + * codec is present in the offer (see ticket #1034). + */ + if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { + + /* Swap the flip-flop pool when SDP negotiation success. */ + if (status == PJ_SUCCESS) { + swap_pool(&inv->pool_prov, &inv->pool_active); + } + + /* Reset the provisional pool regardless SDP negotiation result. */ + pj_pool_reset(inv->pool_prov); + + } else { + + status = PJSIP_ERRNO_FROM_SIP_STATUS(inv->cause); + } + + return status; +} + +/* + * Check in incoming message for SDP offer/answer. + */ +static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv, + pjsip_transaction *tsx, + pjsip_rx_data *rdata) +{ + struct tsx_inv_data *tsx_inv_data; + pj_status_t status; + pjsip_msg *msg; + pjsip_rdata_sdp_info *sdp_info; + + /* Check if SDP is present in the message. */ + + msg = rdata->msg_info.msg; + if (msg->body == NULL) { + /* Message doesn't have body. */ + return PJ_SUCCESS; + } + + sdp_info = pjsip_rdata_get_sdp_info(rdata); + if (sdp_info->body.ptr == NULL) { + /* Message body is not "application/sdp" */ + return PJMEDIA_SDP_EINSDP; + } + + /* Get/attach invite session's transaction data */ + tsx_inv_data = (struct tsx_inv_data*) tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data == NULL) { + tsx_inv_data = PJ_POOL_ZALLOC_T(tsx->pool, struct tsx_inv_data); + tsx_inv_data->inv = inv; + tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; + } + + /* MUST NOT do multiple SDP offer/answer in a single transaction, + * EXCEPT if: + * - this is an initial UAC INVITE transaction (i.e. not re-INVITE), and + * - the previous negotiation was done on an early media (18x) and + * this response is a final/2xx response, and + * - the 2xx response has different To tag than the 18x response + * (i.e. the request has forked). + * + * The exception above is to add a rudimentary support for early media + * forking (sample case: custom ringback). See this ticket for more + * info: http://trac.pjsip.org/repos/ticket/657 + */ + if (tsx_inv_data->sdp_done) { + pj_str_t res_tag; + + res_tag = rdata->msg_info.to->tag; + + /* Allow final response after SDP has been negotiated in early + * media, IF this response is a final response with different + * tag. + */ + if (tsx->role == PJSIP_ROLE_UAC && + rdata->msg_info.msg->line.status.code/100 == 2 && + tsx_inv_data->done_early && + pj_strcmp(&tsx_inv_data->done_tag, &res_tag)) + { + const pjmedia_sdp_session *reoffer_sdp = NULL; + + PJ_LOG(4,(inv->obj_name, "Received forked final response " + "after SDP negotiation has been done in early " + "media. Renegotiating SDP..")); + + /* Retrieve original SDP offer from INVITE request */ + reoffer_sdp = (const pjmedia_sdp_session*) + tsx->last_tx->msg->body->data; + + /* Feed the original offer to negotiator */ + status = pjmedia_sdp_neg_modify_local_offer(inv->pool_prov, + inv->neg, + reoffer_sdp); + if (status != PJ_SUCCESS) { + PJ_LOG(1,(inv->obj_name, "Error updating local offer for " + "forked 2xx response (err=%d)", status)); + return status; + } + + } else { + + if (rdata->msg_info.msg->body) { + PJ_LOG(4,(inv->obj_name, "SDP negotiation done, message " + "body is ignored")); + } + return PJ_SUCCESS; + } + } + + /* Process the SDP body. */ + if (sdp_info->sdp_err) { + PJ_PERROR(4,(THIS_FILE, sdp_info->sdp_err, + "Error parsing SDP in %s", + pjsip_rx_data_get_info(rdata))); + return PJMEDIA_SDP_EINSDP; + } + + pj_assert(sdp_info->sdp != NULL); + + /* The SDP can be an offer or answer, depending on negotiator's state */ + + if (inv->neg == NULL || + pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE) + { + + /* This is an offer. */ + + PJ_LOG(5,(inv->obj_name, "Got SDP offer in %s", + pjsip_rx_data_get_info(rdata))); + + if (inv->neg == NULL) { + status=pjmedia_sdp_neg_create_w_remote_offer(inv->pool, NULL, + sdp_info->sdp, + &inv->neg); + } else { + status=pjmedia_sdp_neg_set_remote_offer(inv->pool_prov, inv->neg, + sdp_info->sdp); + } + + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP offer in %", + pjsip_rx_data_get_info(rdata))); + return PJMEDIA_SDP_EINSDP; + } + + /* Inform application about remote offer. */ + if (mod_inv.cb.on_rx_offer && inv->notify) { + + (*mod_inv.cb.on_rx_offer)(inv, sdp_info->sdp); + + } + + /* application must have supplied an answer at this point. */ + if (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) + { + return PJ_EINVALIDOP; + } + + } else if (pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + int status_code; + + /* This is an answer. + * Process and negotiate remote answer. + */ + + PJ_LOG(5,(inv->obj_name, "Got SDP answer in %s", + pjsip_rx_data_get_info(rdata))); + + status = pjmedia_sdp_neg_set_remote_answer(inv->pool_prov, inv->neg, + sdp_info->sdp); + + if (status != PJ_SUCCESS) { + PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP answer in %s", + pjsip_rx_data_get_info(rdata))); + return PJMEDIA_SDP_EINSDP; + } + + /* Negotiate SDP */ + + inv_negotiate_sdp(inv); + + /* Mark this transaction has having SDP offer/answer done, and + * save the reference to the To tag + */ + + tsx_inv_data->sdp_done = 1; + status_code = rdata->msg_info.msg->line.status.code; + tsx_inv_data->done_early = (status_code/100==1); + pj_strdup(tsx->pool, &tsx_inv_data->done_tag, + &rdata->msg_info.to->tag); + + } else { + + PJ_LOG(5,(THIS_FILE, "Ignored SDP in %s: negotiator state is %s", + pjsip_rx_data_get_info(rdata), + pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv->neg)))); + } + + return PJ_SUCCESS; +} + + +/* + * Process INVITE answer, for both initial and subsequent re-INVITE + */ +static pj_status_t process_answer( pjsip_inv_session *inv, + int st_code, + pjsip_tx_data *tdata, + const pjmedia_sdp_session *local_sdp) +{ + pj_status_t status; + const pjmedia_sdp_session *sdp = NULL; + + /* If local_sdp is specified, then we MUST NOT have answered the + * offer before. + */ + if (local_sdp && (st_code/100==1 || st_code/100==2)) { + + if (inv->neg == NULL) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + local_sdp, + &inv->neg); + } else if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) + { + status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, inv->neg, + local_sdp); + } else { + + /* Can not specify local SDP at this state. */ + pj_assert(0); + status = PJMEDIA_SDPNEG_EINSTATE; + } + + if (status != PJ_SUCCESS) + return status; + + } + + + /* If SDP negotiator is ready, start negotiation. */ + if (st_code/100==2 || (st_code/10==18 && st_code!=180)) { + + pjmedia_sdp_neg_state neg_state; + + /* Start nego when appropriate. */ + neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) : + PJMEDIA_SDP_NEG_STATE_NULL; + + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { + + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &sdp); + + } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO && + pjmedia_sdp_neg_has_local_answer(inv->neg) ) + { + struct tsx_inv_data *tsx_inv_data; + + /* Get invite session's transaction data */ + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; + + status = inv_negotiate_sdp(inv); + if (status != PJ_SUCCESS) + return status; + + /* Mark this transaction has having SDP offer/answer done. */ + tsx_inv_data->sdp_done = 1; + + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + } + } + + /* Include SDP when it's available for 2xx and 18x (but not 180) response. + * Subsequent response will include this SDP. + * + * Note note: + * - When offer/answer has been completed in reliable 183, we MUST NOT + * send SDP in 2xx response. So if we don't have SDP to send, clear + * the SDP in the message body ONLY if 100rel is active in this + * session. + */ + if (sdp) { + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } else { + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + tdata->msg->body = NULL; + } + } + + + return PJ_SUCCESS; +} + + +/* + * Create first response to INVITE + */ +PJ_DEF(pj_status_t) pjsip_inv_initial_answer( pjsip_inv_session *inv, + pjsip_rx_data *rdata, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *sdp, + pjsip_tx_data **p_tdata) +{ + pjsip_tx_data *tdata; + pj_status_t status; + pjsip_status_code st_code2; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* Must have INVITE transaction. */ + PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG); + + pj_log_push_indent(); + + pjsip_dlg_inc_lock(inv->dlg); + + /* Create response */ + status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, st_text, + &tdata); + if (status != PJ_SUCCESS) + goto on_return; + + /* Invoke Session Timers module */ + status = pjsip_timer_process_req(inv, rdata, &st_code2); + if (status != PJ_SUCCESS) { + pj_status_t status2; + + status2 = pjsip_dlg_modify_response(inv->dlg, tdata, st_code2, NULL); + if (status2 != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } + status2 = pjsip_timer_update_resp(inv, tdata); + if (status2 == PJ_SUCCESS) + *p_tdata = tdata; + else + pjsip_tx_data_dec_ref(tdata); + + goto on_return; + } + + /* Process SDP in answer */ + status = process_answer(inv, st_code, tdata, sdp); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(tdata); + goto on_return; + } + + /* Save this answer */ + inv->last_answer = tdata; + pjsip_tx_data_add_ref(inv->last_answer); + PJ_LOG(5,(inv->dlg->obj_name, "Initial answer %s", + pjsip_tx_data_get_info(inv->last_answer))); + + /* Invoke Session Timers */ + pjsip_timer_update_resp(inv, tdata); + + *p_tdata = tdata; + +on_return: + pjsip_dlg_dec_lock(inv->dlg); + pj_log_pop_indent(); + return status; +} + + +/* + * Answer initial INVITE + * Re-INVITE will be answered automatically, and will not use this function. + */ +PJ_DEF(pj_status_t) pjsip_inv_answer( pjsip_inv_session *inv, + int st_code, + const pj_str_t *st_text, + const pjmedia_sdp_session *local_sdp, + pjsip_tx_data **p_tdata ) +{ + pjsip_tx_data *last_res; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* Must have INVITE transaction. */ + PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG); + + /* Must have created an answer before */ + PJ_ASSERT_RETURN(inv->last_answer, PJ_EINVALIDOP); + + pj_log_push_indent(); + + pjsip_dlg_inc_lock(inv->dlg); + + /* Modify last response. */ + last_res = inv->last_answer; + status = pjsip_dlg_modify_response(inv->dlg, last_res, st_code, st_text); + if (status != PJ_SUCCESS) + goto on_return; + + /* For non-2xx final response, strip message body */ + if (st_code >= 300) { + last_res->msg->body = NULL; + } + + /* Process SDP in answer */ + status = process_answer(inv, st_code, last_res, local_sdp); + if (status != PJ_SUCCESS) { + pjsip_tx_data_dec_ref(last_res); + goto on_return; + } + + /* Invoke Session Timers */ + pjsip_timer_update_resp(inv, last_res); + + *p_tdata = last_res; + +on_return: + pjsip_dlg_dec_lock(inv->dlg); + pj_log_pop_indent(); + return status; +} + + +/* + * Set local SDP offer/answer. + */ +PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv, + const pjmedia_sdp_session *sdp ) +{ + const pjmedia_sdp_session *offer; + pj_status_t status; + + PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL); + + /* If we have remote SDP offer, set local answer to respond to the offer, + * otherwise we set/modify our local offer (and create an SDP negotiator + * if we don't have one yet). + */ + if (inv->neg) { + pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg); + + if ((neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER || + neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) && + pjmedia_sdp_neg_get_neg_remote(inv->neg, &offer) == PJ_SUCCESS) + { + status = pjsip_inv_set_sdp_answer(inv, sdp); + } else if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) { + status = pjmedia_sdp_neg_modify_local_offer(inv->pool, + inv->neg, sdp); + } else + return PJMEDIA_SDPNEG_EINSTATE; + } else { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + sdp, &inv->neg); + } + + return status; +} + + +/* + * Set SDP answer. + */ +PJ_DEF(pj_status_t) pjsip_inv_set_sdp_answer( pjsip_inv_session *inv, + const pjmedia_sdp_session *sdp ) +{ + pj_status_t status; + + PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL); + + pjsip_dlg_inc_lock(inv->dlg); + status = pjmedia_sdp_neg_set_local_answer( inv->pool_prov, inv->neg, sdp); + pjsip_dlg_dec_lock(inv->dlg); + + return status; +} + + +/* + * End session. + */ +PJ_DEF(pj_status_t) pjsip_inv_end_session( pjsip_inv_session *inv, + int st_code, + const pj_str_t *st_text, + pjsip_tx_data **p_tdata ) +{ + pjsip_tx_data *tdata; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + pj_log_push_indent(); + + /* Set cause code. */ + inv_set_cause(inv, st_code, st_text); + + /* Create appropriate message. */ + switch (inv->state) { + case PJSIP_INV_STATE_CALLING: + case PJSIP_INV_STATE_EARLY: + case PJSIP_INV_STATE_INCOMING: + + if (inv->role == PJSIP_ROLE_UAC) { + + /* For UAC when session has not been confirmed, create CANCEL. */ + + /* MUST have the original UAC INVITE transaction. */ + PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG); + + /* But CANCEL should only be called when we have received a + * provisional response. If we haven't received any responses, + * just destroy the transaction. + */ + if (inv->invite_tsx->status_code < 100) { + + /* Do not stop INVITE retransmission, see ticket #506 */ + //pjsip_tsx_stop_retransmit(inv->invite_tsx); + inv->cancelling = PJ_TRUE; + inv->pending_cancel = PJ_TRUE; + *p_tdata = NULL; + PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no " + "provisional response is received yet")); + pj_log_pop_indent(); + return PJ_SUCCESS; + } + + /* The CSeq here assumes that the dialog is started with an + * INVITE session. This may not be correct; dialog can be + * started as SUBSCRIBE session. + * So fix this! + */ + status = pjsip_endpt_create_cancel(inv->dlg->endpt, + inv->invite_tsx->last_tx, + &tdata); + if (status != PJ_SUCCESS) { + pj_log_pop_indent(); + return status; + } + + /* Set timeout for the INVITE transaction, in case UAS is not + * able to respond the INVITE with 487 final response. The + * timeout value is 64*T1. + */ + pjsip_tsx_set_timeout(inv->invite_tsx, 64 * pjsip_cfg()->tsx.t1); + + } else { + + /* For UAS, send a final response. */ + tdata = inv->invite_tsx->last_tx; + PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP); + + //status = pjsip_dlg_modify_response(inv->dlg, tdata, st_code, + // st_text); + status = pjsip_inv_answer(inv, st_code, st_text, NULL, &tdata); + } + break; + + case PJSIP_INV_STATE_CONNECTING: + case PJSIP_INV_STATE_CONFIRMED: + /* End Session Timer */ + pjsip_timer_end_session(inv); + + /* For established dialog, send BYE */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), + -1, &tdata); + break; + + case PJSIP_INV_STATE_DISCONNECTED: + /* No need to do anything. */ + pj_log_pop_indent(); + return PJSIP_ESESSIONTERMINATED; + + default: + pj_assert(!"Invalid operation!"); + pj_log_pop_indent(); + return PJ_EINVALIDOP; + } + + if (status != PJ_SUCCESS) { + pj_log_pop_indent(); + return status; + } + + + /* Done */ + + inv->cancelling = PJ_TRUE; + *p_tdata = tdata; + + pj_log_pop_indent(); + return PJ_SUCCESS; +} + +/* Following redirection recursion, get next target from the target set and + * notify user. + * + * Returns PJ_FALSE if recursion fails (either because there's no more target + * or user rejects the recursion). If we return PJ_FALSE, caller should + * disconnect the session. + * + * Note: + * the event 'e' argument may be NULL. + */ +static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code, + const pj_str_t *reason, pjsip_event *e) +{ + pjsip_redirect_op op; + pjsip_target *target; + + /* Won't redirect if the callback is not implemented. */ + if (mod_inv.cb.on_redirected == NULL) + return PJ_FALSE; + + if (reason == NULL) + reason = pjsip_get_status_text(code); + + /* Set status of current target */ + pjsip_target_assign_status(inv->dlg->target_set.current, inv->dlg->pool, + code, reason); + + /* Fetch next target from the target set. We only want to + * process SIP/SIPS URI for now. + */ + for (;;) { + target = pjsip_target_set_get_next(&inv->dlg->target_set); + if (target == NULL) { + /* No more target. */ + return PJ_FALSE; + } + + if (!PJSIP_URI_SCHEME_IS_SIP(target->uri) && + !PJSIP_URI_SCHEME_IS_SIPS(target->uri)) + { + code = PJSIP_SC_UNSUPPORTED_URI_SCHEME; + reason = pjsip_get_status_text(code); + + /* Mark this target as unusable and fetch next target. */ + pjsip_target_assign_status(target, inv->dlg->pool, code, reason); + } else { + /* Found a target */ + break; + } + } + + /* We have target in 'target'. Set this target as current target + * and notify callback. + */ + pjsip_target_set_set_current(&inv->dlg->target_set, target); + + op = (*mod_inv.cb.on_redirected)(inv, target->uri, e); + + + /* Check what the application wants to do now */ + switch (op) { + case PJSIP_REDIRECT_ACCEPT: + case PJSIP_REDIRECT_STOP: + /* Must increment session counter, that's the convention of the + * pjsip_inv_process_redirect(). + */ + pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); + + /* Act on the recursion */ + pjsip_inv_process_redirect(inv, op, e); + return PJ_TRUE; + + case PJSIP_REDIRECT_PENDING: + /* Increment session so that the dialog/session is not destroyed + * while we're waiting for user confirmation. + */ + pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod); + + /* Also clear the invite_tsx variable, otherwise when this tsx is + * terminated, it will also terminate the session. + */ + inv->invite_tsx = NULL; + + /* Done. The processing will continue once the application calls + * pjsip_inv_process_redirect(). + */ + return PJ_TRUE; + + case PJSIP_REDIRECT_REJECT: + /* Recursively call this function again to fetch next target, if any. + */ + return inv_uac_recurse(inv, PJSIP_SC_REQUEST_TERMINATED, NULL, e); + + } + + pj_assert(!"Should not reach here"); + return PJ_FALSE; +} + + +/* Process redirection/recursion */ +PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv, + pjsip_redirect_op op, + pjsip_event *e) +{ + const pjsip_status_code cancel_code = PJSIP_SC_REQUEST_TERMINATED; + pjsip_event usr_event; + pj_status_t status = PJ_SUCCESS; + + PJ_ASSERT_RETURN(inv && op != PJSIP_REDIRECT_PENDING, PJ_EINVAL); + + if (e == NULL) { + PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL); + e = &usr_event; + } + + pjsip_dlg_inc_lock(inv->dlg); + + /* Decrement session. That's the convention here to prevent the dialog + * or session from being destroyed while we're waiting for user + * confirmation. + */ + pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod); + + /* See what the application wants to do now */ + switch (op) { + case PJSIP_REDIRECT_ACCEPT: + /* User accept the redirection. Reset the session and resend the + * INVITE request. + */ + { + pjsip_tx_data *tdata; + pjsip_via_hdr *via; + + /* Get the original INVITE request. */ + tdata = inv->invite_req; + pjsip_tx_data_add_ref(tdata); + + /* Restore strict route set. + * See http://trac.pjsip.org/repos/ticket/492 + */ + pjsip_restore_strict_route_set(tdata); + + /* Set target */ + tdata->msg->line.req.uri = (pjsip_uri*) + pjsip_uri_clone(tdata->pool, inv->dlg->target_set.current->uri); + + /* Remove branch param in Via header. */ + via = (pjsip_via_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + via->branch_param.slen = 0; + + /* Reset message destination info (see #1248). */ + pj_bzero(&tdata->dest_info, sizeof(tdata->dest_info)); + + /* Must invalidate the message! */ + pjsip_tx_data_invalidate_msg(tdata); + + /* Reset the session */ + pjsip_inv_uac_restart(inv, PJ_FALSE); + + /* (re)Send the INVITE request */ + status = pjsip_inv_send_msg(inv, tdata); + } + break; + + case PJSIP_REDIRECT_STOP: + /* User doesn't want the redirection. Disconnect the session now. */ + inv_set_cause(inv, cancel_code, pjsip_get_status_text(cancel_code)); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + /* Caller should expect that the invite session is gone now, so + * we don't need to set status to PJSIP_ESESSIONTERMINATED here. + */ + break; + + case PJSIP_REDIRECT_REJECT: + /* Current target is rejected. Fetch next target if any. */ + if (inv_uac_recurse(inv, cancel_code, NULL, NULL) == PJ_FALSE) { + inv_set_cause(inv, cancel_code, + pjsip_get_status_text(cancel_code)); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + /* Tell caller that the invite session is gone now */ + status = PJSIP_ESESSIONTERMINATED; + } + break; + + + case PJSIP_REDIRECT_PENDING: + pj_assert(!"Should not happen"); + break; + } + + + pjsip_dlg_dec_lock(inv->dlg); + + return status; +} + + +/* + * Create re-INVITE. + */ +PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv, + const pj_str_t *new_contact, + const pjmedia_sdp_session *new_offer, + pjsip_tx_data **p_tdata ) +{ + pj_status_t status; + pjsip_contact_hdr *contact_hdr = NULL; + + /* Check arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* Must NOT have a pending INVITE transaction */ + if (inv->invite_tsx!=NULL) + return PJ_EINVALIDOP; + + pj_log_push_indent(); + + pjsip_dlg_inc_lock(inv->dlg); + + if (new_contact) { + pj_str_t tmp; + const pj_str_t STR_CONTACT = { "Contact", 7 }; + + pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); + contact_hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, + tmp.ptr, tmp.slen, NULL); + if (!contact_hdr) { + status = PJSIP_EINVALIDURI; + goto on_return; + } + } + + + if (new_offer) { + if (!inv->neg) { + status = pjmedia_sdp_neg_create_w_local_offer(inv->pool, + new_offer, + &inv->neg); + if (status != PJ_SUCCESS) + goto on_return; + + } else switch (pjmedia_sdp_neg_get_state(inv->neg)) { + + case PJMEDIA_SDP_NEG_STATE_NULL: + pj_assert(!"Unexpected SDP neg state NULL"); + status = PJ_EBUG; + goto on_return; + + case PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER: + PJ_LOG(4,(inv->obj_name, + "pjsip_inv_reinvite: already have an offer, new " + "offer is ignored")); + break; + + case PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER: + status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, + inv->neg, + new_offer); + if (status != PJ_SUCCESS) + goto on_return; + break; + + case PJMEDIA_SDP_NEG_STATE_WAIT_NEGO: + PJ_LOG(4,(inv->obj_name, + "pjsip_inv_reinvite: SDP in WAIT_NEGO state, new " + "offer is ignored")); + break; + + case PJMEDIA_SDP_NEG_STATE_DONE: + status = pjmedia_sdp_neg_modify_local_offer(inv->pool_prov, + inv->neg, + new_offer); + if (status != PJ_SUCCESS) + goto on_return; + break; + } + } + + if (contact_hdr) + inv->dlg->local.contact = contact_hdr; + + status = pjsip_inv_invite(inv, p_tdata); + +on_return: + pjsip_dlg_dec_lock(inv->dlg); + pj_log_pop_indent(); + return status; +} + +/* + * Create UPDATE. + */ +PJ_DEF(pj_status_t) pjsip_inv_update ( pjsip_inv_session *inv, + const pj_str_t *new_contact, + const pjmedia_sdp_session *offer, + pjsip_tx_data **p_tdata ) +{ + pjsip_contact_hdr *contact_hdr = NULL; + pjsip_tx_data *tdata = NULL; + pjmedia_sdp_session *sdp_copy; + pj_status_t status = PJ_SUCCESS; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* Dialog must have been established */ + PJ_ASSERT_RETURN(inv->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED, + PJ_EINVALIDOP); + + /* Invite session must not have been disconnected */ + PJ_ASSERT_RETURN(inv->state < PJSIP_INV_STATE_DISCONNECTED, + PJ_EINVALIDOP); + + pj_log_push_indent(); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(inv->dlg); + + /* Process offer, if any */ + if (offer) { + if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) { + PJ_LOG(4,(inv->dlg->obj_name, + "Invalid SDP offer/answer state for UPDATE")); + status = PJ_EINVALIDOP; + goto on_error; + } + + /* Notify negotiator about the new offer. This will fix the offer + * with correct SDP origin. + */ + status = pjmedia_sdp_neg_modify_local_offer(inv->pool_prov, inv->neg, + offer); + if (status != PJ_SUCCESS) + goto on_error; + + /* Retrieve the "fixed" offer from negotiator */ + pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + } + + /* Update Contact if required */ + if (new_contact) { + pj_str_t tmp; + const pj_str_t STR_CONTACT = { "Contact", 7 }; + + pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact); + contact_hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT, + tmp.ptr, tmp.slen, NULL); + if (!contact_hdr) { + status = PJSIP_EINVALIDURI; + goto on_error; + } + + inv->dlg->local.contact = contact_hdr; + } + + /* Create request */ + status = pjsip_dlg_create_request(inv->dlg, &pjsip_update_method, + -1, &tdata); + if (status != PJ_SUCCESS) + goto on_error; + + /* Attach SDP body */ + if (offer) { + sdp_copy = pjmedia_sdp_session_clone(tdata->pool, offer); + pjsip_create_sdp_body(tdata->pool, sdp_copy, &tdata->msg->body); + } + + /* Unlock dialog. */ + pjsip_dlg_dec_lock(inv->dlg); + + status = pjsip_timer_update_req(inv, tdata); + if (status != PJ_SUCCESS) + goto on_error; + + *p_tdata = tdata; + + pj_log_pop_indent(); + return PJ_SUCCESS; + +on_error: + if (tdata) + pjsip_tx_data_dec_ref(tdata); + + /* Unlock dialog. */ + pjsip_dlg_dec_lock(inv->dlg); + + pj_log_pop_indent(); + return status; +} + +/* + * Create an ACK request. + */ +PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv, + int cseq, + pjsip_tx_data **p_tdata) +{ + const pjmedia_sdp_session *sdp = NULL; + pj_status_t status; + + PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(inv->dlg); + + /* Destroy last_ack */ + if (inv->last_ack) { + pjsip_tx_data_dec_ref(inv->last_ack); + inv->last_ack = NULL; + } + + /* Create new ACK request */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_ack_method(), + cseq, &inv->last_ack); + if (status != PJ_SUCCESS) { + pjsip_dlg_dec_lock(inv->dlg); + return status; + } + + /* See if we have pending SDP answer to send */ + sdp = inv_has_pending_answer(inv, inv->invite_tsx); + if (sdp) { + inv->last_ack->msg->body = create_sdp_body(inv->last_ack->pool, sdp); + } + + /* Keep this for subsequent response retransmission */ + inv->last_ack_cseq = cseq; + pjsip_tx_data_add_ref(inv->last_ack); + + /* Done */ + *p_tdata = inv->last_ack; + + /* Unlock dialog. */ + pjsip_dlg_dec_lock(inv->dlg); + + return PJ_SUCCESS; +} + +/* + * Send a request or response message. + */ +PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv, + pjsip_tx_data *tdata) +{ + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL); + + pj_log_push_indent(); + + PJ_LOG(5,(inv->obj_name, "Sending %s", + pjsip_tx_data_get_info(tdata))); + + if (tdata->msg->type == PJSIP_REQUEST_MSG) { + struct tsx_inv_data *tsx_inv_data; + + pjsip_dlg_inc_lock(inv->dlg); + + /* Check again that we didn't receive incoming re-INVITE */ + if (tdata->msg->line.req.method.id==PJSIP_INVITE_METHOD && + inv->invite_tsx) + { + pjsip_tx_data_dec_ref(tdata); + pjsip_dlg_dec_lock(inv->dlg); + status = PJ_EINVALIDOP; + goto on_error; + } + + /* Associate our data in outgoing invite transaction */ + tsx_inv_data = PJ_POOL_ZALLOC_T(inv->pool, struct tsx_inv_data); + tsx_inv_data->inv = inv; + + pjsip_dlg_dec_lock(inv->dlg); + + status = pjsip_dlg_send_request(inv->dlg, tdata, mod_inv.mod.id, + tsx_inv_data); + if (status != PJ_SUCCESS) { + goto on_error; + } + + } else { + pjsip_cseq_hdr *cseq; + + /* Can only do this to send response to original INVITE + * request. + */ + PJ_ASSERT_RETURN((cseq=(pjsip_cseq_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL))!=NULL + && (cseq->cseq == inv->invite_tsx->cseq), + PJ_EINVALIDOP); + + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + status = pjsip_100rel_tx_response(inv, tdata); + } else + { + status = pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + } + + if (status != PJ_SUCCESS) { + goto on_error; + } + } + + /* Done */ + pj_log_pop_indent(); + return PJ_SUCCESS; + +on_error: + pj_log_pop_indent(); + return status; +} + + +/* + * Respond to incoming CANCEL request. + */ +static void inv_respond_incoming_cancel(pjsip_inv_session *inv, + pjsip_transaction *cancel_tsx, + pjsip_rx_data *rdata) +{ + pjsip_tx_data *tdata; + pjsip_transaction *invite_tsx; + pj_str_t key; + pj_status_t status; + + /* See if we have matching INVITE server transaction: */ + + pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS, + pjsip_get_invite_method(), rdata); + invite_tsx = pjsip_tsx_layer_find_tsx(&key, PJ_TRUE); + + if (invite_tsx == NULL) { + + /* Invite transaction not found! + * Respond CANCEL with 481 (RFC 3261 Section 9.2 page 55) + */ + status = pjsip_dlg_create_response( inv->dlg, rdata, 481, NULL, + &tdata); + + } else { + /* Always answer CANCEL will 200 (OK) regardless of + * the state of the INVITE transaction. + */ + status = pjsip_dlg_create_response( inv->dlg, rdata, 200, NULL, + &tdata); + } + + /* See if we have created the response successfully. */ + if (status != PJ_SUCCESS) return; + + /* Send the CANCEL response */ + status = pjsip_dlg_send_response(inv->dlg, cancel_tsx, tdata); + if (status != PJ_SUCCESS) return; + + + /* See if we need to terminate the UAS INVITE transaction + * with 487 (Request Terminated) response. + */ + if (invite_tsx && invite_tsx->status_code < 200) { + + pj_assert(invite_tsx->last_tx != NULL); + + tdata = invite_tsx->last_tx; + + status = pjsip_dlg_modify_response(inv->dlg, tdata, 487, NULL); + if (status == PJ_SUCCESS) { + /* Remove the message body */ + tdata->msg->body = NULL; + if (inv->options & PJSIP_INV_REQUIRE_100REL) { + status = pjsip_100rel_tx_response(inv, tdata); + } else { + status = pjsip_dlg_send_response(inv->dlg, invite_tsx, + tdata); + } + } + } + + if (invite_tsx) + pj_mutex_unlock(invite_tsx->mutex); +} + + +/* + * Respond to incoming BYE request. + */ +static void inv_respond_incoming_bye( pjsip_inv_session *inv, + pjsip_transaction *bye_tsx, + pjsip_rx_data *rdata, + pjsip_event *e ) +{ + pj_status_t status; + pjsip_tx_data *tdata; + + /* Respond BYE with 200: */ + + status = pjsip_dlg_create_response(inv->dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) return; + + status = pjsip_dlg_send_response(inv->dlg, bye_tsx, tdata); + if (status != PJ_SUCCESS) return; + + /* Terminate session: */ + + if (inv->state != PJSIP_INV_STATE_DISCONNECTED) { + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } +} + +/* + * Respond to BYE request. + */ +static void inv_handle_bye_response( pjsip_inv_session *inv, + pjsip_transaction *tsx, + pjsip_rx_data *rdata, + pjsip_event *e ) +{ + pj_status_t status; + + if (e->body.tsx_state.type != PJSIP_EVENT_RX_MSG) { + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + return; + } + + /* Handle 401/407 challenge. */ + if (tsx->status_code == 401 || tsx->status_code == 407) { + + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + rdata, + tsx->last_tx, + &tdata); + + if (status != PJ_SUCCESS) { + + /* Does not have proper credentials. + * End the session anyway. + */ + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + } else { + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send BYE. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + } else { + + /* End the session. */ + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + +} + +/* + * Respond to incoming UPDATE request. + */ +static void inv_respond_incoming_update(pjsip_inv_session *inv, + pjsip_rx_data *rdata) +{ + pjmedia_sdp_neg_state neg_state; + pj_status_t status; + pjsip_tx_data *tdata = NULL; + pjsip_status_code st_code; + + /* Invoke Session Timers module */ + status = pjsip_timer_process_req(inv, rdata, &st_code); + if (status != PJ_SUCCESS) { + status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, + NULL, &tdata); + goto on_return; + } + + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + + /* Send 491 if we receive UPDATE while we're waiting for an answer */ + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) { + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, NULL, + &tdata); + } + /* Send 500 with Retry-After header set randomly between 0 and 10 if we + * receive UPDATE while we haven't sent answer. + */ + else if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER || + neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) { + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_INTERNAL_SERVER_ERROR, + NULL, &tdata); + + /* If UPDATE doesn't contain SDP, just respond with 200/OK. + * This is a valid scenario according to session-timer draft. + */ + } else if (rdata->msg_info.msg->body == NULL) { + + status = pjsip_dlg_create_response(inv->dlg, rdata, + 200, NULL, &tdata); + + } else { + /* We receive new offer from remote */ + inv_check_sdp_in_incoming_msg(inv, pjsip_rdata_get_tsx(rdata), rdata); + + /* Application MUST have supplied the answer by now. + * If so, negotiate the SDP. + */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO || + (status=inv_negotiate_sdp(inv)) != PJ_SUCCESS) + { + /* Negotiation has failed. If negotiator is still + * stuck at non-DONE state, cancel any ongoing offer. + */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state != PJMEDIA_SDP_NEG_STATE_DONE) { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_NOT_ACCEPTABLE_HERE, + NULL, &tdata); + } else { + /* New media has been negotiated successfully, send 200/OK */ + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_OK, NULL, &tdata); + if (status == PJ_SUCCESS) { + const pjmedia_sdp_session *sdp; + status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp); + if (status == PJ_SUCCESS) + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } + } + } + +on_return: + /* Invoke Session Timers */ + if (status == PJ_SUCCESS) + status = pjsip_timer_update_resp(inv, tdata); + + if (status != PJ_SUCCESS) { + if (tdata != NULL) { + pjsip_tx_data_dec_ref(tdata); + tdata = NULL; + } + return; + } + + pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), tdata); +} + + +/* + * Handle incoming response to UAC UPDATE request. + */ +static pj_bool_t inv_handle_update_response( pjsip_inv_session *inv, + pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + struct tsx_inv_data *tsx_inv_data; + pj_bool_t handled = PJ_FALSE; + pj_status_t status = -1; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + pj_assert(tsx_inv_data); + + /* Handle 401/407 challenge. */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + (tsx->status_code == 401 || tsx->status_code == 407)) + { + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, + &tdata); + + if (status != PJ_SUCCESS) { + + /* Somehow failed. Probably it's not a good idea to terminate + * the session since this is just a request within dialog. And + * even if we terminate we should send BYE. + */ + /* + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + */ + + } else { + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send request. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + handled = PJ_TRUE; + } + + /* Process 422 response */ + else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->status_code == 422) + { + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + handled = PJ_TRUE; + } + + /* Process 2xx response */ + else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->status_code/100 == 2 && + e->body.tsx_state.src.rdata->msg_info.msg->body) + { + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + status = inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + handled = PJ_TRUE; + } + + /* Get/attach invite session's transaction data */ + else + { + /* Session-Timer needs to see any error responses, to determine + * whether peer supports UPDATE with empty body. + */ + if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->role == PJSIP_ROLE_UAC) + { + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + handled = PJ_TRUE; + } + } + + /* Cancel the negotiation if we don't get successful negotiation by now, + * unless it's authentication challenge and the request is being retried. + */ + if (pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + tsx_inv_data && tsx_inv_data->sdp_done == PJ_FALSE && + !tsx_inv_data->retrying) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + + /* Prevent from us cancelling different offer! */ + tsx_inv_data->sdp_done = PJ_TRUE; + } + + return handled; +} + + +/* + * Handle incoming reliable response. + */ +static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv, + pjsip_rx_data *rdata) +{ + pjsip_tx_data *tdata; + const pjmedia_sdp_session *sdp; + pj_status_t status; + + /* Create PRACK */ + status = pjsip_100rel_create_prack(inv, rdata, &tdata); + if (status != PJ_SUCCESS) + return; + + /* See if we need to attach SDP answer on the PRACK request */ + sdp = inv_has_pending_answer(inv, pjsip_rdata_get_tsx(rdata)); + if (sdp) { + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } + + /* Send PRACK (must be using 100rel module!) */ + pjsip_100rel_send_prack(inv, tdata); +} + + +/* + * Handle incoming PRACK. + */ +static void inv_respond_incoming_prack(pjsip_inv_session *inv, + pjsip_rx_data *rdata) +{ + pj_status_t status; + + /* Run through 100rel module to see if we can accept this + * PRACK request. The 100rel will send 200/OK to PRACK request. + */ + status = pjsip_100rel_on_rx_prack(inv, rdata); + if (status != PJ_SUCCESS) + return; + + /* Now check for SDP answer in the PRACK request */ + if (rdata->msg_info.msg->body) { + status = inv_check_sdp_in_incoming_msg(inv, + pjsip_rdata_get_tsx(rdata), rdata); + } else { + /* No SDP body */ + status = -1; + } + + /* If SDP negotiation has been successful, also mark the + * SDP negotiation flag in the invite transaction to be + * done too. + */ + if (status == PJ_SUCCESS && inv->invite_tsx) { + struct tsx_inv_data *tsx_inv_data; + + /* Get/attach invite session's transaction data */ + tsx_inv_data = (struct tsx_inv_data*) + inv->invite_tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data == NULL) { + tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, + struct tsx_inv_data); + tsx_inv_data->inv = inv; + inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data; + } + + tsx_inv_data->sdp_done = PJ_TRUE; + } +} + + +/* + * State NULL is before anything is sent/received. + */ +static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx->method.id == PJSIP_INVITE_METHOD) { + + /* Keep the initial INVITE transaction. */ + if (inv->invite_tsx == NULL) + inv->invite_tsx = tsx; + + if (dlg->role == PJSIP_ROLE_UAC) { + + /* Save the original INVITE request, if on_redirected() callback + * is implemented. We may need to resend the INVITE if we receive + * redirection response. + */ + if (mod_inv.cb.on_redirected) { + if (inv->invite_req) { + pjsip_tx_data_dec_ref(inv->invite_req); + inv->invite_req = NULL; + } + inv->invite_req = tsx->last_tx; + pjsip_tx_data_add_ref(inv->invite_req); + } + + switch (tsx->state) { + case PJSIP_TSX_STATE_CALLING: + inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); + break; + default: + inv_on_state_calling(inv, e); + break; + } + + } else { + switch (tsx->state) { + case PJSIP_TSX_STATE_TRYING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + break; + case PJSIP_TSX_STATE_PROCEEDING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + if (tsx->status_code > 100) + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + break; + case PJSIP_TSX_STATE_TERMINATED: + /* there is a failure in sending response. */ + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + break; + default: + inv_on_state_incoming(inv, e); + break; + } + } + + } else { + pj_assert(!"Unexpected transaction type"); + } +} + +/* + * Generic UAC transaction handler: + * - resend request on 401 or 407 response. + * - terminate dialog on 408 and 481 response. + * - resend request on 422 response. + */ +static pj_bool_t handle_uac_tsx_response(pjsip_inv_session *inv, + pjsip_event *e) +{ + /* RFC 3261 Section 12.2.1.2: + * If the response for a request within a dialog is a 481 + * (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the UAC + * SHOULD terminate the dialog. A UAC SHOULD also terminate a dialog if + * no response at all is received for the request (the client + * transaction would inform the TU about the timeout.) + * + * For INVITE initiated dialogs, terminating the dialog consists of + * sending a BYE. + * + * Note: + * according to X, this should terminate dialog usage only, not the + * dialog. + */ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + + pj_assert(tsx->role == PJSIP_UAC_ROLE); + + /* Note that 481 response to CANCEL does not terminate dialog usage, + * but only the transaction. + */ + if (inv->state != PJSIP_INV_STATE_DISCONNECTED && + ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && + tsx->method.id != PJSIP_CANCEL_METHOD) || + tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT || + tsx->status_code == PJSIP_SC_TSX_TIMEOUT || + tsx->status_code == PJSIP_SC_TSX_TRANSPORT_ERROR)) + { + pjsip_tx_data *bye; + pj_status_t status; + + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + + /* Send BYE */ + status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(), + -1, &bye); + if (status == PJ_SUCCESS) { + pjsip_inv_send_msg(inv, bye); + } + + return PJ_TRUE; /* Handled */ + + } + /* Handle 401/407 challenge. */ + else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + (tsx->status_code == PJSIP_SC_UNAUTHORIZED || + tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED)) + { + pjsip_tx_data *tdata; + pj_status_t status; + + if (tsx->method.id == PJSIP_INVITE_METHOD) + inv->invite_tsx = NULL; + + status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, &tdata); + + if (status != PJ_SUCCESS) { + /* Somehow failed. Probably it's not a good idea to terminate + * the session since this is just a request within dialog. And + * even if we terminate we should send BYE. + */ + /* + inv_set_cause(inv, PJSIP_SC_OK, NULL); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + */ + + } else { + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + if (tsx_inv_data) + tsx_inv_data->retrying = PJ_TRUE; + + /* Re-send request. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + return PJ_TRUE; /* Handled */ + } + + /* Handle session timer 422 response. */ + else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) + { + handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_FALSE); + + return PJ_TRUE; /* Handled */ + + } else { + return PJ_FALSE; /* Unhandled */ + } +} + + +/* Handle call rejection, especially with regard to processing call + * redirection. We need to handle the following scenarios: + * - 3xx response is received -- see if on_redirected() callback is + * implemented. If so, add the Contact URIs in the response to the + * target set and notify user. + * - 4xx - 6xx resposne is received -- see if we're currently recursing, + * if so fetch the next target if any and notify the on_redirected() + * callback. + * - for other cases -- disconnect the session. + */ +static void handle_uac_call_rejection(pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pj_status_t status; + + if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300)) { + + if (mod_inv.cb.on_redirected == NULL) { + + /* Redirection callback is not implemented, disconnect the + * call. + */ + goto terminate_session; + + } else { + const pjsip_msg *res_msg; + + res_msg = e->body.tsx_state.src.rdata->msg_info.msg; + + /* Gather all Contact URI's in the response and add them + * to target set. The function will take care of removing + * duplicate URI's. + */ + pjsip_target_set_add_from_msg(&inv->dlg->target_set, + inv->dlg->pool, res_msg); + + /* Recurse to alternate targets if application allows us */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) + { + /* Recursion fails, terminate session now */ + goto terminate_session; + } + + /* Done */ + } + + } else if ((tsx->status_code==401 || tsx->status_code==407) && + !inv->cancelling) + { + + /* Handle authentication failure: + * Resend the request with Authorization header. + */ + pjsip_tx_data *tdata; + + status = pjsip_auth_clt_reinit_req(&inv->dlg->auth_sess, + e->body.tsx_state.src.rdata, + tsx->last_tx, + &tdata); + + if (status != PJ_SUCCESS) { + + /* Does not have proper credentials. If we are currently + * recursing, try the next target. Otherwise end the session. + */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) + { + /* Recursion fails, terminate session now */ + goto terminate_session; + } + + } else { + + /* Restart session. */ + pjsip_inv_uac_restart(inv, PJ_FALSE); + + /* Send the request. */ + status = pjsip_inv_send_msg(inv, tdata); + } + + } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED && + tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) + { + /* Handle session timer 422 response: + * Resend the request with requested session timer setting. + */ + status = handle_timer_response(inv, e->body.tsx_state.src.rdata, + PJ_TRUE); + + } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 600)) { + /* Global error */ + goto terminate_session; + + } else { + /* See if we have alternate target to try */ + if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) { + /* Recursion fails, terminate session now */ + goto terminate_session; + } + } + return; + +terminate_session: + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); +} + + +/* + * State CALLING is after sending initial INVITE request but before + * any response (with tag) is received. + */ +static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + pj_status_t status; + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx == inv->invite_tsx) { + + switch (tsx->state) { + + case PJSIP_TSX_STATE_CALLING: + inv_set_state(inv, PJSIP_INV_STATE_CALLING, e); + break; + + case PJSIP_TSX_STATE_PROCEEDING: + if (inv->pending_cancel) { + pjsip_tx_data *cancel; + + inv->pending_cancel = PJ_FALSE; + + status = pjsip_inv_end_session(inv, 487, NULL, &cancel); + if (status == PJ_SUCCESS && cancel) + status = pjsip_inv_send_msg(inv, cancel); + } + + if (dlg->remote.info->tag.slen) { + + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { + inv_handle_incoming_reliable_response( + inv, e->body.tsx_state.src.rdata); + } + + } else { + /* Ignore 100 (Trying) response, as it doesn't change + * session state. It only ceases retransmissions. + */ + } + break; + + case PJSIP_TSX_STATE_COMPLETED: + if (tsx->status_code/100 == 2) { + + /* This should not happen. + * When transaction receives 2xx, it should be terminated + */ + pj_assert(0); + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + } else { + handle_uac_call_rejection(inv, e); + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 == 2) { + /* This must be receipt of 2xx response */ + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + /* Set state to CONNECTING */ + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + /* Send ACK */ + pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + + inv_send_ack(inv, e); + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + default: + break; + } + + } else if (tsx->role == PJSIP_ROLE_UAC) { + /* + * Handle case when outgoing request is answered with 481 (Call/ + * Transaction Does Not Exist), 408, or when it's timed out. In these + * cases, disconnect session (i.e. dialog usage only). + * Note that 481 response to CANCEL does not terminate dialog usage, + * but only the transaction. + */ + if ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST && + tsx->method.id != PJSIP_CANCEL_METHOD) || + tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT || + tsx->status_code == PJSIP_SC_TSX_TIMEOUT || + tsx->status_code == PJSIP_SC_TSX_TRANSPORT_ERROR) + { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + } +} + +/* + * State INCOMING is after we received the request, but before + * responses with tag are sent. + */ +static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx == inv->invite_tsx) { + + /* + * Handle the INVITE state transition. + */ + + switch (tsx->state) { + + case PJSIP_TSX_STATE_TRYING: + inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e); + break; + + case PJSIP_TSX_STATE_PROCEEDING: + /* + * Transaction sent provisional response. + */ + if (tsx->status_code > 100) + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + break; + + case PJSIP_TSX_STATE_COMPLETED: + /* + * Transaction sent final response. + */ + if (tsx->status_code/100 == 2) { + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* + * This happens on transport error (e.g. failed to send + * response) + */ + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + break; + + default: + pj_assert(!"Unexpected INVITE state"); + break; + } + + } else if (tsx->method.id == PJSIP_CANCEL_METHOD && + tsx->role == PJSIP_ROLE_UAS && + tsx->state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) + { + + /* + * Handle incoming CANCEL request. + */ + + inv_respond_incoming_cancel(inv, tsx, e->body.tsx_state.src.rdata); + + } +} + +/* + * State EARLY is for both UAS and UAC, after response with To tag + * is sent/received. + */ +static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx == inv->invite_tsx) { + + /* + * Handle the INVITE state progress. + */ + + switch (tsx->state) { + + case PJSIP_TSX_STATE_PROCEEDING: + /* Send/received another provisional response. */ + inv_set_state(inv, PJSIP_INV_STATE_EARLY, e); + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) { + inv_handle_incoming_reliable_response( + inv, e->body.tsx_state.src.rdata); + } + } + break; + + case PJSIP_TSX_STATE_COMPLETED: + if (tsx->status_code/100 == 2) { + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + pj_status_t status; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + } else if (tsx->role == PJSIP_ROLE_UAC) { + + handle_uac_call_rejection(inv, e); + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + case PJSIP_TSX_STATE_CONFIRMED: + /* For some reason can go here (maybe when ACK for 2xx has + * the same branch value as the INVITE transaction) */ + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 == 2) { + + /* This must be receipt of 2xx response */ + + /* Set state to CONNECTING */ + inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e); + + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + pj_status_t status; + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + break; + + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + /* if UAC, send ACK and move state to confirmed. */ + if (tsx->role == PJSIP_ROLE_UAC) { + pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG); + + inv_send_ack(inv, e); + } + + } else { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } + break; + + default: + pj_assert(!"Unexpected INVITE tsx state"); + } + + } else if (inv->role == PJSIP_ROLE_UAS && + tsx->role == PJSIP_ROLE_UAS && + tsx->method.id == PJSIP_CANCEL_METHOD && + tsx->state < PJSIP_TSX_STATE_COMPLETED && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG ) + { + + /* + * Handle incoming CANCEL request. + */ + + inv_respond_incoming_cancel(inv, tsx, e->body.tsx_state.src.rdata); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata); + + + } else if (tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle response to outgoing UPDATE request. + */ + inv_handle_update_response(inv, e); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + { + /* + * Handle incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + + } else if (tsx->role == PJSIP_ROLE_UAC) { + + /* Generic handling for UAC tsx completion */ + handle_uac_tsx_response(inv, e); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->method.id == PJSIP_BYE_METHOD && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + /* Received BYE before the 2xx/OK response to INVITE. + * Assume that the 2xx/OK response is lost and the BYE + * arrives earlier. + */ + inv_respond_incoming_bye(inv, tsx, e->body.tsx_state.src.rdata, e); + + if (inv->invite_tsx->role == PJSIP_ROLE_UAC) { + /* Set timer just in case we will never get the final response + * for INVITE. + */ + pjsip_tsx_set_timeout(inv->invite_tsx, 64*pjsip_cfg()->tsx.t1); + } else if (inv->invite_tsx->status_code < 200) { + pjsip_tx_data *tdata; + pjsip_msg *msg; + + /* For UAS, send a final response. */ + tdata = inv->invite_tsx->last_tx; + PJ_ASSERT_ON_FAIL(tdata != NULL, return); + + msg = tdata->msg; + msg->line.status.code = PJSIP_SC_REQUEST_TERMINATED; + msg->line.status.reason = + *pjsip_get_status_text(PJSIP_SC_REQUEST_TERMINATED); + msg->body = NULL; + + pjsip_tx_data_invalidate_msg(tdata); + pjsip_tx_data_add_ref(tdata); + + pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata); + } + } +} + +/* + * State CONNECTING is after 2xx response to INVITE is sent/received. + */ +static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx == inv->invite_tsx) { + + /* + * Handle INVITE state progression. + */ + switch (tsx->state) { + + case PJSIP_TSX_STATE_CONFIRMED: + /* It can only go here if incoming ACK request has the same Via + * branch parameter as the INVITE transaction. + */ + if (tsx->status_code/100 == 2) { + if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + } + + inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, e); + } + break; + + case PJSIP_TSX_STATE_TERMINATED: + /* INVITE transaction can be terminated either because UAC + * transaction received 2xx response or because of transport + * error. + */ + if (tsx->status_code/100 != 2) { + if (tsx->role == PJSIP_ROLE_UAC) { + inv_set_cause(inv, tsx->status_code, &tsx->status_text); + inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e); + } else { + pjsip_tx_data *bye; + pj_status_t status; + + /* Send BYE */ + status = pjsip_dlg_create_request(inv->dlg, + pjsip_get_bye_method(), + -1, &bye); + if (status == PJ_SUCCESS) { + pjsip_inv_send_msg(inv, bye); + } + } + } + break; + + case PJSIP_TSX_STATE_DESTROYED: + /* Do nothing. */ + break; + + default: + pj_assert(!"Unexpected state"); + } + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->method.id == PJSIP_BYE_METHOD && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + + /* + * Handle incoming BYE. + */ + + inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); + + } else if (tsx->method.id == PJSIP_BYE_METHOD && + tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED)) + { + + /* + * Outgoing BYE + */ + inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); + + } + else if (tsx->method.id == PJSIP_CANCEL_METHOD && + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + + /* + * Handle strandled incoming CANCEL. + */ + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) return; + + status = pjsip_dlg_send_response(dlg, tsx, tdata); + if (status != PJ_SUCCESS) return; + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_invite_method)==0) + { + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + + /* See https://trac.pjsip.org/repos/ticket/1455 + * Handle incoming re-INVITE before current INVITE is confirmed. + * According to RFC 5407: + * - answer with 200 if we don't have pending offer-answer + * - answer with 491 if we *have* pending offer-answer + * + * But unfortunately accepting the re-INVITE would mean we have + * two outstanding INVITEs, and we don't support that because + * we will get confused when we handle the ACK. + */ + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata); + + + } else if (tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle response to outgoing UPDATE request. + */ + if (inv_handle_update_response(inv, e) == PJ_FALSE) + handle_uac_tsx_response(inv, e); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + { + /* + * Handle incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + + } else if (tsx->role == PJSIP_ROLE_UAC) { + + /* Generic handling for UAC tsx completion */ + handle_uac_tsx_response(inv, e); + + } + +} + +/* + * State CONFIRMED is after ACK is sent/received. + */ +static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + + if (tsx->method.id == PJSIP_BYE_METHOD && + tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED)) + { + + /* + * Outgoing BYE + */ + + inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e); + + } + else if (tsx->method.id == PJSIP_BYE_METHOD && + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + + /* + * Handle incoming BYE. + */ + + inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e ); + + } + else if (tsx->method.id == PJSIP_CANCEL_METHOD && + tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + + /* + * Handle strandled incoming CANCEL. + */ + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) return; + + status = pjsip_dlg_send_response(dlg, tsx, tdata); + if (status != PJ_SUCCESS) return; + + } + else if (tsx->method.id == PJSIP_INVITE_METHOD && + tsx->role == PJSIP_ROLE_UAS) + { + + /* + * Handle incoming re-INVITE + */ + if (tsx->state == PJSIP_TSX_STATE_TRYING) { + + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + pj_status_t status; + pjsip_rdata_sdp_info *sdp_info; + pjsip_status_code st_code; + + /* Check if we have INVITE pending. */ + if (inv->invite_tsx && inv->invite_tsx!=tsx) { + int code; + pj_str_t reason; + + reason = pj_str("Another INVITE transaction in progress"); + + if (inv->invite_tsx->role == PJSIP_ROLE_UAC) + code = 491; + else + code = 500; + + /* Can not receive re-INVITE while another one is pending. */ + status = pjsip_dlg_create_response( inv->dlg, rdata, code, + &reason, &tdata); + if (status != PJ_SUCCESS) + return; + + if (code == 500) { + /* MUST include Retry-After header with random value + * between 0-10. + */ + pjsip_retry_after_hdr *ra_hdr; + int val = (pj_rand() % 10); + + ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr); + } + + status = pjsip_dlg_send_response( inv->dlg, tsx, tdata); + + + return; + } + + /* Save the invite transaction. */ + inv->invite_tsx = tsx; + + /* Process session timers headers in the re-INVITE */ + status = pjsip_timer_process_req(inv, rdata, &st_code); + if (status != PJ_SUCCESS) { + status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); + return; + } + + /* Send 491 if we receive re-INVITE while another offer/answer + * negotiation is in progress + */ + if (pjmedia_sdp_neg_get_state(inv->neg) != + PJMEDIA_SDP_NEG_STATE_DONE) + { + status = pjsip_dlg_create_response(inv->dlg, rdata, + PJSIP_SC_REQUEST_PENDING, + NULL, &tdata); + if (status != PJ_SUCCESS) + return; + pjsip_timer_update_resp(inv, tdata); + status = pjsip_dlg_send_response(dlg, tsx, tdata); + return; + } + + /* Process SDP in incoming message. */ + status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata); + + if (status != PJ_SUCCESS) { + + /* Not Acceptable */ + const pjsip_hdr *accept; + + /* The incoming SDP is unacceptable. If the SDP negotiator + * state has just been changed, i.e: DONE -> REMOTE_OFFER, + * revert it back. + */ + if (pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + status = pjsip_dlg_create_response(inv->dlg, rdata, + 488, NULL, &tdata); + if (status != PJ_SUCCESS) + return; + + + accept = pjsip_endpt_get_capability(dlg->endpt, PJSIP_H_ACCEPT, + NULL); + if (accept) { + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, accept)); + } + + status = pjsip_dlg_send_response(dlg, tsx, tdata); + + return; + } + + /* Create 2xx ANSWER */ + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) + return; + + /* If the INVITE request has SDP body, send answer. + * Otherwise generate offer from local active SDP. + */ + sdp_info = pjsip_rdata_get_sdp_info(rdata); + if (sdp_info->sdp != NULL) { + status = process_answer(inv, 200, tdata, NULL); + } else { + /* INVITE does not have SDP. + * If on_create_offer() callback is implemented, ask app. + * to generate an offer, otherwise just send active local + * SDP to signal that nothing gets modified. + */ + pjmedia_sdp_session *sdp = NULL; + + if (mod_inv.cb.on_create_offer) { + (*mod_inv.cb.on_create_offer)(inv, &sdp); + if (sdp) { + /* Notify negotiator about the new offer. This will + * fix the offer with correct SDP origin. + */ + status = + pjmedia_sdp_neg_modify_local_offer(inv->pool_prov, + inv->neg, + sdp); + + /* Retrieve the "fixed" offer from negotiator */ + if (status==PJ_SUCCESS) { + const pjmedia_sdp_session *lsdp = NULL; + pjmedia_sdp_neg_get_neg_local(inv->neg, &lsdp); + sdp = (pjmedia_sdp_session*)lsdp; + } + } + } + + if (sdp == NULL) { + const pjmedia_sdp_session *active_sdp = NULL; + status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, + inv->neg, + &active_sdp); + if (status == PJ_SUCCESS) + sdp = (pjmedia_sdp_session*) active_sdp; + } + + if (sdp) { + tdata->msg->body = create_sdp_body(tdata->pool, sdp); + } + } + + if (status != PJ_SUCCESS) { + /* + * SDP negotiation has failed. + */ + pj_status_t rc; + pj_str_t reason; + + /* Delete the 2xx answer */ + pjsip_tx_data_dec_ref(tdata); + + /* Create 500 response */ + reason = pj_str("SDP negotiation failed"); + rc = pjsip_dlg_create_response(dlg, rdata, 500, &reason, + &tdata); + if (rc == PJ_SUCCESS) { + pjsip_warning_hdr *w; + const pj_str_t *endpt_name; + + endpt_name = pjsip_endpt_name(dlg->endpt); + w = pjsip_warning_hdr_create_from_status(tdata->pool, + endpt_name, + status); + if (w) + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w); + + pjsip_inv_send_msg(inv, tdata); + } + return; + } + + /* Invoke Session Timers */ + pjsip_timer_update_resp(inv, tdata); + + /* Send 2xx regardless of the status of negotiation */ + status = pjsip_inv_send_msg(inv, tdata); + + } else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) { + /* This is the case where ACK has the same branch as + * the INVITE request. + */ + if (tsx->status_code/100 == 2 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + /* Check if local offer got no SDP answer */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + } + + } + + } + else if (tsx->method.id == PJSIP_INVITE_METHOD && + tsx->role == PJSIP_ROLE_UAC) + { + + /* + * Handle outgoing re-INVITE + */ + if (tsx->state == PJSIP_TSX_STATE_CALLING) { + + /* Must not have other pending INVITE transaction */ + pj_assert(inv->invite_tsx==NULL || tsx==inv->invite_tsx); + + /* Save pending invite transaction */ + inv->invite_tsx = tsx; + + } else if (tsx->state == PJSIP_TSX_STATE_TERMINATED && + tsx->status_code/100 == 2) + { + pj_status_t status; + + /* Re-INVITE was accepted. */ + + /* Process session timer response. */ + status = handle_timer_response(inv, + e->body.tsx_state.src.rdata, + PJ_TRUE); + if (status != PJ_SUCCESS) + return; + + /* Process SDP */ + inv_check_sdp_in_incoming_msg(inv, tsx, + e->body.tsx_state.src.rdata); + + /* Check if local offer got no SDP answer */ + if (pjmedia_sdp_neg_get_state(inv->neg)== + PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + /* Send ACK */ + inv_send_ack(inv, e); + + } else if (handle_uac_tsx_response(inv, e)) { + + /* Handle response that terminates dialog */ + /* Nothing to do (already handled) */ + + } else if (tsx->status_code >= 300 && tsx->status_code < 700) { + + pjmedia_sdp_neg_state neg_state; + struct tsx_inv_data *tsx_inv_data; + + tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id]; + + /* Outgoing INVITE transaction has failed, cancel SDP nego */ + neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER && + tsx_inv_data->retrying == PJ_FALSE) + { + pjmedia_sdp_neg_cancel_offer(inv->neg); + } + + if (tsx == inv->invite_tsx) + inv->invite_tsx = NULL; + } + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle incoming UPDATE + */ + inv_respond_incoming_update(inv, e->body.tsx_state.src.rdata); + + } else if (tsx->role == PJSIP_ROLE_UAC && + (tsx->state == PJSIP_TSX_STATE_COMPLETED || + tsx->state == PJSIP_TSX_STATE_TERMINATED) && + pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0) + { + /* + * Handle response to outgoing UPDATE request. + */ + if (inv_handle_update_response(inv, e) == PJ_FALSE) + handle_uac_tsx_response(inv, e); + + } else if (tsx->role == PJSIP_ROLE_UAS && + tsx->state == PJSIP_TSX_STATE_TRYING && + pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0) + { + /* + * Handle strandled incoming PRACK + */ + inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata); + + } else if (tsx->role == PJSIP_ROLE_UAC) { + /* + * Handle 401/407/408/481/422 response + */ + handle_uac_tsx_response(inv, e); + } + +} + +/* + * After session has been terminated, but before dialog is destroyed + * (because dialog has other usages, or because dialog is waiting for + * the last transaction to terminate). + */ +static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e) +{ + pjsip_transaction *tsx = e->body.tsx_state.tsx; + pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx); + + PJ_ASSERT_ON_FAIL(tsx && dlg, return); + + if (tsx->role == PJSIP_ROLE_UAS && + tsx->status_code < 200 && + e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) + { + pjsip_rx_data *rdata = e->body.tsx_state.src.rdata; + + /* + * Respond BYE with 200/OK + */ + if (tsx->method.id == PJSIP_BYE_METHOD) { + inv_respond_incoming_bye( inv, tsx, rdata, e ); + } else if (tsx->method.id == PJSIP_CANCEL_METHOD) { + /* + * Respond CANCEL with 200/OK too. + */ + pjsip_tx_data *tdata; + pj_status_t status; + + status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata); + if (status != PJ_SUCCESS) return; + + status = pjsip_dlg_send_response(dlg, tsx, tdata); + if (status != PJ_SUCCESS) return; + + } + + } else if (tsx->role == PJSIP_ROLE_UAC) { + /* + * Handle 401/407/408/481/422 response + */ + handle_uac_tsx_response(inv, e); + } +} + diff --git a/pjsip/src/pjsip-ua/sip_reg.c b/pjsip/src/pjsip-ua/sip_reg.c new file mode 100644 index 0000000..bd1fb21 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_reg.c @@ -0,0 +1,1333 @@ +/* $Id: sip_reg.c 4173 2012-06-20 10:39:05Z ming $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_regc.h> +#include <pjsip/sip_endpoint.h> +#include <pjsip/sip_parser.h> +#include <pjsip/sip_module.h> +#include <pjsip/sip_transaction.h> +#include <pjsip/sip_event.h> +#include <pjsip/sip_util.h> +#include <pjsip/sip_auth_msg.h> +#include <pjsip/sip_errno.h> +#include <pj/assert.h> +#include <pj/guid.h> +#include <pj/lock.h> +#include <pj/os.h> +#include <pj/pool.h> +#include <pj/log.h> +#include <pj/rand.h> +#include <pj/string.h> + + +#define REFRESH_TIMER 1 +#define DELAY_BEFORE_REFRESH PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH +#define THIS_FILE "sip_reg.c" + +/* Outgoing transaction timeout when server sends 100 but never replies + * with final response. Value is in MILISECONDS! + */ +#define REGC_TSX_TIMEOUT 33000 + +enum { NOEXP = 0x1FFFFFFF }; + +static const pj_str_t XUID_PARAM_NAME = { "x-uid", 5 }; + + +/* Current/pending operation */ +enum regc_op +{ + REGC_IDLE, + REGC_REGISTERING, + REGC_UNREGISTERING +}; + +/** + * SIP client registration structure. + */ +struct pjsip_regc +{ + pj_pool_t *pool; + pjsip_endpoint *endpt; + pj_lock_t *lock; + pj_bool_t _delete_flag; + pj_bool_t has_tsx; + pj_atomic_t *busy_ctr; + enum regc_op current_op; + + pj_bool_t add_xuid_param; + + void *token; + pjsip_regc_cb *cb; + + pj_str_t str_srv_url; + pjsip_uri *srv_url; + pjsip_cid_hdr *cid_hdr; + pjsip_cseq_hdr *cseq_hdr; + pj_str_t from_uri; + pjsip_from_hdr *from_hdr; + pjsip_to_hdr *to_hdr; + pjsip_contact_hdr contact_hdr_list; + pjsip_contact_hdr removed_contact_hdr_list; + pjsip_expires_hdr *expires_hdr; + pj_uint32_t expires; + pj_uint32_t delay_before_refresh; + pjsip_route_hdr route_set; + pjsip_hdr hdr_list; + pjsip_host_port via_addr; + const void *via_tp; + + /* Authorization sessions. */ + pjsip_auth_clt_sess auth_sess; + + /* Auto refresh registration. */ + pj_bool_t auto_reg; + pj_time_val last_reg; + pj_time_val next_reg; + pj_timer_entry timer; + + /* Transport selector */ + pjsip_tpselector tp_sel; + + /* Last transport used. We acquire the transport to keep + * it open. + */ + pjsip_transport *last_transport; +}; + + +PJ_DEF(pj_status_t) pjsip_regc_create( pjsip_endpoint *endpt, void *token, + pjsip_regc_cb *cb, + pjsip_regc **p_regc) +{ + pj_pool_t *pool; + pjsip_regc *regc; + pj_status_t status; + + /* Verify arguments. */ + PJ_ASSERT_RETURN(endpt && cb && p_regc, PJ_EINVAL); + + pool = pjsip_endpt_create_pool(endpt, "regc%p", 1024, 1024); + PJ_ASSERT_RETURN(pool != NULL, PJ_ENOMEM); + + regc = PJ_POOL_ZALLOC_T(pool, pjsip_regc); + + regc->pool = pool; + regc->endpt = endpt; + regc->token = token; + regc->cb = cb; + regc->expires = PJSIP_REGC_EXPIRATION_NOT_SPECIFIED; + regc->add_xuid_param = pjsip_cfg()->regc.add_xuid_param; + + status = pj_lock_create_recursive_mutex(pool, pool->obj_name, + ®c->lock); + if (status != PJ_SUCCESS) { + pj_pool_release(pool); + return status; + } + + status = pj_atomic_create(pool, 0, ®c->busy_ctr); + if (status != PJ_SUCCESS) { + pj_lock_destroy(regc->lock); + pj_pool_release(pool); + return status; + } + + status = pjsip_auth_clt_init(®c->auth_sess, endpt, regc->pool, 0); + if (status != PJ_SUCCESS) + return status; + + pj_list_init(®c->route_set); + pj_list_init(®c->hdr_list); + pj_list_init(®c->contact_hdr_list); + pj_list_init(®c->removed_contact_hdr_list); + + /* Done */ + *p_regc = regc; + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_destroy(pjsip_regc *regc) +{ + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + if (regc->has_tsx || pj_atomic_get(regc->busy_ctr) != 0) { + regc->_delete_flag = 1; + regc->cb = NULL; + pj_lock_release(regc->lock); + } else { + pjsip_tpselector_dec_ref(®c->tp_sel); + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + if (regc->timer.id != 0) { + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + } + pj_atomic_destroy(regc->busy_ctr); + pj_lock_release(regc->lock); + pj_lock_destroy(regc->lock); + regc->lock = NULL; + pjsip_endpt_release_pool(regc->endpt, regc->pool); + } + + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_get_info( pjsip_regc *regc, + pjsip_regc_info *info ) +{ + PJ_ASSERT_RETURN(regc && info, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + + info->server_uri = regc->str_srv_url; + info->client_uri = regc->from_uri; + info->is_busy = (pj_atomic_get(regc->busy_ctr) || regc->has_tsx); + info->auto_reg = regc->auto_reg; + info->interval = regc->expires; + info->transport = regc->last_transport; + + if (regc->has_tsx) + info->next_reg = 0; + else if (regc->auto_reg == 0) + info->next_reg = 0; + else if (regc->expires < 0) + info->next_reg = regc->expires; + else { + pj_time_val now, next_reg; + + next_reg = regc->next_reg; + pj_gettimeofday(&now); + PJ_TIME_VAL_SUB(next_reg, now); + info->next_reg = next_reg.sec; + } + + pj_lock_release(regc->lock); + + return PJ_SUCCESS; +} + + +PJ_DEF(pj_pool_t*) pjsip_regc_get_pool(pjsip_regc *regc) +{ + return regc->pool; +} + +static void set_expires( pjsip_regc *regc, pj_uint32_t expires) +{ + if (expires != regc->expires) { + regc->expires_hdr = pjsip_expires_hdr_create(regc->pool, expires); + } else { + regc->expires_hdr = NULL; + } +} + + +static pj_status_t set_contact( pjsip_regc *regc, + int contact_cnt, + const pj_str_t contact[] ) +{ + const pj_str_t CONTACT = { "Contact", 7 }; + pjsip_contact_hdr *h; + int i; + + /* Save existing contact list to removed_contact_hdr_list and + * clear contact_hdr_list. + */ + pj_list_merge_last(®c->removed_contact_hdr_list, + ®c->contact_hdr_list); + + /* Set the expiration of Contacts in to removed_contact_hdr_list + * zero. + */ + h = regc->removed_contact_hdr_list.next; + while (h != ®c->removed_contact_hdr_list) { + h->expires = 0; + h = h->next; + } + + /* Process new contacts */ + for (i=0; i<contact_cnt; ++i) { + pjsip_contact_hdr *hdr; + pj_str_t tmp; + + pj_strdup_with_null(regc->pool, &tmp, &contact[i]); + hdr = (pjsip_contact_hdr*) + pjsip_parse_hdr(regc->pool, &CONTACT, tmp.ptr, tmp.slen, NULL); + if (hdr == NULL) { + PJ_LOG(4,(THIS_FILE, "Invalid Contact: \"%.*s\"", + (int)tmp.slen, tmp.ptr)); + return PJSIP_EINVALIDURI; + } + + /* Find the new contact in old contact list. If found, remove + * the old header from the old header list. + */ + h = regc->removed_contact_hdr_list.next; + while (h != ®c->removed_contact_hdr_list) { + int rc; + + rc = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, + h->uri, hdr->uri); + if (rc == 0) { + /* Match */ + pj_list_erase(h); + break; + } + + h = h->next; + } + + /* If add_xuid_param option is enabled and Contact URI is sip/sips, + * add xuid parameter to assist matching the Contact URI in the + * REGISTER response later. + */ + if (regc->add_xuid_param && (PJSIP_URI_SCHEME_IS_SIP(hdr->uri) || + PJSIP_URI_SCHEME_IS_SIPS(hdr->uri))) + { + pjsip_param *xuid_param; + pjsip_sip_uri *sip_uri; + + xuid_param = PJ_POOL_ZALLOC_T(regc->pool, pjsip_param); + xuid_param->name = XUID_PARAM_NAME; + pj_create_unique_string(regc->pool, &xuid_param->value); + + sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(hdr->uri); + pj_list_push_back(&sip_uri->other_param, xuid_param); + } + + pj_list_push_back(®c->contact_hdr_list, hdr); + } + + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_init( pjsip_regc *regc, + const pj_str_t *srv_url, + const pj_str_t *from_url, + const pj_str_t *to_url, + int contact_cnt, + const pj_str_t contact[], + pj_uint32_t expires) +{ + pj_str_t tmp; + pj_status_t status; + + PJ_ASSERT_RETURN(regc && srv_url && from_url && to_url && + contact_cnt && contact && expires, PJ_EINVAL); + + /* Copy server URL. */ + pj_strdup_with_null(regc->pool, ®c->str_srv_url, srv_url); + + /* Set server URL. */ + tmp = regc->str_srv_url; + regc->srv_url = pjsip_parse_uri( regc->pool, tmp.ptr, tmp.slen, 0); + if (regc->srv_url == NULL) { + return PJSIP_EINVALIDURI; + } + + /* Set "From" header. */ + pj_strdup_with_null(regc->pool, ®c->from_uri, from_url); + tmp = regc->from_uri; + regc->from_hdr = pjsip_from_hdr_create(regc->pool); + regc->from_hdr->uri = pjsip_parse_uri(regc->pool, tmp.ptr, tmp.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); + if (!regc->from_hdr->uri) { + PJ_LOG(4,(THIS_FILE, "regc: invalid source URI %.*s", + from_url->slen, from_url->ptr)); + return PJSIP_EINVALIDURI; + } + + /* Set "To" header. */ + pj_strdup_with_null(regc->pool, &tmp, to_url); + regc->to_hdr = pjsip_to_hdr_create(regc->pool); + regc->to_hdr->uri = pjsip_parse_uri(regc->pool, tmp.ptr, tmp.slen, + PJSIP_PARSE_URI_AS_NAMEADDR); + if (!regc->to_hdr->uri) { + PJ_LOG(4,(THIS_FILE, "regc: invalid target URI %.*s", to_url->slen, to_url->ptr)); + return PJSIP_EINVALIDURI; + } + + + /* Set "Contact" header. */ + status = set_contact( regc, contact_cnt, contact); + if (status != PJ_SUCCESS) + return status; + + /* Set "Expires" header, if required. */ + set_expires( regc, expires); + regc->delay_before_refresh = DELAY_BEFORE_REFRESH; + + /* Set "Call-ID" header. */ + regc->cid_hdr = pjsip_cid_hdr_create(regc->pool); + pj_create_unique_string(regc->pool, ®c->cid_hdr->id); + + /* Set "CSeq" header. */ + regc->cseq_hdr = pjsip_cseq_hdr_create(regc->pool); + regc->cseq_hdr->cseq = pj_rand() % 0xFFFF; + pjsip_method_set( ®c->cseq_hdr->method, PJSIP_REGISTER_METHOD); + + /* Done. */ + return PJ_SUCCESS; +} + +PJ_DEF(pj_status_t) pjsip_regc_set_credentials( pjsip_regc *regc, + int count, + const pjsip_cred_info cred[] ) +{ + PJ_ASSERT_RETURN(regc && count && cred, PJ_EINVAL); + return pjsip_auth_clt_set_credentials(®c->auth_sess, count, cred); +} + +PJ_DEF(pj_status_t) pjsip_regc_set_prefs( pjsip_regc *regc, + const pjsip_auth_clt_pref *pref) +{ + PJ_ASSERT_RETURN(regc && pref, PJ_EINVAL); + return pjsip_auth_clt_set_prefs(®c->auth_sess, pref); +} + +PJ_DEF(pj_status_t) pjsip_regc_set_route_set( pjsip_regc *regc, + const pjsip_route_hdr *route_set) +{ + const pjsip_route_hdr *chdr; + + PJ_ASSERT_RETURN(regc && route_set, PJ_EINVAL); + + pj_list_init(®c->route_set); + + chdr = route_set->next; + while (chdr != route_set) { + pj_list_push_back(®c->route_set, pjsip_hdr_clone(regc->pool, chdr)); + chdr = chdr->next; + } + + return PJ_SUCCESS; +} + + +/* + * Bind client registration to a specific transport/listener. + */ +PJ_DEF(pj_status_t) pjsip_regc_set_transport( pjsip_regc *regc, + const pjsip_tpselector *sel) +{ + PJ_ASSERT_RETURN(regc && sel, PJ_EINVAL); + + pjsip_tpselector_dec_ref(®c->tp_sel); + pj_memcpy(®c->tp_sel, sel, sizeof(*sel)); + pjsip_tpselector_add_ref(®c->tp_sel); + + return PJ_SUCCESS; +} + +/* Release transport */ +PJ_DEF(pj_status_t) pjsip_regc_release_transport(pjsip_regc *regc) +{ + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_add_headers( pjsip_regc *regc, + const pjsip_hdr *hdr_list) +{ + const pjsip_hdr *hdr; + + PJ_ASSERT_RETURN(regc && hdr_list, PJ_EINVAL); + + //This is "add" operation, so don't remove headers. + //pj_list_init(®c->hdr_list); + + hdr = hdr_list->next; + while (hdr != hdr_list) { + pj_list_push_back(®c->hdr_list, pjsip_hdr_clone(regc->pool, hdr)); + hdr = hdr->next; + } + + return PJ_SUCCESS; +} + +static pj_status_t create_request(pjsip_regc *regc, + pjsip_tx_data **p_tdata) +{ + pj_status_t status; + pjsip_tx_data *tdata; + + PJ_ASSERT_RETURN(regc && p_tdata, PJ_EINVAL); + + /* Create the request. */ + status = pjsip_endpt_create_request_from_hdr( regc->endpt, + pjsip_get_register_method(), + regc->srv_url, + regc->from_hdr, + regc->to_hdr, + NULL, + regc->cid_hdr, + regc->cseq_hdr->cseq, + NULL, + &tdata); + if (status != PJ_SUCCESS) + return status; + + /* Add cached authorization headers. */ + pjsip_auth_clt_init_req( ®c->auth_sess, tdata ); + + /* Add Route headers from route set, ideally after Via header */ + if (!pj_list_empty(®c->route_set)) { + pjsip_hdr *route_pos; + const pjsip_route_hdr *route; + + route_pos = (pjsip_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + if (!route_pos) + route_pos = &tdata->msg->hdr; + + route = regc->route_set.next; + while (route != ®c->route_set) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, route); + pj_list_insert_after(route_pos, new_hdr); + route_pos = new_hdr; + route = route->next; + } + } + + /* Add additional request headers */ + if (!pj_list_empty(®c->hdr_list)) { + const pjsip_hdr *hdr; + + hdr = regc->hdr_list.next; + while (hdr != ®c->hdr_list) { + pjsip_hdr *new_hdr = (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr); + pjsip_msg_add_hdr(tdata->msg, new_hdr); + hdr = hdr->next; + } + } + + /* Done. */ + *p_tdata = tdata; + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_register(pjsip_regc *regc, pj_bool_t autoreg, + pjsip_tx_data **p_tdata) +{ + pjsip_msg *msg; + pjsip_contact_hdr *hdr; + const pjsip_hdr *h_allow; + pj_status_t status; + pjsip_tx_data *tdata; + + PJ_ASSERT_RETURN(regc && p_tdata, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + + status = create_request(regc, &tdata); + if (status != PJ_SUCCESS) { + pj_lock_release(regc->lock); + return status; + } + + msg = tdata->msg; + + /* Add Contact headers. */ + hdr = regc->contact_hdr_list.next; + while (hdr != ®c->contact_hdr_list) { + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + hdr = hdr->next; + } + + /* Also add bindings which are to be removed */ + while (!pj_list_empty(®c->removed_contact_hdr_list)) { + hdr = regc->removed_contact_hdr_list.next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + pj_list_erase(hdr); + } + + + if (regc->expires_hdr) + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, + regc->expires_hdr)); + + if (regc->timer.id != 0) { + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + } + + /* Add Allow header (http://trac.pjsip.org/repos/ticket/1039) */ + h_allow = pjsip_endpt_get_capability(regc->endpt, PJSIP_H_ALLOW, NULL); + if (h_allow) { + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, h_allow)); + + } + + regc->auto_reg = autoreg; + + pj_lock_release(regc->lock); + + /* Done */ + *p_tdata = tdata; + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_unregister(pjsip_regc *regc, + pjsip_tx_data **p_tdata) +{ + pjsip_tx_data *tdata; + pjsip_msg *msg; + pjsip_hdr *hdr; + pj_status_t status; + + PJ_ASSERT_RETURN(regc && p_tdata, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + + if (regc->timer.id != 0) { + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + } + + status = create_request(regc, &tdata); + if (status != PJ_SUCCESS) { + pj_lock_release(regc->lock); + return status; + } + + msg = tdata->msg; + + /* Add Contact headers. */ + hdr = (pjsip_hdr*)regc->contact_hdr_list.next; + while ((void*)hdr != (void*)®c->contact_hdr_list) { + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_shallow_clone(tdata->pool, hdr)); + hdr = hdr->next; + } + + /* Also add bindings which are to be removed */ + while (!pj_list_empty(®c->removed_contact_hdr_list)) { + hdr = (pjsip_hdr*)regc->removed_contact_hdr_list.next; + pjsip_msg_add_hdr(msg, (pjsip_hdr*) + pjsip_hdr_clone(tdata->pool, hdr)); + pj_list_erase(hdr); + } + + /* Add Expires:0 header */ + hdr = (pjsip_hdr*) pjsip_expires_hdr_create(tdata->pool, 0); + pjsip_msg_add_hdr(msg, hdr); + + pj_lock_release(regc->lock); + + *p_tdata = tdata; + return PJ_SUCCESS; +} + +PJ_DEF(pj_status_t) pjsip_regc_unregister_all(pjsip_regc *regc, + pjsip_tx_data **p_tdata) +{ + pjsip_tx_data *tdata; + pjsip_contact_hdr *hcontact; + pjsip_hdr *hdr; + pjsip_msg *msg; + pj_status_t status; + + PJ_ASSERT_RETURN(regc && p_tdata, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + + if (regc->timer.id != 0) { + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + } + + status = create_request(regc, &tdata); + if (status != PJ_SUCCESS) { + pj_lock_release(regc->lock); + return status; + } + + msg = tdata->msg; + + /* Clear removed_contact_hdr_list */ + pj_list_init(®c->removed_contact_hdr_list); + + /* Add Contact:* header */ + hcontact = pjsip_contact_hdr_create(tdata->pool); + hcontact->star = 1; + pjsip_msg_add_hdr(msg, (pjsip_hdr*)hcontact); + + /* Add Expires:0 header */ + hdr = (pjsip_hdr*) pjsip_expires_hdr_create(tdata->pool, 0); + pjsip_msg_add_hdr(msg, hdr); + + pj_lock_release(regc->lock); + + *p_tdata = tdata; + return PJ_SUCCESS; +} + + +PJ_DEF(pj_status_t) pjsip_regc_update_contact( pjsip_regc *regc, + int contact_cnt, + const pj_str_t contact[] ) +{ + pj_status_t status; + + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + status = set_contact( regc, contact_cnt, contact ); + pj_lock_release(regc->lock); + + return status; +} + + +PJ_DEF(pj_status_t) pjsip_regc_update_expires( pjsip_regc *regc, + pj_uint32_t expires ) +{ + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + + pj_lock_acquire(regc->lock); + set_expires( regc, expires ); + pj_lock_release(regc->lock); + + return PJ_SUCCESS; +} + + +static void call_callback(pjsip_regc *regc, pj_status_t status, int st_code, + const pj_str_t *reason, + pjsip_rx_data *rdata, pj_int32_t expiration, + int contact_cnt, pjsip_contact_hdr *contact[]) +{ + struct pjsip_regc_cbparam cbparam; + + + if (!regc->cb) + return; + + cbparam.regc = regc; + cbparam.token = regc->token; + cbparam.status = status; + cbparam.code = st_code; + cbparam.reason = *reason; + cbparam.rdata = rdata; + cbparam.contact_cnt = contact_cnt; + cbparam.expiration = expiration; + if (contact_cnt) { + pj_memcpy( cbparam.contact, contact, + contact_cnt*sizeof(pjsip_contact_hdr*)); + } + + (*regc->cb)(&cbparam); +} + +static void regc_refresh_timer_cb( pj_timer_heap_t *timer_heap, + struct pj_timer_entry *entry) +{ + pjsip_regc *regc = (pjsip_regc*) entry->user_data; + pjsip_tx_data *tdata; + pj_status_t status; + + PJ_UNUSED_ARG(timer_heap); + + /* Temporarily increase busy flag to prevent regc from being deleted + * in pjsip_regc_send() or in the callback + */ + pj_atomic_inc(regc->busy_ctr); + + entry->id = 0; + status = pjsip_regc_register(regc, 1, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_regc_send(regc, tdata); + } + + if (status != PJ_SUCCESS && regc->cb) { + char errmsg[PJ_ERR_MSG_SIZE]; + pj_str_t reason = pj_strerror(status, errmsg, sizeof(errmsg)); + call_callback(regc, status, 400, &reason, NULL, -1, 0, NULL); + } + + /* Delete the record if user destroy regc during the callback. */ + if (pj_atomic_dec_and_get(regc->busy_ctr)==0 && regc->_delete_flag) { + pjsip_regc_destroy(regc); + } +} + +static void schedule_registration ( pjsip_regc *regc, pj_int32_t expiration ) +{ + if (regc->auto_reg && expiration > 0) { + pj_time_val delay = { 0, 0}; + + delay.sec = expiration - regc->delay_before_refresh; + if (regc->expires != PJSIP_REGC_EXPIRATION_NOT_SPECIFIED && + delay.sec > (pj_int32_t)regc->expires) + { + delay.sec = regc->expires; + } + if (delay.sec < DELAY_BEFORE_REFRESH) + delay.sec = DELAY_BEFORE_REFRESH; + regc->timer.cb = ®c_refresh_timer_cb; + regc->timer.id = REFRESH_TIMER; + regc->timer.user_data = regc; + pjsip_endpt_schedule_timer( regc->endpt, ®c->timer, &delay); + pj_gettimeofday(®c->last_reg); + regc->next_reg = regc->last_reg; + regc->next_reg.sec += delay.sec; + } +} + +PJ_DEF(pj_status_t) pjsip_regc_set_via_sent_by( pjsip_regc *regc, + pjsip_host_port *via_addr, + pjsip_transport *via_tp) +{ + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + + if (!via_addr) + pj_bzero(®c->via_addr, sizeof(regc->via_addr)); + else + regc->via_addr = *via_addr; + regc->via_tp = via_tp; + + return PJ_SUCCESS; +} + +PJ_DEF(pj_status_t) +pjsip_regc_set_delay_before_refresh( pjsip_regc *regc, + pj_uint32_t delay ) +{ + PJ_ASSERT_RETURN(regc, PJ_EINVAL); + + if (delay > regc->expires) + return PJ_ETOOBIG; + + if (regc->delay_before_refresh != delay) + { + regc->delay_before_refresh = delay; + + if (regc->timer.id != 0) { + /* Cancel registration timer */ + pjsip_endpt_cancel_timer(regc->endpt, ®c->timer); + regc->timer.id = 0; + + /* Schedule next registration */ + schedule_registration(regc, regc->expires); + } + } + + return PJ_SUCCESS; +} + + +static pj_int32_t calculate_response_expiration(const pjsip_regc *regc, + const pjsip_rx_data *rdata, + unsigned *contact_cnt, + unsigned max_contact, + pjsip_contact_hdr *contacts[]) +{ + pj_int32_t expiration = NOEXP; + const pjsip_msg *msg = rdata->msg_info.msg; + const pjsip_hdr *hdr; + + /* Enumerate all Contact headers in the response */ + *contact_cnt = 0; + for (hdr=msg->hdr.next; hdr!=&msg->hdr; hdr=hdr->next) { + if (hdr->type == PJSIP_H_CONTACT && + *contact_cnt < max_contact) + { + contacts[*contact_cnt] = (pjsip_contact_hdr*)hdr; + ++(*contact_cnt); + } + } + + if (regc->current_op == REGC_REGISTERING) { + pj_bool_t has_our_contact = PJ_FALSE; + const pjsip_expires_hdr *expires; + + /* Get Expires header */ + expires = (const pjsip_expires_hdr*) + pjsip_msg_find_hdr(msg, PJSIP_H_EXPIRES, NULL); + + /* Try to find the Contact URIs that we register, in the response + * to get the expires value. We'll try both with comparing the URI + * and comparing the extension param only. + */ + if (pjsip_cfg()->regc.check_contact || regc->add_xuid_param) { + unsigned i; + for (i=0; i<*contact_cnt; ++i) { + const pjsip_contact_hdr *our_hdr; + + our_hdr = (const pjsip_contact_hdr*) + regc->contact_hdr_list.next; + + /* Match with our Contact header(s) */ + while ((void*)our_hdr != (void*)®c->contact_hdr_list) { + + const pjsip_uri *uri1, *uri2; + pj_bool_t matched = PJ_FALSE; + + /* Exclude the display name when comparing the URI + * since server may not return it. + */ + uri1 = (const pjsip_uri*) + pjsip_uri_get_uri(contacts[i]->uri); + uri2 = (const pjsip_uri*) + pjsip_uri_get_uri(our_hdr->uri); + + /* First try with exact matching, according to RFC 3261 + * Section 19.1.4 URI Comparison + */ + if (pjsip_cfg()->regc.check_contact) { + matched = pjsip_uri_cmp(PJSIP_URI_IN_CONTACT_HDR, + uri1, uri2)==0; + } + + /* If no match is found, try with matching the extension + * parameter only if extension parameter was added. + */ + if (!matched && regc->add_xuid_param && + (PJSIP_URI_SCHEME_IS_SIP(uri1) || + PJSIP_URI_SCHEME_IS_SIPS(uri1)) && + (PJSIP_URI_SCHEME_IS_SIP(uri2) || + PJSIP_URI_SCHEME_IS_SIPS(uri2))) + { + const pjsip_sip_uri *sip_uri1, *sip_uri2; + const pjsip_param *p1, *p2; + + sip_uri1 = (const pjsip_sip_uri*)uri1; + sip_uri2 = (const pjsip_sip_uri*)uri2; + + p1 = pjsip_param_cfind(&sip_uri1->other_param, + &XUID_PARAM_NAME); + p2 = pjsip_param_cfind(&sip_uri2->other_param, + &XUID_PARAM_NAME); + matched = p1 && p2 && + pj_strcmp(&p1->value, &p2->value)==0; + + } + + if (matched) { + has_our_contact = PJ_TRUE; + + if (contacts[i]->expires >= 0 && + contacts[i]->expires < expiration) + { + /* Get the lowest expiration time. */ + expiration = contacts[i]->expires; + } + + break; + } + + our_hdr = our_hdr->next; + + } /* while ((void.. */ + + } /* for (i=.. */ + + /* If matching Contact header(s) are found but the + * header doesn't contain expires parameter, get the + * expiration value from the Expires header. And + * if Expires header is not present, get the expiration + * value from the request. + */ + if (has_our_contact && expiration == NOEXP) { + if (expires) { + expiration = expires->ivalue; + } else if (regc->expires_hdr) { + expiration = regc->expires_hdr->ivalue; + } else { + /* We didn't request explicit expiration value, + * and server doesn't specify it either. This + * shouldn't happen unless we have a broken + * registrar. + */ + expiration = 3600; + } + } + + } + + /* If we still couldn't get matching Contact header(s), it means + * there must be something wrong with the registrar (e.g. it may + * have modified the URI's in the response, which is prohibited). + */ + if (expiration==NOEXP) { + /* If the number of Contact headers in the response matches + * ours, they're all probably ours. Get the expiration + * from there if this is the case, or from Expires header + * if we don't have exact Contact header count, or + * from the request as the last resort. + */ + unsigned our_contact_cnt; + + our_contact_cnt = pj_list_size(®c->contact_hdr_list); + + if (*contact_cnt == our_contact_cnt && *contact_cnt && + contacts[0]->expires >= 0) + { + expiration = contacts[0]->expires; + } else if (expires) + expiration = expires->ivalue; + else if (regc->expires_hdr) + expiration = regc->expires_hdr->ivalue; + else + expiration = 3600; + } + + } else { + /* Just assume that the unregistration has been successful. */ + expiration = 0; + } + + /* Must have expiration value by now */ + pj_assert(expiration != NOEXP); + + return expiration; +} + +static void regc_tsx_callback(void *token, pjsip_event *event) +{ + pj_status_t status; + pjsip_regc *regc = (pjsip_regc*) token; + pjsip_transaction *tsx = event->body.tsx_state.tsx; + pj_bool_t handled = PJ_TRUE; + + pj_atomic_inc(regc->busy_ctr); + pj_lock_acquire(regc->lock); + + /* Decrement pending transaction counter. */ + pj_assert(regc->has_tsx); + regc->has_tsx = PJ_FALSE; + + /* Add reference to the transport */ + if (tsx->transport != regc->last_transport) { + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + + if (tsx->transport) { + regc->last_transport = tsx->transport; + pjsip_transport_add_ref(regc->last_transport); + } + } + + /* Handle 401/407 challenge (even when _delete_flag is set) */ + if (tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED || + tsx->status_code == PJSIP_SC_UNAUTHORIZED) + { + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_tx_data *tdata; + + /* reset current op */ + regc->current_op = REGC_IDLE; + + status = pjsip_auth_clt_reinit_req( ®c->auth_sess, + rdata, + tsx->last_tx, + &tdata); + + if (status == PJ_SUCCESS) { + status = pjsip_regc_send(regc, tdata); + } + + if (status != PJ_SUCCESS) { + + /* Only call callback if application is still interested + * in it. + */ + if (regc->_delete_flag == 0) { + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, status, tsx->status_code, + &rdata->msg_info.msg->line.status.reason, + rdata, -1, 0, NULL); + pj_lock_acquire(regc->lock); + } + } + + } else if (regc->_delete_flag) { + + /* User has called pjsip_regc_destroy(), so don't call callback. + * This regc will be destroyed later in this function. + */ + + /* Just reset current op */ + regc->current_op = REGC_IDLE; + + } else if (tsx->status_code == PJSIP_SC_INTERVAL_TOO_BRIEF && + regc->current_op == REGC_REGISTERING) + { + /* Handle 423 response automatically: + * - set requested expiration to Min-Expires header, ONLY IF + * the original request is a registration (as opposed to + * unregistration) and the requested expiration was indeed + * lower than Min-Expires) + * - resend the request + */ + pjsip_rx_data *rdata = event->body.tsx_state.src.rdata; + pjsip_min_expires_hdr *me_hdr; + pjsip_tx_data *tdata; + pj_int32_t min_exp; + + /* reset current op */ + regc->current_op = REGC_IDLE; + + /* Update requested expiration */ + me_hdr = (pjsip_min_expires_hdr*) + pjsip_msg_find_hdr(rdata->msg_info.msg, + PJSIP_H_MIN_EXPIRES, NULL); + if (me_hdr) { + min_exp = me_hdr->ivalue; + } else { + /* Broken server, Min-Expires doesn't exist. + * Just guestimate then, BUT ONLY if if this is the + * first time we received such response. + */ + enum { + /* Note: changing this value would require changing couple of + * Python test scripts. + */ + UNSPECIFIED_MIN_EXPIRES = 3601 + }; + if (!regc->expires_hdr || + regc->expires_hdr->ivalue != UNSPECIFIED_MIN_EXPIRES) + { + min_exp = UNSPECIFIED_MIN_EXPIRES; + } else { + handled = PJ_FALSE; + PJ_LOG(4,(THIS_FILE, "Registration failed: 423 response " + "without Min-Expires header is invalid")); + goto handle_err; + } + } + + if (regc->expires_hdr && regc->expires_hdr->ivalue >= min_exp) { + /* But we already send with greater expiration time, why does + * the server send us with 423? Oh well, just fail the request. + */ + handled = PJ_FALSE; + PJ_LOG(4,(THIS_FILE, "Registration failed: invalid " + "Min-Expires header value in response")); + goto handle_err; + } + + set_expires(regc, min_exp); + + status = pjsip_regc_register(regc, regc->auto_reg, &tdata); + if (status == PJ_SUCCESS) { + status = pjsip_regc_send(regc, tdata); + } + + if (status != PJ_SUCCESS) { + /* Only call callback if application is still interested + * in it. + */ + if (!regc->_delete_flag) { + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, status, tsx->status_code, + &rdata->msg_info.msg->line.status.reason, + rdata, -1, 0, NULL); + pj_lock_acquire(regc->lock); + } + } + + } else { + handled = PJ_FALSE; + } + +handle_err: + if (!handled) { + pjsip_rx_data *rdata; + pj_int32_t expiration = NOEXP; + unsigned contact_cnt = 0; + pjsip_contact_hdr *contact[PJSIP_REGC_MAX_CONTACT]; + + if (tsx->status_code/100 == 2) { + + rdata = event->body.tsx_state.src.rdata; + + /* Calculate expiration */ + expiration = calculate_response_expiration(regc, rdata, + &contact_cnt, + PJSIP_REGC_MAX_CONTACT, + contact); + + /* Schedule next registration */ + schedule_registration(regc, expiration); + + } else { + rdata = (event->body.tsx_state.type==PJSIP_EVENT_RX_MSG) ? + event->body.tsx_state.src.rdata : NULL; + } + + /* Update registration */ + if (expiration==NOEXP) expiration=-1; + regc->expires = expiration; + + /* Mark operation as complete */ + regc->current_op = REGC_IDLE; + + /* Call callback. */ + /* Should be safe to release the lock temporarily. + * We do this to avoid deadlock. + */ + pj_lock_release(regc->lock); + call_callback(regc, PJ_SUCCESS, tsx->status_code, + (rdata ? &rdata->msg_info.msg->line.status.reason + : &tsx->status_text), + rdata, expiration, + contact_cnt, contact); + pj_lock_acquire(regc->lock); + } + + pj_lock_release(regc->lock); + + /* Delete the record if user destroy regc during the callback. */ + if (pj_atomic_dec_and_get(regc->busy_ctr)==0 && regc->_delete_flag) { + pjsip_regc_destroy(regc); + } +} + +PJ_DEF(pj_status_t) pjsip_regc_send(pjsip_regc *regc, pjsip_tx_data *tdata) +{ + pj_status_t status; + pjsip_cseq_hdr *cseq_hdr; + pjsip_expires_hdr *expires_hdr; + pj_uint32_t cseq; + + pj_atomic_inc(regc->busy_ctr); + pj_lock_acquire(regc->lock); + + /* Make sure we don't have pending transaction. */ + if (regc->has_tsx) { + PJ_LOG(4,(THIS_FILE, "Unable to send request, regc has another " + "transaction pending")); + pjsip_tx_data_dec_ref( tdata ); + pj_lock_release(regc->lock); + pj_atomic_dec(regc->busy_ctr); + return PJSIP_EBUSY; + } + + pj_assert(regc->current_op == REGC_IDLE); + + /* Invalidate message buffer. */ + pjsip_tx_data_invalidate_msg(tdata); + + /* Increment CSeq */ + cseq = ++regc->cseq_hdr->cseq; + cseq_hdr = (pjsip_cseq_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL); + cseq_hdr->cseq = cseq; + + /* Find Expires header */ + expires_hdr = (pjsip_expires_hdr*) + pjsip_msg_find_hdr(tdata->msg, PJSIP_H_EXPIRES, NULL); + + /* Bind to transport selector */ + pjsip_tx_data_set_transport(tdata, ®c->tp_sel); + + regc->has_tsx = PJ_TRUE; + + /* Set current operation based on the value of Expires header */ + if (expires_hdr && expires_hdr->ivalue==0) + regc->current_op = REGC_UNREGISTERING; + else + regc->current_op = REGC_REGISTERING; + + /* Prevent deletion of tdata, e.g: when something wrong in sending, + * we need tdata to retrieve the transport. + */ + pjsip_tx_data_add_ref(tdata); + + /* If via_addr is set, use this address for the Via header. */ + if (regc->via_addr.host.slen > 0) { + tdata->via_addr = regc->via_addr; + tdata->via_tp = regc->via_tp; + } + + /* Need to unlock the regc temporarily while sending the message to + * prevent deadlock (https://trac.pjsip.org/repos/ticket/1247). + * It should be safe to do this since the regc's refcount has been + * incremented. + */ + pj_lock_release(regc->lock); + + /* Now send the message */ + status = pjsip_endpt_send_request(regc->endpt, tdata, REGC_TSX_TIMEOUT, + regc, ®c_tsx_callback); + if (status!=PJ_SUCCESS) { + PJ_LOG(4,(THIS_FILE, "Error sending request, status=%d", status)); + } + + /* Reacquire the lock */ + pj_lock_acquire(regc->lock); + + /* Get last transport used and add reference to it */ + if (tdata->tp_info.transport != regc->last_transport && + status==PJ_SUCCESS) + { + if (regc->last_transport) { + pjsip_transport_dec_ref(regc->last_transport); + regc->last_transport = NULL; + } + + if (tdata->tp_info.transport) { + regc->last_transport = tdata->tp_info.transport; + pjsip_transport_add_ref(regc->last_transport); + } + } + + /* Release tdata */ + pjsip_tx_data_dec_ref(tdata); + + pj_lock_release(regc->lock); + + /* Delete the record if user destroy regc during the callback. */ + if (pj_atomic_dec_and_get(regc->busy_ctr)==0 && regc->_delete_flag) { + pjsip_regc_destroy(regc); + } + + return status; +} + + diff --git a/pjsip/src/pjsip-ua/sip_replaces.c b/pjsip/src/pjsip-ua/sip_replaces.c new file mode 100644 index 0000000..b961cf9 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_replaces.c @@ -0,0 +1,384 @@ +/* $Id: sip_replaces.c 3999 2012-03-30 07:10:13Z bennylp $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_replaces.h> +#include <pjsip-ua/sip_inv.h> +#include <pjsip/print_util.h> +#include <pjsip/sip_endpoint.h> +#include <pjsip/sip_errno.h> +#include <pjsip/sip_parser.h> +#include <pjsip/sip_transport.h> +#include <pjsip/sip_ua_layer.h> +#include <pjsip/sip_util.h> +#include <pj/assert.h> +#include <pj/log.h> +#include <pj/pool.h> +#include <pj/string.h> + +#define THIS_FILE "sip_replaces.c" + + +/* + * Replaces header vptr. + */ +static int replaces_hdr_print( pjsip_replaces_hdr *hdr, + char *buf, pj_size_t size); +static pjsip_replaces_hdr* replaces_hdr_clone( pj_pool_t *pool, + const pjsip_replaces_hdr *hdr); +static pjsip_replaces_hdr* replaces_hdr_shallow_clone( pj_pool_t *pool, + const pjsip_replaces_hdr*); + +static pjsip_hdr_vptr replaces_hdr_vptr = +{ + (pjsip_hdr_clone_fptr) &replaces_hdr_clone, + (pjsip_hdr_clone_fptr) &replaces_hdr_shallow_clone, + (pjsip_hdr_print_fptr) &replaces_hdr_print, +}; + +/* Globals */ +static pjsip_endpoint *the_endpt; +static pj_bool_t is_initialized; + +PJ_DEF(pjsip_replaces_hdr*) pjsip_replaces_hdr_create(pj_pool_t *pool) +{ + pjsip_replaces_hdr *hdr = PJ_POOL_ZALLOC_T(pool, pjsip_replaces_hdr); + hdr->type = PJSIP_H_OTHER; + hdr->name.ptr = "Replaces"; + hdr->name.slen = 8; + hdr->vptr = &replaces_hdr_vptr; + pj_list_init(hdr); + pj_list_init(&hdr->other_param); + return hdr; +} + +static int replaces_hdr_print( pjsip_replaces_hdr *hdr, + char *buf, pj_size_t size) +{ + char *p = buf; + char *endbuf = buf+size; + int printed; + const pjsip_parser_const_t *pc = pjsip_parser_const(); + + copy_advance(p, hdr->name); + *p++ = ':'; + *p++ = ' '; + + copy_advance(p, hdr->call_id); + copy_advance_pair(p, ";to-tag=", 8, hdr->to_tag); + copy_advance_pair(p, ";from-tag=", 10, hdr->from_tag); + + if (hdr->early_only) { + const pj_str_t str_early_only = { ";early-only", 11 }; + copy_advance(p, str_early_only); + } + + printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); + if (printed < 0) + return printed; + + p += printed; + return p - buf; +} + +static pjsip_replaces_hdr* replaces_hdr_clone( pj_pool_t *pool, + const pjsip_replaces_hdr *rhs) +{ + pjsip_replaces_hdr *hdr = pjsip_replaces_hdr_create(pool); + pj_strdup(pool, &hdr->call_id, &rhs->call_id); + pj_strdup(pool, &hdr->to_tag, &rhs->to_tag); + pj_strdup(pool, &hdr->from_tag, &rhs->from_tag); + hdr->early_only = rhs->early_only; + pjsip_param_clone(pool, &hdr->other_param, &rhs->other_param); + return hdr; +} + +static pjsip_replaces_hdr* +replaces_hdr_shallow_clone( pj_pool_t *pool, + const pjsip_replaces_hdr *rhs ) +{ + pjsip_replaces_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_replaces_hdr); + pj_memcpy(hdr, rhs, sizeof(*hdr)); + pjsip_param_shallow_clone(pool, &hdr->other_param, &rhs->other_param); + return hdr; +} + + +/* + * Parse Replaces header. + */ +static pjsip_hdr *parse_hdr_replaces(pjsip_parse_ctx *ctx) +{ + pjsip_replaces_hdr *hdr = pjsip_replaces_hdr_create(ctx->pool); + const pj_str_t to_tag = { "to-tag", 6 }; + const pj_str_t from_tag = { "from-tag", 8 }; + const pj_str_t early_only_tag = { "early-only", 10 }; + + /*pj_scan_get(ctx->scanner, &pjsip_TOKEN_SPEC, &hdr->call_id);*/ + /* Get Call-ID (until ';' is found). using pjsip_TOKEN_SPEC doesn't work + * because it stops parsing when '@' character is found. + */ + pj_scan_get_until_ch(ctx->scanner, ';', &hdr->call_id); + + while (*ctx->scanner->curptr == ';') { + pj_str_t pname, pvalue; + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + if (pj_stricmp(&pname, &to_tag)==0) { + hdr->to_tag = pvalue; + } else if (pj_stricmp(&pname, &from_tag)==0) { + hdr->from_tag = pvalue; + } else if (pj_stricmp(&pname, &early_only_tag)==0) { + hdr->early_only = PJ_TRUE; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } + } + pjsip_parse_end_hdr_imp( ctx->scanner ); + return (pjsip_hdr*)hdr; +} + + +/* Deinitialize Replaces */ +static void pjsip_replaces_deinit_module(pjsip_endpoint *endpt) +{ + PJ_TODO(provide_initialized_flag_for_each_endpoint); + PJ_UNUSED_ARG(endpt); + is_initialized = PJ_FALSE; +} + +/* + * Initialize Replaces support in PJSIP. + */ +PJ_DEF(pj_status_t) pjsip_replaces_init_module(pjsip_endpoint *endpt) +{ + pj_status_t status; + const pj_str_t STR_REPLACES = { "replaces", 8 }; + + the_endpt = endpt; + + if (is_initialized) + return PJ_SUCCESS; + + /* Register Replaces header parser */ + status = pjsip_register_hdr_parser( "Replaces", NULL, + &parse_hdr_replaces); + if (status != PJ_SUCCESS) + return status; + + /* Register "replaces" capability */ + status = pjsip_endpt_add_capability(endpt, NULL, PJSIP_H_SUPPORTED, NULL, + 1, &STR_REPLACES); + + /* Register deinit module to be executed when PJLIB shutdown */ + if (pjsip_endpt_atexit(endpt, &pjsip_replaces_deinit_module) != PJ_SUCCESS) + { + /* Failure to register this function may cause this module won't + * work properly when the stack is restarted (without quitting + * application). + */ + pj_assert(!"Failed to register Replaces deinit."); + PJ_LOG(1, (THIS_FILE, "Failed to register Replaces deinit.")); + } + + is_initialized = PJ_TRUE; + return PJ_SUCCESS; +} + + +/* + * Verify that incoming request with Replaces header can be processed. + */ +PJ_DEF(pj_status_t) pjsip_replaces_verify_request( pjsip_rx_data *rdata, + pjsip_dialog **p_dlg, + pj_bool_t lock_dlg, + pjsip_tx_data **p_tdata) +{ + const pj_str_t STR_REPLACES = { "Replaces", 8 }; + pjsip_replaces_hdr *rep_hdr; + int code = 200; + const char *warn_text = NULL; + pjsip_hdr res_hdr_list; + pjsip_dialog *dlg = NULL; + pjsip_inv_session *inv; + pj_status_t status = PJ_SUCCESS; + + PJ_ASSERT_RETURN(rdata && p_dlg, PJ_EINVAL); + + /* Check that pjsip_replaces_init_module() has been called. */ + PJ_ASSERT_RETURN(the_endpt != NULL, PJ_EINVALIDOP); + + + /* Init output arguments */ + *p_dlg = NULL; + if (p_tdata) *p_tdata = NULL; + + pj_list_init(&res_hdr_list); + + /* Find Replaces header */ + rep_hdr = (pjsip_replaces_hdr*) + pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_REPLACES, + NULL); + if (!rep_hdr) { + /* No Replaces header. No further processing is necessary. */ + return PJ_SUCCESS; + } + + + /* Check that there's no other Replaces header and return 400 Bad Request + * if not. + */ + if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &STR_REPLACES, + rep_hdr->next)) { + code = PJSIP_SC_BAD_REQUEST; + warn_text = "Found multiple Replaces headers"; + goto on_return; + } + + /* Find the dialog identified by Replaces header (and always lock the + * dialog no matter what application wants). + */ + dlg = pjsip_ua_find_dialog(&rep_hdr->call_id, &rep_hdr->to_tag, + &rep_hdr->from_tag, PJ_TRUE); + + /* Respond with 481 "Call/Transaction Does Not Exist" response if + * no dialog is found. + */ + if (dlg == NULL) { + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "No dialog found for Replaces request"; + goto on_return; + } + + /* Get the invite session within the dialog */ + inv = pjsip_dlg_get_inv_session(dlg); + + /* Return 481 if no invite session is present. */ + if (inv == NULL) { + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "No INVITE session found for Replaces request"; + goto on_return; + } + + /* Return 603 Declined response if invite session has already + * terminated + */ + if (inv->state >= PJSIP_INV_STATE_DISCONNECTED) { + code = PJSIP_SC_DECLINE; + warn_text = "INVITE session already terminated"; + goto on_return; + } + + /* If "early-only" flag is present, check that the invite session + * has not been confirmed yet. If the session has been confirmed, + * return 486 "Busy Here" response. + */ + if (rep_hdr->early_only && inv->state >= PJSIP_INV_STATE_CONNECTING) { + code = PJSIP_SC_BUSY_HERE; + warn_text = "INVITE session already established"; + goto on_return; + } + + /* If the Replaces header field matches an early dialog that was not + * initiated by this UA, it returns a 481 (Call/Transaction Does Not + * Exist) response to the new INVITE. + */ + if (inv->state <= PJSIP_INV_STATE_EARLY && inv->role != PJSIP_ROLE_UAC) { + code = PJSIP_SC_CALL_TSX_DOES_NOT_EXIST; + warn_text = "Found early INVITE session but not initiated by this UA"; + goto on_return; + } + + + /* + * Looks like everything is okay!! + */ + *p_dlg = dlg; + status = PJ_SUCCESS; + code = 200; + +on_return: + + /* Create response if necessary */ + if (code != 200) { + /* If we have dialog we must unlock it */ + if (dlg) + pjsip_dlg_dec_lock(dlg); + + /* Create response */ + if (p_tdata) { + pjsip_tx_data *tdata; + const pjsip_hdr *h; + + status = pjsip_endpt_create_response(the_endpt, rdata, code, + NULL, &tdata); + + if (status != PJ_SUCCESS) + return status; + + /* Add response headers. */ + h = res_hdr_list.next; + while (h != &res_hdr_list) { + pjsip_hdr *cloned; + + cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h); + PJ_ASSERT_RETURN(cloned, PJ_ENOMEM); + + pjsip_msg_add_hdr(tdata->msg, cloned); + + h = h->next; + } + + /* Add warn text, if any */ + if (warn_text) { + pjsip_warning_hdr *warn_hdr; + pj_str_t warn_value = pj_str((char*)warn_text); + + warn_hdr=pjsip_warning_hdr_create(tdata->pool, 399, + pjsip_endpt_name(the_endpt), + &warn_value); + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)warn_hdr); + } + + *p_tdata = tdata; + } + + /* Can not return PJ_SUCCESS when response message is produced. + * Ref: PROTOS test ~#2490 + */ + if (status == PJ_SUCCESS) + status = PJSIP_ERRNO_FROM_SIP_STATUS(code); + + } else { + /* If application doesn't want to lock the dialog, unlock it */ + if (!lock_dlg) + pjsip_dlg_dec_lock(dlg); + } + + return status; +} + + + diff --git a/pjsip/src/pjsip-ua/sip_timer.c b/pjsip/src/pjsip-ua/sip_timer.c new file mode 100644 index 0000000..2c70791 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_timer.c @@ -0,0 +1,1062 @@ +/* $Id: sip_timer.c 3999 2012-03-30 07:10:13Z bennylp $ */ +/* + * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_timer.h> +#include <pjsip/print_util.h> +#include <pjsip/sip_endpoint.h> +#include <pj/log.h> +#include <pj/math.h> +#include <pj/os.h> +#include <pj/pool.h> + +#define THIS_FILE "sip_timer.c" + + +/* Constant of Session Timers */ +#define ABS_MIN_SE 90 /* Absolute Min-SE, in seconds */ + + +/* String definitions */ +static const pj_str_t STR_SE = {"Session-Expires", 15}; +static const pj_str_t STR_SHORT_SE = {"x", 1}; +static const pj_str_t STR_MIN_SE = {"Min-SE", 6}; +static const pj_str_t STR_REFRESHER = {"refresher", 9}; +static const pj_str_t STR_UAC = {"uac", 3}; +static const pj_str_t STR_UAS = {"uas", 3}; +static const pj_str_t STR_TIMER = {"timer", 5}; + + +/* Enumeration of refresher */ +enum timer_refresher { + TR_UNKNOWN, + TR_UAC, + TR_UAS +}; + +/* Structure definition of Session Timers */ +struct pjsip_timer +{ + pj_bool_t active; /**< Active/inactive flag */ + pjsip_timer_setting setting; /**< Session Timers setting */ + enum timer_refresher refresher; /**< Session refresher */ + pj_time_val last_refresh; /**< Timestamp of last + refresh */ + pj_timer_entry timer; /**< Timer entry */ + pj_bool_t use_update; /**< Use UPDATE method to + refresh the session */ + pj_bool_t with_sdp; /**< SDP in UPDATE? */ + pjsip_role_e role; /**< Role in last INVITE/ + UPDATE transaction. */ + +}; + +/* External global vars */ +extern pj_bool_t pjsip_use_compact_form; + +/* Local functions & vars */ +static void stop_timer(pjsip_inv_session *inv); +static void start_timer(pjsip_inv_session *inv); +static pj_bool_t is_initialized; +const pjsip_method pjsip_update_method = { PJSIP_OTHER_METHOD, {"UPDATE", 6}}; +/* + * Session-Expires header vptr. + */ +static int se_hdr_print(pjsip_sess_expires_hdr *hdr, + char *buf, pj_size_t size); +static pjsip_sess_expires_hdr* se_hdr_clone(pj_pool_t *pool, + const pjsip_sess_expires_hdr *hdr); +static pjsip_sess_expires_hdr* se_hdr_shallow_clone( + pj_pool_t *pool, + const pjsip_sess_expires_hdr* hdr); + +static pjsip_hdr_vptr se_hdr_vptr = +{ + (pjsip_hdr_clone_fptr) &se_hdr_clone, + (pjsip_hdr_clone_fptr) &se_hdr_shallow_clone, + (pjsip_hdr_print_fptr) &se_hdr_print, +}; + +/* + * Min-SE header vptr. + */ +static int min_se_hdr_print(pjsip_min_se_hdr *hdr, + char *buf, pj_size_t size); +static pjsip_min_se_hdr* min_se_hdr_clone(pj_pool_t *pool, + const pjsip_min_se_hdr *hdr); +static pjsip_min_se_hdr* min_se_hdr_shallow_clone( + pj_pool_t *pool, + const pjsip_min_se_hdr* hdr); + +static pjsip_hdr_vptr min_se_hdr_vptr = +{ + (pjsip_hdr_clone_fptr) &min_se_hdr_clone, + (pjsip_hdr_clone_fptr) &min_se_hdr_shallow_clone, + (pjsip_hdr_print_fptr) &min_se_hdr_print, +}; + +/* + * Session-Expires header vptr. + */ +static int se_hdr_print(pjsip_sess_expires_hdr *hdr, + char *buf, pj_size_t size) +{ + char *p = buf; + char *endbuf = buf+size; + int printed; + const pjsip_parser_const_t *pc = pjsip_parser_const(); + const pj_str_t *hname = pjsip_use_compact_form? &hdr->sname : &hdr->name; + + /* Print header name and value */ + if ((endbuf - p) < (hname->slen + 16)) + return -1; + + copy_advance(p, (*hname)); + *p++ = ':'; + *p++ = ' '; + + printed = pj_utoa(hdr->sess_expires, p); + p += printed; + + /* Print 'refresher' param */ + if (hdr->refresher.slen) + { + if ((endbuf - p) < (STR_REFRESHER.slen + 2 + hdr->refresher.slen)) + return -1; + + *p++ = ';'; + copy_advance(p, STR_REFRESHER); + *p++ = '='; + copy_advance(p, hdr->refresher); + } + + /* Print generic params */ + printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); + if (printed < 0) + return printed; + + p += printed; + return p - buf; +} + +static pjsip_sess_expires_hdr* se_hdr_clone(pj_pool_t *pool, + const pjsip_sess_expires_hdr *hsrc) +{ + pjsip_sess_expires_hdr *hdr = pjsip_sess_expires_hdr_create(pool); + hdr->sess_expires = hsrc->sess_expires; + pj_strdup(pool, &hdr->refresher, &hsrc->refresher); + pjsip_param_clone(pool, &hdr->other_param, &hsrc->other_param); + return hdr; +} + +static pjsip_sess_expires_hdr* se_hdr_shallow_clone( + pj_pool_t *pool, + const pjsip_sess_expires_hdr* hsrc) +{ + pjsip_sess_expires_hdr *hdr = PJ_POOL_ALLOC_T(pool,pjsip_sess_expires_hdr); + pj_memcpy(hdr, hsrc, sizeof(*hdr)); + pjsip_param_shallow_clone(pool, &hdr->other_param, &hsrc->other_param); + return hdr; +} + +/* + * Min-SE header vptr. + */ +static int min_se_hdr_print(pjsip_min_se_hdr *hdr, + char *buf, pj_size_t size) +{ + char *p = buf; + char *endbuf = buf+size; + int printed; + const pjsip_parser_const_t *pc = pjsip_parser_const(); + + /* Print header name and value */ + if ((endbuf - p) < (hdr->name.slen + 16)) + return -1; + + copy_advance(p, hdr->name); + *p++ = ':'; + *p++ = ' '; + + printed = pj_utoa(hdr->min_se, p); + p += printed; + + /* Print generic params */ + printed = pjsip_param_print_on(&hdr->other_param, p, endbuf-p, + &pc->pjsip_TOKEN_SPEC, + &pc->pjsip_TOKEN_SPEC, ';'); + if (printed < 0) + return printed; + + p += printed; + return p - buf; +} + +static pjsip_min_se_hdr* min_se_hdr_clone(pj_pool_t *pool, + const pjsip_min_se_hdr *hsrc) +{ + pjsip_min_se_hdr *hdr = pjsip_min_se_hdr_create(pool); + hdr->min_se = hsrc->min_se; + pjsip_param_clone(pool, &hdr->other_param, &hsrc->other_param); + return hdr; +} + +static pjsip_min_se_hdr* min_se_hdr_shallow_clone( + pj_pool_t *pool, + const pjsip_min_se_hdr* hsrc) +{ + pjsip_min_se_hdr *hdr = PJ_POOL_ALLOC_T(pool, pjsip_min_se_hdr); + pj_memcpy(hdr, hsrc, sizeof(*hdr)); + pjsip_param_shallow_clone(pool, &hdr->other_param, &hsrc->other_param); + return hdr; +} + + +/* + * Parse Session-Expires header. + */ +static pjsip_hdr *parse_hdr_se(pjsip_parse_ctx *ctx) +{ + pjsip_sess_expires_hdr *hdr = pjsip_sess_expires_hdr_create(ctx->pool); + const pjsip_parser_const_t *pc = pjsip_parser_const(); + pj_str_t token; + + pj_scan_get(ctx->scanner, &pc->pjsip_DIGIT_SPEC, &token); + hdr->sess_expires = pj_strtoul(&token); + + while (*ctx->scanner->curptr == ';') { + pj_str_t pname, pvalue; + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + if (pj_stricmp(&pname, &STR_REFRESHER)==0) { + hdr->refresher = pvalue; + } else { + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } + } + pjsip_parse_end_hdr_imp( ctx->scanner ); + return (pjsip_hdr*)hdr; +} + +/* + * Parse Min-SE header. + */ +static pjsip_hdr *parse_hdr_min_se(pjsip_parse_ctx *ctx) +{ + pjsip_min_se_hdr *hdr = pjsip_min_se_hdr_create(ctx->pool); + const pjsip_parser_const_t *pc = pjsip_parser_const(); + pj_str_t token; + + pj_scan_get(ctx->scanner, &pc->pjsip_DIGIT_SPEC, &token); + hdr->min_se = pj_strtoul(&token); + + while (*ctx->scanner->curptr == ';') { + pj_str_t pname, pvalue; + pjsip_param *param = PJ_POOL_ALLOC_T(ctx->pool, pjsip_param); + + pj_scan_get_char(ctx->scanner); + pjsip_parse_param_imp(ctx->scanner, ctx->pool, &pname, &pvalue, 0); + + param->name = pname; + param->value = pvalue; + pj_list_push_back(&hdr->other_param, param); + } + pjsip_parse_end_hdr_imp( ctx->scanner ); + return (pjsip_hdr*)hdr; +} + + +/* Add "Session-Expires" and "Min-SE" headers. Note that "Min-SE" header + * can only be added to INVITE/UPDATE request and 422 response. + */ +static void add_timer_headers(pjsip_inv_session *inv, pjsip_tx_data *tdata, + pj_bool_t add_se, pj_bool_t add_min_se) +{ + pjsip_timer *timer = inv->timer; + + /* Add Session-Expires header */ + if (add_se) { + pjsip_sess_expires_hdr *hdr; + + hdr = pjsip_sess_expires_hdr_create(tdata->pool); + hdr->sess_expires = timer->setting.sess_expires; + if (timer->refresher != TR_UNKNOWN) + hdr->refresher = (timer->refresher == TR_UAC? STR_UAC : STR_UAS); + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); + } + + /* Add Min-SE header */ + if (add_min_se) { + pjsip_min_se_hdr *hdr; + + hdr = pjsip_min_se_hdr_create(tdata->pool); + hdr->min_se = timer->setting.min_se; + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hdr); + } +} + +/* Timer callback. When the timer is fired, it can be time to refresh + * the session if UA is the refresher, otherwise it is time to end + * the session. + */ +static void timer_cb(pj_timer_heap_t *timer_heap, struct pj_timer_entry *entry) +{ + pjsip_inv_session *inv = (pjsip_inv_session*) entry->user_data; + pjsip_tx_data *tdata = NULL; + pj_status_t status; + pj_bool_t as_refresher; + + pj_assert(inv); + + inv->timer->timer.id = 0; + + PJ_UNUSED_ARG(timer_heap); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(inv->dlg); + + /* Check our role */ + as_refresher = + (inv->timer->refresher == TR_UAC && inv->timer->role == PJSIP_ROLE_UAC) || + (inv->timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS); + + /* Do action based on role, refresher or refreshee */ + if (as_refresher) { + pj_time_val now; + + /* As refresher, reshedule the refresh request on the following: + * - msut not send re-INVITE if another INVITE or SDP negotiation + * is in progress. + * - must not send UPDATE with SDP if SDP negotiation is in progress + */ + pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg); + if ( (!inv->timer->use_update && ( + inv->invite_tsx != NULL || + neg_state != PJMEDIA_SDP_NEG_STATE_DONE) + ) + || + (inv->timer->use_update && inv->timer->with_sdp && + neg_state != PJMEDIA_SDP_NEG_STATE_DONE + ) + ) + { + pj_time_val delay = {1, 0}; + + inv->timer->timer.id = 1; + pjsip_endpt_schedule_timer(inv->dlg->endpt, &inv->timer->timer, + &delay); + pjsip_dlg_dec_lock(inv->dlg); + return; + } + + /* Refresher, refresh the session */ + if (inv->timer->use_update) { + const pjmedia_sdp_session *offer = NULL; + + if (inv->timer->with_sdp) { + pjmedia_sdp_neg_get_active_local(inv->neg, &offer); + } + status = pjsip_inv_update(inv, NULL, offer, &tdata); + } else { + /* Create re-INVITE without modifying session */ + pjsip_msg_body *body; + const pjmedia_sdp_session *offer = NULL; + + pj_assert(pjmedia_sdp_neg_get_state(inv->neg) == + PJMEDIA_SDP_NEG_STATE_DONE); + + status = pjsip_inv_invite(inv, &tdata); + if (status == PJ_SUCCESS) + status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov, + inv->neg, &offer); + if (status == PJ_SUCCESS) + status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer); + if (status == PJ_SUCCESS) { + status = pjsip_create_sdp_body(tdata->pool, + (pjmedia_sdp_session*)offer, &body); + tdata->msg->body = body; + } + } + + pj_gettimeofday(&now); + PJ_LOG(4, (inv->pool->obj_name, + "Refreshing session after %ds (expiration period=%ds)", + (now.sec-inv->timer->last_refresh.sec), + inv->timer->setting.sess_expires)); + } else { + + pj_time_val now; + + /* Refreshee, terminate the session */ + status = pjsip_inv_end_session(inv, PJSIP_SC_REQUEST_TIMEOUT, + NULL, &tdata); + + pj_gettimeofday(&now); + PJ_LOG(3, (inv->pool->obj_name, + "No session refresh received after %ds " + "(expiration period=%ds), stopping session now!", + (now.sec-inv->timer->last_refresh.sec), + inv->timer->setting.sess_expires)); + } + + /* Unlock dialog. */ + pjsip_dlg_dec_lock(inv->dlg); + + /* Send message, if any */ + if (tdata && status == PJ_SUCCESS) { + status = pjsip_inv_send_msg(inv, tdata); + } + + /* Print error message, if any */ + if (status != PJ_SUCCESS) { + PJ_PERROR(2, (inv->pool->obj_name, status, + "Error in %s session timer", + (as_refresher? "refreshing" : "terminating"))); + } +} + +/* Start Session Timers */ +static void start_timer(pjsip_inv_session *inv) +{ + const pj_str_t UPDATE = { "UPDATE", 6 }; + pjsip_timer *timer = inv->timer; + pj_time_val delay = {0}; + + pj_assert(inv->timer->active == PJ_TRUE); + + stop_timer(inv); + + inv->timer->use_update = + (pjsip_dlg_remote_has_cap(inv->dlg, PJSIP_H_ALLOW, NULL, + &UPDATE) == PJSIP_DIALOG_CAP_SUPPORTED); + if (!inv->timer->use_update) { + /* INVITE always needs SDP */ + inv->timer->with_sdp = PJ_TRUE; + } + + pj_timer_entry_init(&timer->timer, + 1, /* id */ + inv, /* user data */ + timer_cb); /* callback */ + + /* Set delay based on role, refresher or refreshee */ + if ((timer->refresher == TR_UAC && inv->timer->role == PJSIP_ROLE_UAC) || + (timer->refresher == TR_UAS && inv->timer->role == PJSIP_ROLE_UAS)) + { + /* Next refresh, the delay is half of session expire */ + delay.sec = timer->setting.sess_expires / 2; + } else { + /* Send BYE if no refresh received until this timer fired, delay + * is the minimum of 32 seconds and one third of the session interval + * before session expiration. + */ + delay.sec = timer->setting.sess_expires - + timer->setting.sess_expires/3; + delay.sec = PJ_MAX((long)timer->setting.sess_expires-32, delay.sec); + } + + /* Schedule the timer */ + pjsip_endpt_schedule_timer(inv->dlg->endpt, &timer->timer, &delay); + + /* Update last refresh time */ + pj_gettimeofday(&timer->last_refresh); +} + +/* Stop Session Timers */ +static void stop_timer(pjsip_inv_session *inv) +{ + if (inv->timer->timer.id != 0) { + pjsip_endpt_cancel_timer(inv->dlg->endpt, &inv->timer->timer); + inv->timer->timer.id = 0; + } +} + +/* Deinitialize Session Timers */ +static void pjsip_timer_deinit_module(pjsip_endpoint *endpt) +{ + PJ_TODO(provide_initialized_flag_for_each_endpoint); + PJ_UNUSED_ARG(endpt); + is_initialized = PJ_FALSE; +} + +/* + * Initialize Session Timers support in PJSIP. + */ +PJ_DEF(pj_status_t) pjsip_timer_init_module(pjsip_endpoint *endpt) +{ + pj_status_t status; + + PJ_ASSERT_RETURN(endpt, PJ_EINVAL); + + if (is_initialized) + return PJ_SUCCESS; + + /* Register Session-Expires header parser */ + status = pjsip_register_hdr_parser( STR_SE.ptr, STR_SHORT_SE.ptr, + &parse_hdr_se); + if (status != PJ_SUCCESS) + return status; + + /* Register Min-SE header parser */ + status = pjsip_register_hdr_parser( STR_MIN_SE.ptr, NULL, + &parse_hdr_min_se); + if (status != PJ_SUCCESS) + return status; + + /* Register 'timer' capability to endpoint */ + status = pjsip_endpt_add_capability(endpt, NULL, PJSIP_H_SUPPORTED, + NULL, 1, &STR_TIMER); + if (status != PJ_SUCCESS) + return status; + + /* Register deinit module to be executed when PJLIB shutdown */ + if (pjsip_endpt_atexit(endpt, &pjsip_timer_deinit_module) != PJ_SUCCESS) { + /* Failure to register this function may cause this module won't + * work properly when the stack is restarted (without quitting + * application). + */ + pj_assert(!"Failed to register Session Timer deinit."); + PJ_LOG(1, (THIS_FILE, "Failed to register Session Timer deinit.")); + } + + is_initialized = PJ_TRUE; + + return PJ_SUCCESS; +} + + +/* + * Initialize Session Timers setting with default values. + */ +PJ_DEF(pj_status_t) pjsip_timer_setting_default(pjsip_timer_setting *setting) +{ + pj_bzero(setting, sizeof(pjsip_timer_setting)); + + setting->sess_expires = PJSIP_SESS_TIMER_DEF_SE; + setting->min_se = ABS_MIN_SE; + + return PJ_SUCCESS; +} + +/* + * Initialize Session Timers in an INVITE session. + */ +PJ_DEF(pj_status_t) pjsip_timer_init_session( + pjsip_inv_session *inv, + const pjsip_timer_setting *setting) +{ + pjsip_timer_setting *s; + + pj_assert(is_initialized); + PJ_ASSERT_RETURN(inv, PJ_EINVAL); + + /* Allocate and/or reset Session Timers structure */ + if (!inv->timer) + inv->timer = PJ_POOL_ZALLOC_T(inv->pool, pjsip_timer); + else + pj_bzero(inv->timer, sizeof(pjsip_timer)); + + s = &inv->timer->setting; + + /* Init Session Timers setting */ + if (setting) { + PJ_ASSERT_RETURN(setting->min_se >= ABS_MIN_SE, + PJ_ETOOSMALL); + PJ_ASSERT_RETURN(setting->sess_expires >= setting->min_se, + PJ_EINVAL); + + pj_memcpy(s, setting, sizeof(*s)); + } else { + pjsip_timer_setting_default(s); + } + + return PJ_SUCCESS; +} + + +/* + * Create Session-Expires header. + */ +PJ_DEF(pjsip_sess_expires_hdr*) pjsip_sess_expires_hdr_create( + pj_pool_t *pool) +{ + pjsip_sess_expires_hdr *hdr = PJ_POOL_ZALLOC_T(pool, + pjsip_sess_expires_hdr); + + pj_assert(is_initialized); + + hdr->type = PJSIP_H_OTHER; + hdr->name = STR_SE; + hdr->sname = STR_SHORT_SE; + hdr->vptr = &se_hdr_vptr; + pj_list_init(hdr); + pj_list_init(&hdr->other_param); + return hdr; +} + + +/* + * Create Min-SE header. + */ +PJ_DEF(pjsip_min_se_hdr*) pjsip_min_se_hdr_create(pj_pool_t *pool) +{ + pjsip_min_se_hdr *hdr = PJ_POOL_ZALLOC_T(pool, pjsip_min_se_hdr); + + pj_assert(is_initialized); + + hdr->type = PJSIP_H_OTHER; + hdr->name = STR_MIN_SE; + hdr->vptr = &min_se_hdr_vptr; + pj_list_init(hdr); + pj_list_init(&hdr->other_param); + return hdr; +} + + +/* + * This function generates headers for Session Timers for intial and + * refresh INVITE or UPDATE. + */ +PJ_DEF(pj_status_t) pjsip_timer_update_req(pjsip_inv_session *inv, + pjsip_tx_data *tdata) +{ + PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL); + + /* Check if Session Timers is supported */ + if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) + return PJ_SUCCESS; + + pj_assert(is_initialized); + + /* Make sure Session Timers is initialized */ + if (inv->timer == NULL) + pjsip_timer_init_session(inv, NULL); + + /* If refresher role (i.e: ours or peer) has been set/negotiated, + * better to keep it. + */ + if (inv->timer->refresher != TR_UNKNOWN) { + pj_bool_t as_refresher; + + /* Check our refresher role */ + as_refresher = + (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || + (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); + + /* Update transaction role */ + inv->timer->role = PJSIP_ROLE_UAC; + + /* Update refresher role */ + inv->timer->refresher = as_refresher? TR_UAC : TR_UAS; + } + + /* Add Session Timers headers */ + add_timer_headers(inv, tdata, PJ_TRUE, PJ_TRUE); + + return PJ_SUCCESS; +} + +/* + * This function will handle Session Timers part of INVITE/UPDATE + * responses with code: + * - 422 (Session Interval Too Small) + * - 2xx final response + */ +PJ_DEF(pj_status_t) pjsip_timer_process_resp(pjsip_inv_session *inv, + const pjsip_rx_data *rdata, + pjsip_status_code *st_code) +{ + const pjsip_msg *msg; + + PJ_ASSERT_ON_FAIL(inv && rdata, + {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); + + /* Check if Session Timers is supported */ + if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) + return PJ_SUCCESS; + + pj_assert(is_initialized); + + msg = rdata->msg_info.msg; + pj_assert(msg->type == PJSIP_RESPONSE_MSG); + + /* Only process response of INVITE or UPDATE */ + if (rdata->msg_info.cseq->method.id != PJSIP_INVITE_METHOD && + pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) + { + return PJ_SUCCESS; + } + + if (msg->line.status.code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) { + /* Our Session-Expires is too small, let's update it based on + * Min-SE header in the response. + */ + pjsip_tx_data *tdata; + pjsip_min_se_hdr *min_se_hdr; + pjsip_hdr *hdr; + pjsip_via_hdr *via; + + /* Get Min-SE value from response */ + min_se_hdr = (pjsip_min_se_hdr*) + pjsip_msg_find_hdr_by_name(msg, &STR_MIN_SE, NULL); + if (min_se_hdr == NULL) { + /* Response 422 should contain Min-SE header */ + return PJ_SUCCESS; + } + + /* Session Timers should have been initialized here */ + pj_assert(inv->timer); + + /* Update Min-SE */ + inv->timer->setting.min_se = PJ_MAX(min_se_hdr->min_se, + inv->timer->setting.min_se); + + /* Update Session Timers setting */ + if (inv->timer->setting.sess_expires < inv->timer->setting.min_se) + inv->timer->setting.sess_expires = inv->timer->setting.min_se; + + /* Prepare to restart the request */ + + /* Get the original INVITE request. */ + tdata = inv->invite_req; + + /* Remove branch param in Via header. */ + via = (pjsip_via_hdr*) pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL); + pj_assert(via); + via->branch_param.slen = 0; + + /* Restore strict route set. + * See http://trac.pjsip.org/repos/ticket/492 + */ + pjsip_restore_strict_route_set(tdata); + + /* Must invalidate the message! */ + pjsip_tx_data_invalidate_msg(tdata); + + pjsip_tx_data_add_ref(tdata); + + /* Update Session Timers headers */ + hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_name(tdata->msg, + &STR_MIN_SE, NULL); + if (hdr != NULL) pj_list_erase(hdr); + + hdr = (pjsip_hdr*) pjsip_msg_find_hdr_by_names(tdata->msg, &STR_SE, + &STR_SHORT_SE, NULL); + if (hdr != NULL) pj_list_erase(hdr); + + add_timer_headers(inv, tdata, PJ_TRUE, PJ_TRUE); + + /* Restart UAC */ + pjsip_inv_uac_restart(inv, PJ_FALSE); + pjsip_inv_send_msg(inv, tdata); + + return PJ_SUCCESS; + + } else if (msg->line.status.code/100 == 2) { + + pjsip_sess_expires_hdr *se_hdr; + + /* Find Session-Expires header */ + se_hdr = (pjsip_sess_expires_hdr*) pjsip_msg_find_hdr_by_names( + msg, &STR_SE, + &STR_SHORT_SE, NULL); + if (se_hdr == NULL) { + /* Remote doesn't support/want Session Timers, check if local + * require or force to use Session Timers. + */ + if (inv->options & PJSIP_INV_REQUIRE_TIMER) { + if (st_code) + *st_code = PJSIP_SC_EXTENSION_REQUIRED; + pjsip_timer_end_session(inv); + return PJSIP_ERRNO_FROM_SIP_STATUS( + PJSIP_SC_EXTENSION_REQUIRED); + } + + if ((inv->options & PJSIP_INV_ALWAYS_USE_TIMER) == 0) { + /* Session Timers not forced */ + pjsip_timer_end_session(inv); + return PJ_SUCCESS; + } + } + + /* Make sure Session Timers is initialized */ + if (inv->timer == NULL) + pjsip_timer_init_session(inv, NULL); + + /* Session expiration period specified by remote is lower than our + * Min-SE. + */ + if (se_hdr && + se_hdr->sess_expires < inv->timer->setting.min_se) + { + /* See ticket #954, instead of returning non-PJ_SUCCESS (which + * may cause disconnecting call/dialog), let's just accept the + * SE and update our local SE, as long as it isn't less than 90s. + */ + if (se_hdr->sess_expires >= ABS_MIN_SE) { + PJ_LOG(3, (inv->pool->obj_name, + "Peer responds with bad Session-Expires, %ds, " + "which is less than Min-SE specified in request, " + "%ds. Well, let's just accept and use it.", + se_hdr->sess_expires, inv->timer->setting.min_se)); + + inv->timer->setting.sess_expires = se_hdr->sess_expires; + inv->timer->setting.min_se = se_hdr->sess_expires; + } + + //if (st_code) + // *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; + //pjsip_timer_end_session(inv); + //return PJSIP_ERRNO_FROM_SIP_STATUS( + // PJSIP_SC_SESSION_TIMER_TOO_SMALL); + } + + /* Update SE. Session-Expires in response cannot be lower than Min-SE. + * Session-Expires in response can only be equal or lower than in + * request. + */ + if (se_hdr && + se_hdr->sess_expires <= inv->timer->setting.sess_expires && + se_hdr->sess_expires >= inv->timer->setting.min_se) + { + /* Good SE from remote, update local SE */ + inv->timer->setting.sess_expires = se_hdr->sess_expires; + } + + /* Set the refresher */ + if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAC) == 0) + inv->timer->refresher = TR_UAC; + else if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAS) == 0) + inv->timer->refresher = TR_UAS; + else + /* UAS should set the refresher, however, there is a case that + * UAS doesn't support/want Session Timers but the UAC insists + * to use Session Timers. + */ + inv->timer->refresher = TR_UAC; + + /* Remember our role in this transaction */ + inv->timer->role = PJSIP_ROLE_UAC; + + /* Finally, set active flag and start the Session Timers */ + inv->timer->active = PJ_TRUE; + start_timer(inv); + + } else if (pjsip_method_cmp(&rdata->msg_info.cseq->method, + &pjsip_update_method) == 0 && + msg->line.status.code >= 400 && msg->line.status.code < 600) + { + /* This is to handle error response to previous UPDATE that was + * sent without SDP. In this case, retry sending UPDATE but + * with SDP this time. + * Note: the additional expressions are to check that the + * UPDATE was really the one sent by us, not by other + * call components (e.g. to change codec) + */ + if (inv->timer->timer.id == 0 && inv->timer->use_update && + inv->timer->with_sdp == PJ_FALSE) + { + inv->timer->with_sdp = PJ_TRUE; + timer_cb(NULL, &inv->timer->timer); + } + } + + return PJ_SUCCESS; +} + +/* + * Handle incoming INVITE or UPDATE request. + */ +PJ_DEF(pj_status_t) pjsip_timer_process_req(pjsip_inv_session *inv, + const pjsip_rx_data *rdata, + pjsip_status_code *st_code) +{ + pjsip_min_se_hdr *min_se_hdr; + pjsip_sess_expires_hdr *se_hdr; + const pjsip_msg *msg; + unsigned min_se; + + PJ_ASSERT_ON_FAIL(inv && rdata, + {if(st_code)*st_code=PJSIP_SC_INTERNAL_SERVER_ERROR;return PJ_EINVAL;}); + + /* Check if Session Timers is supported */ + if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) + return PJ_SUCCESS; + + pj_assert(is_initialized); + + msg = rdata->msg_info.msg; + pj_assert(msg->type == PJSIP_REQUEST_MSG); + + /* Only process INVITE or UPDATE request */ + if (msg->line.req.method.id != PJSIP_INVITE_METHOD && + pjsip_method_cmp(&rdata->msg_info.cseq->method, &pjsip_update_method)) + { + return PJ_SUCCESS; + } + + /* Find Session-Expires header */ + se_hdr = (pjsip_sess_expires_hdr*) pjsip_msg_find_hdr_by_names( + msg, &STR_SE, &STR_SHORT_SE, NULL); + if (se_hdr == NULL) { + /* Remote doesn't support/want Session Timers, check if local + * require or force to use Session Timers. Note that Supported and + * Require headers negotiation should have been verified by invite + * session. + */ + if ((inv->options & + (PJSIP_INV_REQUIRE_TIMER | PJSIP_INV_ALWAYS_USE_TIMER)) == 0) + { + /* Session Timers not forced/required */ + pjsip_timer_end_session(inv); + return PJ_SUCCESS; + } + } + + /* Make sure Session Timers is initialized */ + if (inv->timer == NULL) + pjsip_timer_init_session(inv, NULL); + + /* Find Min-SE header */ + min_se_hdr = (pjsip_min_se_hdr*) pjsip_msg_find_hdr_by_name(msg, + &STR_MIN_SE, NULL); + /* Update Min-SE */ + min_se = inv->timer->setting.min_se; + if (min_se_hdr) + min_se = PJ_MAX(min_se_hdr->min_se, min_se); + + /* Validate SE. Session-Expires cannot be lower than Min-SE + * (or 90 seconds if Min-SE is not set). + */ + if (se_hdr && se_hdr->sess_expires < min_se) { + if (st_code) + *st_code = PJSIP_SC_SESSION_TIMER_TOO_SMALL; + return PJSIP_ERRNO_FROM_SIP_STATUS(PJSIP_SC_SESSION_TIMER_TOO_SMALL); + } + + /* Update SE. Note that there is a case that SE is not available in the + * request (which means remote doesn't want/support it), but local insists + * to use Session Timers. + */ + if (se_hdr) { + /* Update SE as specified by peer. */ + inv->timer->setting.sess_expires = se_hdr->sess_expires; + } else if (inv->timer->setting.sess_expires < min_se) { + /* There is no SE in the request (remote support Session Timers but + * doesn't want to use it, it just specify Min-SE) and local SE is + * lower than Min-SE specified by remote. + */ + inv->timer->setting.sess_expires = min_se; + } + + /* Set the refresher */ + if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAC) == 0) + inv->timer->refresher = TR_UAC; + else if (se_hdr && pj_stricmp(&se_hdr->refresher, &STR_UAS) == 0) + inv->timer->refresher = TR_UAS; + else { + /* If refresher role (i.e: ours or peer) has been set/negotiated, + * better to keep it. + */ + if (inv->timer->refresher != TR_UNKNOWN) { + pj_bool_t as_refresher; + + /* Check our refresher role */ + as_refresher = + (inv->timer->refresher==TR_UAC && inv->timer->role==PJSIP_ROLE_UAC) || + (inv->timer->refresher==TR_UAS && inv->timer->role==PJSIP_ROLE_UAS); + + /* Update refresher role */ + inv->timer->refresher = as_refresher? TR_UAS : TR_UAC; + } else { + /* If UAC support timer (currently check the existance of + * Session-Expires header in the request), set UAC as refresher. + */ + inv->timer->refresher = se_hdr? TR_UAC : TR_UAS; + } + } + + /* Remember our role in this transaction */ + inv->timer->role = PJSIP_ROLE_UAS; + + /* Set active flag */ + inv->timer->active = PJ_TRUE; + + return PJ_SUCCESS; +} + +/* + * Handle outgoing response with status code 2xx & 422. + */ +PJ_DEF(pj_status_t) pjsip_timer_update_resp(pjsip_inv_session *inv, + pjsip_tx_data *tdata) +{ + pjsip_msg *msg; + + /* Check if Session Timers is supported */ + if ((inv->options & PJSIP_INV_SUPPORT_TIMER) == 0) + return PJ_SUCCESS; + + pj_assert(is_initialized); + PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL); + + msg = tdata->msg; + + if (msg->line.status.code/100 == 2) + { + if (inv->timer && inv->timer->active) { + /* Add Session-Expires header and start the timer */ + add_timer_headers(inv, tdata, PJ_TRUE, PJ_FALSE); + start_timer(inv); + } + } + else if (msg->line.status.code == PJSIP_SC_SESSION_TIMER_TOO_SMALL) + { + /* Add Min-SE header */ + add_timer_headers(inv, tdata, PJ_FALSE, PJ_TRUE); + } + + return PJ_SUCCESS; +} + + +/* + * End the Session Timers. + */ +PJ_DEF(pj_status_t) pjsip_timer_end_session(pjsip_inv_session *inv) +{ + PJ_ASSERT_RETURN(inv, PJ_EINVAL); + + if (inv->timer) { + /* Reset active flag */ + inv->timer->active = PJ_FALSE; + + /* Stop Session Timers */ + stop_timer(inv); + } + + return PJ_SUCCESS; +} diff --git a/pjsip/src/pjsip-ua/sip_xfer.c b/pjsip/src/pjsip-ua/sip_xfer.c new file mode 100644 index 0000000..cfa3e10 --- /dev/null +++ b/pjsip/src/pjsip-ua/sip_xfer.c @@ -0,0 +1,630 @@ +/* $Id: sip_xfer.c 3553 2011-05-05 06:14:19Z nanang $ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include <pjsip-ua/sip_xfer.h> +#include <pjsip-simple/evsub_msg.h> +#include <pjsip/sip_dialog.h> +#include <pjsip/sip_errno.h> +#include <pjsip/sip_endpoint.h> +#include <pjsip/sip_module.h> +#include <pjsip/sip_transport.h> +#include <pj/assert.h> +#include <pj/pool.h> +#include <pj/string.h> + +/* Subscription expiration */ +#ifndef PJSIP_XFER_EXPIRES +# define PJSIP_XFER_EXPIRES 600 +#endif + + +/* + * Refer module (mod-refer) + */ +static struct pjsip_module mod_xfer = +{ + NULL, NULL, /* prev, next. */ + { "mod-refer", 9 }, /* Name. */ + -1, /* Id */ + PJSIP_MOD_PRIORITY_DIALOG_USAGE, /* Priority */ + NULL, /* load() */ + NULL, /* start() */ + NULL, /* stop() */ + NULL, /* unload() */ + NULL, /* on_rx_request() */ + NULL, /* on_rx_response() */ + NULL, /* on_tx_request. */ + NULL, /* on_tx_response() */ + NULL, /* on_tsx_state() */ +}; + + +/* Declare PJSIP_REFER_METHOD, so that if somebody declares this in + * sip_msg.h we can catch the error here. + */ +enum +{ + PJSIP_REFER_METHOD = PJSIP_OTHER_METHOD +}; + +PJ_DEF_DATA(const pjsip_method) pjsip_refer_method = { + (pjsip_method_e) PJSIP_REFER_METHOD, + { "REFER", 5} +}; + +PJ_DEF(const pjsip_method*) pjsip_get_refer_method() +{ + return &pjsip_refer_method; +} + +/* + * String constants + */ +const pj_str_t STR_REFER = { "refer", 5 }; +const pj_str_t STR_MESSAGE = { "message", 7 }; +const pj_str_t STR_SIPFRAG = { "sipfrag", 7 }; +const pj_str_t STR_SIPFRAG_VERSION = {";version=2.0", 12 }; + + +/* + * Transfer struct. + */ +struct pjsip_xfer +{ + pjsip_evsub *sub; /**< Event subscribtion record. */ + pjsip_dialog *dlg; /**< The dialog. */ + pjsip_evsub_user user_cb; /**< The user callback. */ + pj_str_t refer_to_uri; /**< The full Refer-To URI. */ + int last_st_code; /**< st_code sent in last NOTIFY */ + pj_str_t last_st_text; /**< st_text sent in last NOTIFY */ +}; + + +typedef struct pjsip_xfer pjsip_xfer; + + + +/* + * Forward decl for evsub callback. + */ +static void xfer_on_evsub_state( pjsip_evsub *sub, pjsip_event *event); +static void xfer_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, + pjsip_event *event); +static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); +static void xfer_on_evsub_rx_notify( pjsip_evsub *sub, + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body); +static void xfer_on_evsub_client_refresh(pjsip_evsub *sub); +static void xfer_on_evsub_server_timeout(pjsip_evsub *sub); + + +/* + * Event subscription callback for xference. + */ +static pjsip_evsub_user xfer_user = +{ + &xfer_on_evsub_state, + &xfer_on_evsub_tsx_state, + &xfer_on_evsub_rx_refresh, + &xfer_on_evsub_rx_notify, + &xfer_on_evsub_client_refresh, + &xfer_on_evsub_server_timeout, +}; + + + + +/* + * Initialize the REFER subsystem. + */ +PJ_DEF(pj_status_t) pjsip_xfer_init_module(pjsip_endpoint *endpt) +{ + const pj_str_t accept = { "message/sipfrag;version=2.0", 27 }; + pj_status_t status; + + PJ_ASSERT_RETURN(endpt != NULL, PJ_EINVAL); + PJ_ASSERT_RETURN(mod_xfer.id == -1, PJ_EINVALIDOP); + + status = pjsip_endpt_register_module(endpt, &mod_xfer); + if (status != PJ_SUCCESS) + return status; + + status = pjsip_endpt_add_capability( endpt, &mod_xfer, PJSIP_H_ALLOW, + NULL, 1, + &pjsip_get_refer_method()->name); + if (status != PJ_SUCCESS) + return status; + + status = pjsip_evsub_register_pkg(&mod_xfer, &STR_REFER, + PJSIP_XFER_EXPIRES, 1, &accept); + if (status != PJ_SUCCESS) + return status; + + return PJ_SUCCESS; +} + + +/* + * Create transferer (sender of REFER request). + * + */ +PJ_DEF(pj_status_t) pjsip_xfer_create_uac( pjsip_dialog *dlg, + const pjsip_evsub_user *user_cb, + pjsip_evsub **p_evsub ) +{ + pj_status_t status; + pjsip_xfer *xfer; + pjsip_evsub *sub; + + PJ_ASSERT_RETURN(dlg && p_evsub, PJ_EINVAL); + + pjsip_dlg_inc_lock(dlg); + + /* Create event subscription */ + status = pjsip_evsub_create_uac( dlg, &xfer_user, &STR_REFER, + PJSIP_EVSUB_NO_EVENT_ID, &sub); + if (status != PJ_SUCCESS) + goto on_return; + + /* Create xfer session */ + xfer = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_xfer); + xfer->dlg = dlg; + xfer->sub = sub; + if (user_cb) + pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); + + /* Attach to evsub */ + pjsip_evsub_set_mod_data(sub, mod_xfer.id, xfer); + + *p_evsub = sub; + +on_return: + pjsip_dlg_dec_lock(dlg); + return status; + +} + + + + +/* + * Create transferee (receiver of REFER request). + * + */ +PJ_DEF(pj_status_t) pjsip_xfer_create_uas( pjsip_dialog *dlg, + const pjsip_evsub_user *user_cb, + pjsip_rx_data *rdata, + pjsip_evsub **p_evsub ) +{ + pjsip_evsub *sub; + pjsip_xfer *xfer; + const pj_str_t STR_EVENT = {"Event", 5 }; + pjsip_event_hdr *event_hdr; + pj_status_t status; + + /* Check arguments */ + PJ_ASSERT_RETURN(dlg && rdata && p_evsub, PJ_EINVAL); + + /* Must be request message */ + PJ_ASSERT_RETURN(rdata->msg_info.msg->type == PJSIP_REQUEST_MSG, + PJSIP_ENOTREQUESTMSG); + + /* Check that request is REFER */ + PJ_ASSERT_RETURN(pjsip_method_cmp(&rdata->msg_info.msg->line.req.method, + pjsip_get_refer_method())==0, + PJSIP_ENOTREFER); + + /* Lock dialog */ + pjsip_dlg_inc_lock(dlg); + + /* The evsub framework expects an Event header in the request, + * while a REFER request conveniently doesn't have one (pun intended!). + * So create a dummy Event header. + */ + if (pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, + &STR_EVENT, NULL)==NULL) + { + event_hdr = pjsip_event_hdr_create(rdata->tp_info.pool); + event_hdr->event_type = STR_REFER; + pjsip_msg_add_hdr(rdata->msg_info.msg, (pjsip_hdr*)event_hdr); + } + + /* Create server subscription */ + status = pjsip_evsub_create_uas( dlg, &xfer_user, rdata, + PJSIP_EVSUB_NO_EVENT_ID, &sub); + if (status != PJ_SUCCESS) + goto on_return; + + /* Create server xfer subscription */ + xfer = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_xfer); + xfer->dlg = dlg; + xfer->sub = sub; + if (user_cb) + pj_memcpy(&xfer->user_cb, user_cb, sizeof(pjsip_evsub_user)); + + /* Attach to evsub */ + pjsip_evsub_set_mod_data(sub, mod_xfer.id, xfer); + + /* Done: */ + *p_evsub = sub; + +on_return: + pjsip_dlg_dec_lock(dlg); + return status; +} + + + +/* + * Call this function to create request to initiate REFER subscription. + * + */ +PJ_DEF(pj_status_t) pjsip_xfer_initiate( pjsip_evsub *sub, + const pj_str_t *refer_to_uri, + pjsip_tx_data **p_tdata) +{ + pjsip_xfer *xfer; + const pj_str_t refer_to = { "Refer-To", 8}; + pjsip_tx_data *tdata; + pjsip_generic_string_hdr *hdr; + pj_status_t status; + + /* sub and p_tdata argument must be valid. */ + PJ_ASSERT_RETURN(sub && p_tdata, PJ_EINVAL); + + + /* Get the xfer object. */ + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_RETURN(xfer != NULL, PJSIP_ENOREFERSESSION); + + /* refer_to_uri argument MAY be NULL for subsequent REFER requests, + * but it MUST be specified in the first REFER. + */ + PJ_ASSERT_RETURN((refer_to_uri || xfer->refer_to_uri.slen), PJ_EINVAL); + + /* Lock dialog. */ + pjsip_dlg_inc_lock(xfer->dlg); + + /* Create basic REFER request */ + status = pjsip_evsub_initiate(sub, pjsip_get_refer_method(), -1, + &tdata); + if (status != PJ_SUCCESS) + goto on_return; + + /* Save Refer-To URI. */ + if (refer_to_uri == NULL) { + refer_to_uri = &xfer->refer_to_uri; + } else { + pj_strdup(xfer->dlg->pool, &xfer->refer_to_uri, refer_to_uri); + } + + /* Create and add Refer-To header. */ + hdr = pjsip_generic_string_hdr_create(tdata->pool, &refer_to, + refer_to_uri); + if (!hdr) { + pjsip_tx_data_dec_ref(tdata); + status = PJ_ENOMEM; + goto on_return; + } + + pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)hdr); + + + /* Done. */ + *p_tdata = tdata; + + status = PJ_SUCCESS; + +on_return: + pjsip_dlg_dec_lock(xfer->dlg); + return status; +} + + +/* + * Accept the incoming REFER request by sending 2xx response. + * + */ +PJ_DEF(pj_status_t) pjsip_xfer_accept( pjsip_evsub *sub, + pjsip_rx_data *rdata, + int st_code, + const pjsip_hdr *hdr_list ) +{ + /* + * Don't need to add custom headers, so just call basic + * evsub response. + */ + return pjsip_evsub_accept( sub, rdata, st_code, hdr_list ); +} + + +/* + * For notifier, create NOTIFY request to subscriber, and set the state + * of the subscription. + */ +PJ_DEF(pj_status_t) pjsip_xfer_notify( pjsip_evsub *sub, + pjsip_evsub_state state, + int xfer_st_code, + const pj_str_t *xfer_st_text, + pjsip_tx_data **p_tdata) +{ + pjsip_tx_data *tdata; + pjsip_xfer *xfer; + pjsip_param *param; + const pj_str_t reason = { "noresource", 10 }; + char *body; + int bodylen; + pjsip_msg_body *msg_body; + pj_status_t status; + + + /* Check arguments. */ + PJ_ASSERT_RETURN(sub, PJ_EINVAL); + + /* Get the xfer object. */ + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_RETURN(xfer != NULL, PJSIP_ENOREFERSESSION); + + + /* Lock object. */ + pjsip_dlg_inc_lock(xfer->dlg); + + /* Create the NOTIFY request. + * Note that reason is only used when state is TERMINATED, and + * the defined termination reason for REFER is "noresource". + */ + status = pjsip_evsub_notify( sub, state, NULL, &reason, &tdata); + if (status != PJ_SUCCESS) + goto on_return; + + + /* Check status text */ + if (xfer_st_text==NULL || xfer_st_text->slen==0) + xfer_st_text = pjsip_get_status_text(xfer_st_code); + + /* Save st_code and st_text, for current_notify() */ + xfer->last_st_code = xfer_st_code; + pj_strdup(xfer->dlg->pool, &xfer->last_st_text, xfer_st_text); + + /* Create sipfrag content. */ + body = (char*) pj_pool_alloc(tdata->pool, 128); + bodylen = pj_ansi_snprintf(body, 128, "SIP/2.0 %u %.*s\r\n", + xfer_st_code, + (int)xfer_st_text->slen, + xfer_st_text->ptr); + PJ_ASSERT_ON_FAIL(bodylen > 0 && bodylen < 128, + {status=PJ_EBUG; pjsip_tx_data_dec_ref(tdata); + goto on_return; }); + + + /* Create SIP message body. */ + msg_body = PJ_POOL_ZALLOC_T(tdata->pool, pjsip_msg_body); + pjsip_media_type_init(&msg_body->content_type, (pj_str_t*)&STR_MESSAGE, + (pj_str_t*)&STR_SIPFRAG); + msg_body->data = body; + msg_body->len = bodylen; + msg_body->print_body = &pjsip_print_text_body; + msg_body->clone_data = &pjsip_clone_text_data; + + param = PJ_POOL_ALLOC_T(tdata->pool, pjsip_param); + param->name = pj_str("version"); + param->value = pj_str("2.0"); + pj_list_push_back(&msg_body->content_type.param, param); + + /* Attach sipfrag body. */ + tdata->msg->body = msg_body; + + + /* Done. */ + *p_tdata = tdata; + + +on_return: + pjsip_dlg_dec_lock(xfer->dlg); + return status; + +} + + +/* + * Send current state and the last sipfrag body. + */ +PJ_DEF(pj_status_t) pjsip_xfer_current_notify( pjsip_evsub *sub, + pjsip_tx_data **p_tdata ) +{ + pjsip_xfer *xfer; + pj_status_t status; + + + /* Check arguments. */ + PJ_ASSERT_RETURN(sub, PJ_EINVAL); + + /* Get the xfer object. */ + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_RETURN(xfer != NULL, PJSIP_ENOREFERSESSION); + + pjsip_dlg_inc_lock(xfer->dlg); + + status = pjsip_xfer_notify(sub, pjsip_evsub_get_state(sub), + xfer->last_st_code, &xfer->last_st_text, + p_tdata); + + pjsip_dlg_dec_lock(xfer->dlg); + + return status; +} + + +/* + * Send request message. + */ +PJ_DEF(pj_status_t) pjsip_xfer_send_request( pjsip_evsub *sub, + pjsip_tx_data *tdata) +{ + return pjsip_evsub_send_request(sub, tdata); +} + + +/* + * This callback is called by event subscription when subscription + * state has changed. + */ +static void xfer_on_evsub_state( pjsip_evsub *sub, pjsip_event *event) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_evsub_state) + (*xfer->user_cb.on_evsub_state)(sub, event); + +} + +/* + * Called when transaction state has changed. + */ +static void xfer_on_evsub_tsx_state( pjsip_evsub *sub, pjsip_transaction *tsx, + pjsip_event *event) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_tsx_state) + (*xfer->user_cb.on_tsx_state)(sub, tsx, event); +} + +/* + * Called when REFER is received to refresh subscription. + */ +static void xfer_on_evsub_rx_refresh( pjsip_evsub *sub, + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_rx_refresh) { + (*xfer->user_cb.on_rx_refresh)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); + + } else { + /* Implementors MUST send NOTIFY if it implements on_rx_refresh + * (implementor == "us" from evsub point of view. + */ + pjsip_tx_data *tdata; + pj_status_t status; + + if (pjsip_evsub_get_state(sub)==PJSIP_EVSUB_STATE_TERMINATED) { + status = pjsip_xfer_notify( sub, PJSIP_EVSUB_STATE_TERMINATED, + xfer->last_st_code, + &xfer->last_st_text, + &tdata); + } else { + status = pjsip_xfer_current_notify(sub, &tdata); + } + + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); + } +} + + +/* + * Called when NOTIFY is received. + */ +static void xfer_on_evsub_rx_notify( pjsip_evsub *sub, + pjsip_rx_data *rdata, + int *p_st_code, + pj_str_t **p_st_text, + pjsip_hdr *res_hdr, + pjsip_msg_body **p_body) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_rx_notify) + (*xfer->user_cb.on_rx_notify)(sub, rdata, p_st_code, p_st_text, + res_hdr, p_body); +} + +/* + * Called when it's time to send SUBSCRIBE. + */ +static void xfer_on_evsub_client_refresh(pjsip_evsub *sub) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_client_refresh) { + (*xfer->user_cb.on_client_refresh)(sub); + } else { + pj_status_t status; + pjsip_tx_data *tdata; + + status = pjsip_evsub_initiate(sub, NULL, PJSIP_XFER_EXPIRES, &tdata); + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); + } +} + + +/* + * Called when no refresh is received after the interval. + */ +static void xfer_on_evsub_server_timeout(pjsip_evsub *sub) +{ + pjsip_xfer *xfer; + + xfer = (pjsip_xfer*) pjsip_evsub_get_mod_data(sub, mod_xfer.id); + PJ_ASSERT_ON_FAIL(xfer!=NULL, {return;}); + + if (xfer->user_cb.on_server_timeout) { + (*xfer->user_cb.on_server_timeout)(sub); + } else { + pj_status_t status; + pjsip_tx_data *tdata; + + status = pjsip_xfer_notify(sub, PJSIP_EVSUB_STATE_TERMINATED, + xfer->last_st_code, + &xfer->last_st_text, &tdata); + if (status == PJ_SUCCESS) + pjsip_xfer_send_request(sub, tdata); + } +} + |