1 /* $Id$ */
2 /*
3  * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4  * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 #include <pjsip-ua/sip_inv.h>
21 #include <pjsip-ua/sip_100rel.h>
22 #include <pjsip-ua/sip_timer.h>
23 #include <pjsip/sip_module.h>
24 #include <pjsip/sip_endpoint.h>
25 #include <pjsip/sip_event.h>
26 #include <pjsip/sip_multipart.h>
27 #include <pjsip/sip_transaction.h>
28 #include <pjmedia/sdp.h>
29 #include <pjmedia/sdp_neg.h>
30 #include <pjmedia/errno.h>
31 #include <pj/array.h>
32 #include <pj/string.h>
33 #include <pj/pool.h>
34 #include <pj/assert.h>
35 #include <pj/os.h>
36 #include <pj/log.h>
37 #include <pj/rand.h>
38 
39 /*
40  * Note on offer/answer:
41  *
42  * The offer/answer framework in this implementation assumes the occurence
43  * of SDP in a particular request/response according to this table:
44 
45 		  offer   answer    Note:
46     ========================================================================
47     INVITE	    X		    INVITE may contain offer
48     18x/INVITE	    X	    X	    Response may contain offer or answer
49     2xx/INVITE	    X	    X	    Response may contain offer or answer
50     ACK			    X	    ACK may contain answer
51 
52     PRACK		    X	    PRACK can only contain answer
53     2xx/PRACK	    		    Response may not have offer nor answer
54 
55     UPDATE	    X		    UPDATE may only contain offer
56     2xx/UPDATE		    X	    Response may only contain answer
57     ========================================================================
58 
59   *
60   */
61 
62 #define THIS_FILE	"sip_inv.c"
63 
64 static const char *inv_state_names[] =
65 {
66     "NULL",
67     "CALLING",
68     "INCOMING",
69     "EARLY",
70     "CONNECTING",
71     "CONFIRMED",
72     "DISCONNCTD",
73     "TERMINATED",
74 };
75 
76 /* UPDATE method */
77 static const pjsip_method pjsip_update_method =
78 {
79     PJSIP_OTHER_METHOD,
80     { "UPDATE", 6 }
81 };
82 
83 #define POOL_INIT_SIZE	256
84 #define POOL_INC_SIZE	256
85 
86 /*
87  * Static prototypes.
88  */
89 static pj_status_t mod_inv_load(pjsip_endpoint *endpt);
90 static pj_status_t mod_inv_unload(void);
91 static pj_bool_t   mod_inv_on_rx_request(pjsip_rx_data *rdata);
92 static pj_bool_t   mod_inv_on_rx_response(pjsip_rx_data *rdata);
93 static void	   mod_inv_on_tsx_state(pjsip_transaction*, pjsip_event*);
94 
95 static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e);
96 static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e);
97 static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e);
98 static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e);
99 static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e);
100 static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e);
101 static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e);
102 
103 static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv,
104 						  pjsip_transaction *tsx,
105 						  pjsip_rx_data *rdata);
106 static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv );
107 static pjsip_msg_body *create_sdp_body(pj_pool_t *pool,
108 				       const pjmedia_sdp_session *c_sdp);
109 static pj_status_t process_answer( pjsip_inv_session *inv,
110 				   int st_code,
111 				   pjsip_tx_data *tdata,
112 				   const pjmedia_sdp_session *local_sdp);
113 
114 static pj_status_t handle_timer_response(pjsip_inv_session *inv,
115 				         const pjsip_rx_data *rdata,
116 				         pj_bool_t end_sess_on_failure);
117 
118 static pj_bool_t inv_check_secure_dlg(pjsip_inv_session *inv,
119 				      pjsip_event *e);
120 
121 static void (*inv_state_handler[])( pjsip_inv_session *inv, pjsip_event *e) =
122 {
123     &inv_on_state_null,
124     &inv_on_state_calling,
125     &inv_on_state_incoming,
126     &inv_on_state_early,
127     &inv_on_state_connecting,
128     &inv_on_state_confirmed,
129     &inv_on_state_disconnected,
130 };
131 
132 static struct mod_inv
133 {
134     pjsip_module	 mod;
135     pjsip_endpoint	*endpt;
136     pjsip_inv_callback	 cb;
137 } mod_inv =
138 {
139     {
140 	NULL, NULL,			    /* prev, next.		*/
141 	{ "mod-invite", 10 },		    /* Name.			*/
142 	-1,				    /* Id			*/
143 	PJSIP_MOD_PRIORITY_DIALOG_USAGE,    /* Priority			*/
144 	&mod_inv_load,			    /* load()			*/
145 	NULL,				    /* start()			*/
146 	NULL,				    /* stop()			*/
147 	&mod_inv_unload,		    /* unload()			*/
148 	&mod_inv_on_rx_request,		    /* on_rx_request()		*/
149 	&mod_inv_on_rx_response,	    /* on_rx_response()		*/
150 	NULL,				    /* on_tx_request.		*/
151 	NULL,				    /* on_tx_response()		*/
152 	&mod_inv_on_tsx_state,		    /* on_tsx_state()		*/
153     }
154 };
155 
156 
157 /* Invite session data to be attached to transaction. */
158 struct tsx_inv_data
159 {
160     pjsip_inv_session	*inv;	    /* The invite session		    */
161     pj_bool_t		 sdp_done;  /* SDP negotiation done for this tsx?   */
162     pj_bool_t		 retrying;  /* Resend (e.g. due to 401/407)         */
163     pj_str_t		 done_tag;  /* To tag in RX response with answer    */
164     pj_bool_t		 done_early;/* Negotiation was done for early med?  */
165     pj_bool_t		 done_early_rel;/* Early med was realiable?	    */
166     pj_bool_t		 has_sdp;   /* Message with SDP?		    */
167 };
168 
169 /*
170  * Module load()
171  */
mod_inv_load(pjsip_endpoint * endpt)172 static pj_status_t mod_inv_load(pjsip_endpoint *endpt)
173 {
174     pj_str_t allowed[] = {{"INVITE", 6}, {"ACK",3}, {"BYE",3}, {"CANCEL",6},
175 			    { "UPDATE", 6}};
176     pj_str_t accepted = { "application/sdp", 15 };
177 
178     /* Register supported methods: INVITE, ACK, BYE, CANCEL, UPDATE */
179     pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ALLOW, NULL,
180 			       PJ_ARRAY_SIZE(allowed), allowed);
181 
182     /* Register "application/sdp" in Accept header */
183     pjsip_endpt_add_capability(endpt, &mod_inv.mod, PJSIP_H_ACCEPT, NULL,
184 			       1, &accepted);
185 
186     return PJ_SUCCESS;
187 }
188 
189 /*
190  * Module unload()
191  */
mod_inv_unload(void)192 static pj_status_t mod_inv_unload(void)
193 {
194     /* Should remove capability here */
195     return PJ_SUCCESS;
196 }
197 
198 /*
199  * Add reference to INVITE session.
200  */
pjsip_inv_add_ref(pjsip_inv_session * inv)201 PJ_DEF(pj_status_t) pjsip_inv_add_ref( pjsip_inv_session *inv )
202 {
203     PJ_ASSERT_RETURN(inv && inv->ref_cnt, PJ_EINVAL);
204 
205     pj_atomic_inc(inv->ref_cnt);
206 
207     return PJ_SUCCESS;
208 }
209 
inv_session_destroy(pjsip_inv_session * inv)210 static void inv_session_destroy(pjsip_inv_session *inv)
211 {
212     if (inv->last_ack) {
213 	pjsip_tx_data_dec_ref(inv->last_ack);
214 	inv->last_ack = NULL;
215     }
216     if (inv->invite_req) {
217 	pjsip_tx_data_dec_ref(inv->invite_req);
218 	inv->invite_req = NULL;
219     }
220     if (inv->pending_bye) {
221 	pjsip_tx_data_dec_ref(inv->pending_bye);
222 	inv->pending_bye = NULL;
223     }
224     pjsip_100rel_end_session(inv);
225     pjsip_timer_end_session(inv);
226     pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod);
227 
228     /* Release the flip-flop pools */
229     pj_pool_release(inv->pool_prov);
230     inv->pool_prov = NULL;
231     pj_pool_release(inv->pool_active);
232     inv->pool_active = NULL;
233 
234     pj_atomic_destroy(inv->ref_cnt);
235     inv->ref_cnt = NULL;
236 }
237 
238 /*
239  * Decrease INVITE session reference, destroy it when the reference count
240  * reaches zero.
241  */
pjsip_inv_dec_ref(pjsip_inv_session * inv)242 PJ_DEF(pj_status_t) pjsip_inv_dec_ref( pjsip_inv_session *inv )
243 {
244     pj_atomic_value_t ref_cnt;
245 
246     PJ_ASSERT_RETURN(inv && inv->ref_cnt, PJ_EINVAL);
247 
248     ref_cnt = pj_atomic_dec_and_get(inv->ref_cnt);
249     pj_assert( ref_cnt >= 0);
250     if (ref_cnt == 0) {
251         inv_session_destroy(inv);
252         return PJ_EGONE;
253     }
254     return PJ_SUCCESS;
255 }
256 
257 /*
258  * Set session state.
259  */
inv_set_state(pjsip_inv_session * inv,pjsip_inv_state state,pjsip_event * e)260 static void inv_set_state(pjsip_inv_session *inv, pjsip_inv_state state,
261 			  pjsip_event *e)
262 {
263     pjsip_inv_state prev_state = inv->state;
264     pj_bool_t dont_notify = PJ_FALSE;
265     pj_status_t status;
266 
267     /* Prevent STATE_CALLING from being reported more than once because
268      * of authentication
269      * https://trac.pjsip.org/repos/ticket/1318
270      */
271     if (state==PJSIP_INV_STATE_CALLING &&
272 	(inv->cb_called & (1 << PJSIP_INV_STATE_CALLING)) != 0)
273     {
274 	dont_notify = PJ_TRUE;
275     }
276 
277     /* If state is confirmed, check that SDP negotiation is done,
278      * otherwise disconnect the session.
279      */
280     if (state == PJSIP_INV_STATE_CONFIRMED) {
281 	struct tsx_inv_data *tsx_inv_data = NULL;
282 
283 	if (inv->invite_tsx) {
284 	    tsx_inv_data = (struct tsx_inv_data*)
285 			   inv->invite_tsx->mod_data[mod_inv.mod.id];
286 	}
287 
288 	if ((tsx_inv_data && !tsx_inv_data->sdp_done) &&
289 	    (!inv->neg || pjmedia_sdp_neg_get_state(inv->neg)!=
290 						PJMEDIA_SDP_NEG_STATE_DONE))
291 	{
292 	    pjsip_tx_data *bye;
293 
294 	    PJ_LOG(4,(inv->obj_name, "SDP offer/answer incomplete, ending the "
295 		      "session"));
296 
297 	    status = pjsip_inv_end_session(inv, PJSIP_SC_NOT_ACCEPTABLE,
298 					   NULL, &bye);
299 	    if (status == PJ_SUCCESS && bye)
300 		status = pjsip_inv_send_msg(inv, bye);
301 
302 	    return;
303 	}
304     }
305 
306     /* Set state. */
307     inv->state = state;
308 
309     /* If state is DISCONNECTED, cause code MUST have been set. */
310     pj_assert(inv->state != PJSIP_INV_STATE_DISCONNECTED ||
311 	      inv->cause != 0);
312 
313     /* Mark the callback as called for this state */
314     inv->cb_called |= (1 << state);
315 
316     /* Call on_state_changed() callback.
317      * While in the callback, can the state shift to DISCONNECTED? Perhaps
318      * yes, so better avoid premature destroy of the invite session by
319      * temporarily increase its ref counter.
320      */
321     pjsip_inv_add_ref(inv);
322     if (mod_inv.cb.on_state_changed && inv->notify && !dont_notify)
323 	(*mod_inv.cb.on_state_changed)(inv, e);
324     pjsip_inv_dec_ref(inv);
325 
326     /* The above callback may change the state, so we need to be careful here
327      * and only decrement inv under the following conditions:
328      * 1. If the state parameter is DISCONNECTED, and previous state is not
329      *    already DISCONNECTED.
330      *    This is to make sure that dec_ref() is not called more than once.
331      * 2. If current state is PJSIP_INV_STATE_DISCONNECTED.
332      *    This is to make sure that dec_ref() is not called if user restarts
333      *    inv within the callback. Note that this check must be last since
334      *    inv may have already been destroyed.
335      */
336     if (state == PJSIP_INV_STATE_DISCONNECTED &&
337 	prev_state != PJSIP_INV_STATE_DISCONNECTED &&
338 	inv->state == PJSIP_INV_STATE_DISCONNECTED)
339     {
340 	pjsip_inv_dec_ref(inv);
341     }
342 }
343 
344 
345 /*
346  * Set cause code.
347  */
inv_set_cause(pjsip_inv_session * inv,int cause_code,const pj_str_t * cause_text)348 static void inv_set_cause(pjsip_inv_session *inv, int cause_code,
349 			  const pj_str_t *cause_text)
350 {
351     if ((cause_code > inv->cause) || inv->pending_bye) {
352 	inv->cause = (pjsip_status_code) cause_code;
353 	if (cause_text)
354 	    pj_strdup(inv->pool, &inv->cause_text, cause_text);
355 	else if (cause_code/100 == 2)
356 	    inv->cause_text = pj_str("Normal call clearing");
357 	else
358 	    inv->cause_text = *pjsip_get_status_text(cause_code);
359     }
360 }
361 
362 
363 /*
364  * Check if outgoing request needs to have SDP answer.
365  * This applies for both ACK and PRACK requests.
366  */
inv_has_pending_answer(pjsip_inv_session * inv,pjsip_transaction * tsx)367 static const pjmedia_sdp_session *inv_has_pending_answer(pjsip_inv_session *inv,
368 						         pjsip_transaction *tsx)
369 {
370     pjmedia_sdp_neg_state neg_state;
371     const pjmedia_sdp_session *sdp = NULL;
372     pj_status_t status;
373 
374     /* If SDP negotiator is ready, start negotiation. */
375 
376     /* Start nego when appropriate. */
377     neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) :
378 		PJMEDIA_SDP_NEG_STATE_NULL;
379 
380     if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) {
381 
382 	/* Nothing to do */
383 
384     } else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
385 	       pjmedia_sdp_neg_has_local_answer(inv->neg) )
386     {
387 	struct tsx_inv_data *tsx_inv_data;
388 	struct tsx_inv_data dummy;
389 
390 	/* Get invite session's transaction data.
391 	 * Note that tsx may be NULL, for example when application sends
392 	 * delayed ACK request (at this time, the original INVITE
393 	 * transaction may have been destroyed.
394 	 */
395 	if (tsx) {
396 	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
397 	} else {
398 	    tsx_inv_data = &dummy;
399 	    pj_bzero(&dummy, sizeof(dummy));
400 	    dummy.inv = inv;
401 	}
402 
403 	status = inv_negotiate_sdp(inv);
404 	if (status != PJ_SUCCESS)
405 	    return NULL;
406 
407 	/* Mark this transaction has having SDP offer/answer done. */
408 	tsx_inv_data->sdp_done = 1;
409 
410 	status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
411 
412     } else {
413 	/* This remark is only valid for ACK.
414 	PJ_LOG(4,(inv->dlg->obj_name,
415 		  "FYI, the SDP negotiator state (%s) is in a mess "
416 		  "when sending this ACK/PRACK request",
417 		  pjmedia_sdp_neg_state_str(neg_state)));
418 	 */
419     }
420 
421     return sdp;
422 }
423 
424 /* Process pending disconnection
425  *  http://trac.pjsip.org/repos/ticket/1712
426  */
inv_perform_pending_bye(pjsip_inv_session * inv)427 static void inv_perform_pending_bye(pjsip_inv_session *inv)
428 {
429     if (inv->pending_bye) {
430 	pjsip_tx_data *bye = inv->pending_bye;
431 	pj_status_t status;
432 
433 	PJ_LOG(4,(inv->dlg->obj_name, "Sending pending BYE"));
434 
435 	inv->pending_bye = NULL;
436 	status = pjsip_inv_send_msg(inv, bye);
437 
438 	if (status != PJ_SUCCESS) {
439 	    PJ_PERROR(1,(inv->dlg->obj_name, status,
440 			 "Failed sending pending BYE"));
441 	}
442     }
443 }
444 
445 /*
446  * Send ACK for 2xx response.
447  */
inv_send_ack(pjsip_inv_session * inv,pjsip_event * e)448 static pj_status_t inv_send_ack(pjsip_inv_session *inv, pjsip_event *e)
449 {
450     pjsip_rx_data *rdata;
451     pjsip_event ack_e;
452     pj_status_t status;
453 
454     if (e->type == PJSIP_EVENT_TSX_STATE)
455 	rdata = e->body.tsx_state.src.rdata;
456     else if (e->type == PJSIP_EVENT_RX_MSG)
457 	rdata = e->body.rx_msg.rdata;
458     else {
459 	pj_assert(!"Unsupported event type");
460 	return PJ_EBUG;
461     }
462 
463     /* Note that with https://trac.pjsip.org/repos/ticket/1725, this
464      * function can be called to send ACK for previous INVITE 200/OK
465      * retransmission
466      */
467 
468     PJ_LOG(5,(inv->obj_name, "Received %s, sending ACK",
469 	      pjsip_rx_data_get_info(rdata)));
470 
471     /* Check if we have cached ACK request and if we have sent it.
472      * Must not use the cached ACK if it's still marked as pending
473      * by transport (#1011).
474      */
475     if (inv->last_ack && rdata->msg_info.cseq->cseq == inv->last_ack_cseq &&
476 	inv->last_ack->tp_info.transport != NULL &&
477 	!inv->last_ack->is_pending)
478     {
479 	pjsip_tx_data_add_ref(inv->last_ack);
480 
481     } else if (mod_inv.cb.on_send_ack) {
482 	/* If application handles ACK transmission manually, just notify the
483 	 * callback
484 	 */
485 	PJ_LOG(5,(inv->obj_name, "Received %s, notifying application callback",
486 		  pjsip_rx_data_get_info(rdata)));
487 
488 	(*mod_inv.cb.on_send_ack)(inv, rdata);
489 	return PJ_SUCCESS;
490 
491     } else {
492 	status = pjsip_inv_create_ack(inv, rdata->msg_info.cseq->cseq,
493 				      &inv->last_ack);
494 	if (status != PJ_SUCCESS)
495 	    return status;
496     }
497 
498     PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack);
499 
500     /* Send ACK */
501     status = pjsip_dlg_send_request(inv->dlg, inv->last_ack, -1, NULL);
502     if (status != PJ_SUCCESS) {
503 	/* Better luck next time */
504 	pj_assert(!"Unable to send ACK!");
505 	return status;
506     }
507 
508 
509     /* Set state to CONFIRMED (if we're not in CONFIRMED yet).
510      * But don't set it to CONFIRMED if we're already DISCONNECTED
511      * (this may have been a late 200/OK response.
512      */
513     if (inv->state < PJSIP_INV_STATE_CONFIRMED) {
514 	inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e);
515     } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED && inv->last_ack) {
516         /* Avoid possible leaked tdata when invite session is already
517          * destroyed.
518          * https://github.com/pjsip/pjproject/pull/2432
519          */
520         pjsip_tx_data_dec_ref(inv->last_ack);
521         inv->last_ack = NULL;
522     }
523 
524     return PJ_SUCCESS;
525 }
526 
527 /*
528  * Module on_rx_request()
529  *
530  * This callback is called for these events:
531  *  - endpoint receives request which was unhandled by higher priority
532  *    modules (e.g. transaction layer, dialog layer).
533  *  - dialog distributes incoming request to its usages.
534  */
mod_inv_on_rx_request(pjsip_rx_data * rdata)535 static pj_bool_t mod_inv_on_rx_request(pjsip_rx_data *rdata)
536 {
537     pjsip_method *method;
538     pjsip_dialog *dlg;
539     pjsip_inv_session *inv;
540 
541     /* Only wants to receive request from a dialog. */
542     dlg = pjsip_rdata_get_dlg(rdata);
543     if (dlg == NULL)
544 	return PJ_FALSE;
545 
546     inv = (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id];
547 
548     /* Report to dialog that we handle INVITE, CANCEL, BYE, ACK.
549      * If we need to send response, it will be sent in the state
550      * handlers.
551      */
552     method = &rdata->msg_info.msg->line.req.method;
553 
554     if (method->id == PJSIP_INVITE_METHOD) {
555 	return PJ_TRUE;
556     }
557 
558     /* BYE and CANCEL must have existing invite session */
559     if (method->id == PJSIP_BYE_METHOD ||
560 	method->id == PJSIP_CANCEL_METHOD)
561     {
562 	if (inv == NULL)
563 	    return PJ_FALSE;
564 
565 	return PJ_TRUE;
566     }
567 
568     /* On receipt ACK request, when state is CONNECTING,
569      * move state to CONFIRMED.
570      */
571     if (method->id == PJSIP_ACK_METHOD && inv) {
572 
573 	/* Ignore if we don't have INVITE in progress */
574 	if (!inv->invite_tsx) {
575 	    return PJ_TRUE;
576 	}
577 
578 	/* Ignore ACK if pending INVITE transaction has not finished. */
579 	if (inv->invite_tsx->state < PJSIP_TSX_STATE_COMPLETED) {
580 	    return PJ_TRUE;
581 	}
582 
583 	/* Ignore ACK with different CSeq
584 	 * https://trac.pjsip.org/repos/ticket/1391
585 	 */
586 	if (rdata->msg_info.cseq->cseq != inv->invite_tsx->cseq) {
587 	    return PJ_TRUE;
588 	}
589 
590 	/* Terminate INVITE transaction, if it's still present. */
591 	if (inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED) {
592 	    /* Before we terminate INVITE transaction, process the SDP
593 	     * in the ACK request, if any.
594 	     * Only do this when invite state is not already disconnected
595 	     * (http://trac.pjsip.org/repos/ticket/640).
596 	     */
597 	    if (inv->state < PJSIP_INV_STATE_DISCONNECTED) {
598 		inv_check_sdp_in_incoming_msg(inv, inv->invite_tsx, rdata);
599 
600 		/* Check if local offer got no SDP answer and INVITE session
601 		 * is in CONFIRMED state.
602 		 */
603 		if (pjmedia_sdp_neg_get_state(inv->neg)==
604 		    PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
605 		    inv->state==PJSIP_INV_STATE_CONFIRMED)
606 		{
607 		    pjmedia_sdp_neg_cancel_offer(inv->neg);
608 		}
609 	    }
610 
611 	    /* Now we can terminate the INVITE transaction */
612 	    pj_assert(inv->invite_tsx->status_code >= 200);
613 	    pjsip_tsx_terminate(inv->invite_tsx,
614 				inv->invite_tsx->status_code);
615 	    inv->invite_tsx = NULL;
616 	    if (inv->last_answer) {
617 		    pjsip_tx_data_dec_ref(inv->last_answer);
618 		    inv->last_answer = NULL;
619 	    }
620 	}
621 
622 	/* On receipt of ACK, only set state to confirmed when state
623 	 * is CONNECTING (e.g. we don't want to set the state to confirmed
624 	 * when we receive ACK retransmission after sending non-2xx!)
625 	 */
626 	if (inv->state == PJSIP_INV_STATE_CONNECTING) {
627 	    pjsip_event event;
628 
629 	    PJSIP_EVENT_INIT_RX_MSG(event, rdata);
630 	    inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &event);
631 
632 	    /* Send pending BYE if any:
633 	     *   http://trac.pjsip.org/repos/ticket/1712
634 	     * Do this after setting the state to CONFIRMED, so that we
635 	     * have consistent CONFIRMED state between caller and callee.
636 	     */
637 	    if (inv->pending_bye)
638 		inv_perform_pending_bye(inv);
639 	}
640     }
641 
642     return PJ_FALSE;
643 }
644 
645 /* This function will process Session Timer headers in received
646  * 2xx or 422 response of INVITE/UPDATE request.
647  */
handle_timer_response(pjsip_inv_session * inv,const pjsip_rx_data * rdata,pj_bool_t end_sess_on_failure)648 static pj_status_t handle_timer_response(pjsip_inv_session *inv,
649 				         const pjsip_rx_data *rdata,
650 					 pj_bool_t end_sess_on_failure)
651 {
652     pjsip_status_code st_code;
653     pj_status_t status;
654 
655     status = pjsip_timer_process_resp(inv, rdata, &st_code);
656     if (status != PJ_SUCCESS && end_sess_on_failure) {
657 	pjsip_tx_data *tdata;
658 	pj_status_t status2;
659 
660 	status2 = pjsip_inv_end_session(inv, st_code, NULL, &tdata);
661 	if (tdata && status2 == PJ_SUCCESS)
662 	    pjsip_inv_send_msg(inv, tdata);
663     }
664 
665     return status;
666 }
667 
668 /*
669  * Module on_rx_response().
670  *
671  * This callback is called for these events:
672  *  - dialog distributes incoming 2xx response to INVITE (outside
673  *    transaction) to its usages.
674  *  - endpoint distributes strayed responses.
675  */
mod_inv_on_rx_response(pjsip_rx_data * rdata)676 static pj_bool_t mod_inv_on_rx_response(pjsip_rx_data *rdata)
677 {
678     pjsip_dialog *dlg;
679     pjsip_inv_session *inv;
680     pjsip_msg *msg = rdata->msg_info.msg;
681 
682     dlg = pjsip_rdata_get_dlg(rdata);
683 
684     /* Ignore responses outside dialog */
685     if (dlg == NULL)
686 	return PJ_FALSE;
687 
688     /* Ignore responses not belonging to invite session */
689     inv = pjsip_dlg_get_inv_session(dlg);
690     if (inv == NULL)
691 	return PJ_FALSE;
692 
693     /* This MAY be retransmission of 2xx response to INVITE.
694      * If it is, we need to send ACK.
695      */
696     if (msg->type == PJSIP_RESPONSE_MSG && msg->line.status.code/100==2 &&
697 	rdata->msg_info.cseq->method.id == PJSIP_INVITE_METHOD)
698     {
699 	/* The code inside "if" is called the second time 200/OK
700 	 * retransmission is received. Also handle the situation
701 	 * when we have another re-INVITE on going and 200/OK
702 	 * retransmission is received. See:
703 	 * https://trac.pjsip.org/repos/ticket/1725.
704 	 * Also send ACK for 200/OK of pending re-INVITE after call is
705 	 * disconnected (see https://trac.pjsip.org/repos/ticket/1755).
706 	 */
707 	if (inv->invite_tsx == NULL ||
708 	    inv->state == PJSIP_INV_STATE_DISCONNECTED ||
709 	    (inv->last_ack && inv->last_ack_cseq==rdata->msg_info.cseq->cseq))
710 	{
711 	    pjsip_event e;
712 
713 	    PJSIP_EVENT_INIT_RX_MSG(e, rdata);
714 	    inv_send_ack(inv, &e);
715 	    return PJ_TRUE;
716 	}
717     }
718 
719     /* No other processing needs to be done here. */
720     return PJ_FALSE;
721 }
722 
723 /*
724  * Module on_tsx_state()
725  *
726  * This callback is called by dialog framework for all transactions
727  * inside the dialog for all its dialog usages.
728  */
mod_inv_on_tsx_state(pjsip_transaction * tsx,pjsip_event * e)729 static void mod_inv_on_tsx_state(pjsip_transaction *tsx, pjsip_event *e)
730 {
731     pjsip_dialog *dlg;
732     pjsip_inv_session *inv;
733 
734     dlg = pjsip_tsx_get_dlg(tsx);
735     if (dlg == NULL)
736 	return;
737 
738     inv = pjsip_dlg_get_inv_session(dlg);
739     if (inv == NULL)
740 	return;
741 
742     /* Call state handler for the invite session. */
743     (*inv_state_handler[inv->state])(inv, e);
744 
745     /* Clear invite transaction when tsx is terminated.
746      * Necessary for app that wants to send a new re-INVITE request immediately
747      * after the transaction is terminated.
748      */
749     if (tsx->state==PJSIP_TSX_STATE_TERMINATED  && tsx == inv->invite_tsx) {
750 	inv->invite_tsx = NULL;
751 
752 	if (inv->last_answer) {
753 		pjsip_tx_data_dec_ref(inv->last_answer);
754 		inv->last_answer = NULL;
755 	}
756     }
757 
758     /* Call on_tsx_state. CANCEL request is a special case and has been
759      * reported earlier in inv_respond_incoming_cancel()
760      */
761     if (mod_inv.cb.on_tsx_state_changed && inv->notify &&
762         !(tsx->method.id==PJSIP_CANCEL_METHOD &&
763           e->body.tsx_state.type==PJSIP_EVENT_RX_MSG))
764     {
765 	(*mod_inv.cb.on_tsx_state_changed)(inv, tsx, e);
766     }
767 
768     /* Clear invite transaction when tsx is confirmed.
769      * Previously we set invite_tsx to NULL only when transaction has
770      * terminated, but this didn't work when ACK has the same Via branch
771      * value as the INVITE (see http://www.pjsip.org/trac/ticket/113)
772      */
773     if (tsx->state>=PJSIP_TSX_STATE_CONFIRMED && tsx == inv->invite_tsx) {
774 	inv->invite_tsx = NULL;
775 
776 	if (inv->last_answer) {
777 		pjsip_tx_data_dec_ref(inv->last_answer);
778 		inv->last_answer = NULL;
779 	}
780     }
781 }
782 
783 /*
784  * Check if tx_data has sdp.
785  */
tx_data_has_sdp(const pjsip_tx_data * tdata)786 static pj_bool_t tx_data_has_sdp(const pjsip_tx_data *tdata)
787 {
788     pjsip_msg_body *body = tdata->msg->body;
789     pjsip_media_type app_sdp;
790 
791     PJ_ASSERT_RETURN(tdata, PJ_FALSE);
792 
793     pjsip_media_type_init2(&app_sdp, "application", "sdp");
794 
795     if (body &&
796 	pj_stricmp(&body->content_type.type, &app_sdp.type)==0 &&
797 	pj_stricmp(&body->content_type.subtype, &app_sdp.subtype)==0)
798     {
799 	return PJ_TRUE;
800 
801     } else if (body &&
802 	       pj_stricmp2(&body->content_type.type, "multipart") &&
803 	       (pj_stricmp2(&body->content_type.subtype, "mixed")==0 ||
804 	        pj_stricmp2(&body->content_type.subtype, "alternative")==0))
805     {
806 	pjsip_multipart_part *part;
807 
808 	part = pjsip_multipart_find_part(body, &app_sdp, NULL);
809 	if (part) {
810 	    return PJ_TRUE;
811 	}
812     }
813 
814     return PJ_FALSE;
815 }
816 
817 
818 /*
819  * Initialize the invite module.
820  */
pjsip_inv_usage_init(pjsip_endpoint * endpt,const pjsip_inv_callback * cb)821 PJ_DEF(pj_status_t) pjsip_inv_usage_init( pjsip_endpoint *endpt,
822 					  const pjsip_inv_callback *cb)
823 {
824     pj_status_t status;
825 
826     /* Check arguments. */
827     PJ_ASSERT_RETURN(endpt && cb, PJ_EINVAL);
828 
829     /* Some callbacks are mandatory */
830     PJ_ASSERT_RETURN(cb->on_state_changed, PJ_EINVAL);
831 
832     /* Check if module already registered. */
833     PJ_ASSERT_RETURN(mod_inv.mod.id == -1, PJ_EINVALIDOP);
834 
835     /* Copy param. */
836     pj_memcpy(&mod_inv.cb, cb, sizeof(pjsip_inv_callback));
837 
838     mod_inv.endpt = endpt;
839 
840     /* Register the module. */
841     status = pjsip_endpt_register_module(endpt, &mod_inv.mod);
842     if (status != PJ_SUCCESS)
843 	return status;
844 
845     return PJ_SUCCESS;
846 }
847 
848 /*
849  * Get the instance of invite module.
850  */
pjsip_inv_usage_instance(void)851 PJ_DEF(pjsip_module*) pjsip_inv_usage_instance(void)
852 {
853     return &mod_inv.mod;
854 }
855 
856 
857 
858 /*
859  * Return the invite session for the specified dialog.
860  */
pjsip_dlg_get_inv_session(pjsip_dialog * dlg)861 PJ_DEF(pjsip_inv_session*) pjsip_dlg_get_inv_session(pjsip_dialog *dlg)
862 {
863     return (pjsip_inv_session*) dlg->mod_data[mod_inv.mod.id];
864 }
865 
866 
867 /*
868  * Get INVITE state name.
869  */
pjsip_inv_state_name(pjsip_inv_state state)870 PJ_DEF(const char *) pjsip_inv_state_name(pjsip_inv_state state)
871 {
872     PJ_ASSERT_RETURN(state >= PJSIP_INV_STATE_NULL &&
873 		     state <= PJSIP_INV_STATE_DISCONNECTED,
874 		     "??");
875 
876     return inv_state_names[state];
877 }
878 
879 /*
880  * Create UAC invite session.
881  */
pjsip_inv_create_uac(pjsip_dialog * dlg,const pjmedia_sdp_session * local_sdp,unsigned options,pjsip_inv_session ** p_inv)882 PJ_DEF(pj_status_t) pjsip_inv_create_uac( pjsip_dialog *dlg,
883 					  const pjmedia_sdp_session *local_sdp,
884 					  unsigned options,
885 					  pjsip_inv_session **p_inv)
886 {
887     pjsip_inv_session *inv;
888     pj_status_t status;
889 
890     /* Verify arguments. */
891     PJ_ASSERT_RETURN(dlg && p_inv, PJ_EINVAL);
892 
893     /* Must lock dialog first */
894     pjsip_dlg_inc_lock(dlg);
895 
896     /* Normalize options */
897     if (options & PJSIP_INV_REQUIRE_100REL)
898 	options |= PJSIP_INV_SUPPORT_100REL;
899     if (options & PJSIP_INV_REQUIRE_TIMER)
900 	options |= PJSIP_INV_SUPPORT_TIMER;
901     if (options & PJSIP_INV_REQUIRE_TRICKLE_ICE)
902 	options |= PJSIP_INV_SUPPORT_TRICKLE_ICE;
903 
904     /* Create the session */
905     inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session);
906     pj_assert(inv != NULL);
907 
908     status = pj_atomic_create(dlg->pool, 0, &inv->ref_cnt);
909     if (status != PJ_SUCCESS) {
910 	pjsip_dlg_dec_lock(dlg);
911 	return status;
912     }
913 
914     inv->pool = dlg->pool;
915     inv->role = PJSIP_ROLE_UAC;
916     inv->state = PJSIP_INV_STATE_NULL;
917     inv->dlg = dlg;
918     inv->options = options;
919     inv->notify = PJ_TRUE;
920     inv->cause = (pjsip_status_code) 0;
921 
922     /* Create flip-flop pool (see ticket #877) */
923     /* (using inv->obj_name as temporary variable for pool names */
924     pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool);
925     inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
926 					     POOL_INIT_SIZE, POOL_INC_SIZE);
927     inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
928 					       POOL_INIT_SIZE, POOL_INC_SIZE);
929 
930     /* Object name will use the same dialog pointer. */
931     pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg);
932 
933     /* Create negotiator if local_sdp is specified. */
934     if (local_sdp) {
935 	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool,
936 						      local_sdp, &inv->neg);
937 	if (status != PJ_SUCCESS) {
938 	    pjsip_dlg_dec_lock(dlg);
939 	    return status;
940 	}
941     }
942 
943     /* Register invite as dialog usage. */
944     status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv);
945     if (status != PJ_SUCCESS) {
946 	pjsip_dlg_dec_lock(dlg);
947 	return status;
948     }
949 
950     /* Increment dialog session */
951     pjsip_dlg_inc_session(dlg, &mod_inv.mod);
952 
953     /* Create 100rel handler */
954     pjsip_100rel_attach(inv);
955 
956     /* Done */
957     pjsip_inv_add_ref(inv);
958     *p_inv = inv;
959 
960     pjsip_dlg_dec_lock(dlg);
961 
962     PJ_LOG(5,(inv->obj_name, "UAC invite session created for dialog %s",
963 	      dlg->obj_name));
964 
965     return PJ_SUCCESS;
966 }
967 
968 
pjsip_rdata_get_sdp_info(pjsip_rx_data * rdata)969 PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info(pjsip_rx_data *rdata)
970 {
971     return pjsip_rdata_get_sdp_info2(rdata, NULL);
972 }
973 
974 
pjsip_rdata_get_sdp_info2(pjsip_rx_data * rdata,const pjsip_media_type * med_type)975 PJ_DEF(pjsip_rdata_sdp_info*) pjsip_rdata_get_sdp_info2(
976 					    pjsip_rx_data *rdata,
977 					    const pjsip_media_type *med_type)
978 {
979     pjsip_rdata_sdp_info *sdp_info;
980     pjsip_msg_body *body = rdata->msg_info.msg->body;
981     pjsip_ctype_hdr *ctype_hdr = rdata->msg_info.ctype;
982     pjsip_media_type app_sdp;
983 
984     sdp_info = (pjsip_rdata_sdp_info*)
985 	       rdata->endpt_info.mod_data[mod_inv.mod.id];
986     if (sdp_info)
987 	return sdp_info;
988 
989     sdp_info = PJ_POOL_ZALLOC_T(rdata->tp_info.pool,
990 				pjsip_rdata_sdp_info);
991     PJ_ASSERT_RETURN(mod_inv.mod.id >= 0, sdp_info);
992     rdata->endpt_info.mod_data[mod_inv.mod.id] = sdp_info;
993 
994     if (!med_type) {
995 	pjsip_media_type_init2(&app_sdp, "application", "sdp");
996     } else {
997 	pj_memcpy(&app_sdp, med_type, sizeof(app_sdp));
998     }
999 
1000     if (body && ctype_hdr &&
1001 	pj_stricmp(&ctype_hdr->media.type, &app_sdp.type)==0 &&
1002 	pj_stricmp(&ctype_hdr->media.subtype, &app_sdp.subtype)==0)
1003     {
1004 	sdp_info->body.ptr = (char*)body->data;
1005 	sdp_info->body.slen = body->len;
1006     } else if  (body && ctype_hdr &&
1007 	    	pj_stricmp2(&ctype_hdr->media.type, "multipart")==0 &&
1008 	    	(pj_stricmp2(&ctype_hdr->media.subtype, "mixed")==0 ||
1009 	    	 pj_stricmp2(&ctype_hdr->media.subtype, "alternative")==0))
1010     {
1011 	pjsip_multipart_part *part;
1012 
1013 	part = pjsip_multipart_find_part(body, &app_sdp, NULL);
1014 	if (part) {
1015 	    sdp_info->body.ptr = (char*)part->body->data;
1016 	    sdp_info->body.slen = part->body->len;
1017 	}
1018     }
1019 
1020     if (sdp_info->body.ptr) {
1021 	pj_status_t status;
1022 	status = pjmedia_sdp_parse(rdata->tp_info.pool,
1023 				   sdp_info->body.ptr,
1024 				   sdp_info->body.slen,
1025 				   &sdp_info->sdp);
1026 	if (status == PJ_SUCCESS)
1027 	    status = pjmedia_sdp_validate2(sdp_info->sdp, PJ_FALSE);
1028 
1029 	if (status != PJ_SUCCESS) {
1030 	    sdp_info->sdp = NULL;
1031 	    PJ_PERROR(1,(THIS_FILE, status,
1032 			 "Error parsing/validating SDP body"));
1033 	}
1034 
1035 	sdp_info->sdp_err = status;
1036     }
1037 
1038     return sdp_info;
1039 }
1040 
1041 
1042 /*
1043  * Verify incoming INVITE request.
1044  */
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)1045 PJ_DEF(pj_status_t) pjsip_inv_verify_request3(pjsip_rx_data *rdata,
1046                                               pj_pool_t *tmp_pool,
1047 					      unsigned *options,
1048 					      const pjmedia_sdp_session *r_sdp,
1049 					      const pjmedia_sdp_session *l_sdp,
1050 					      pjsip_dialog *dlg,
1051 					      pjsip_endpoint *endpt,
1052 					      pjsip_tx_data **p_tdata)
1053 {
1054     pjsip_msg *msg = NULL;
1055     pjsip_allow_hdr *allow = NULL;
1056     pjsip_supported_hdr *sup_hdr = NULL;
1057     pjsip_require_hdr *req_hdr = NULL;
1058     pjsip_contact_hdr *c_hdr = NULL;
1059     int code = 200;
1060     unsigned rem_option = 0;
1061     pj_status_t status = PJ_SUCCESS;
1062     pjsip_hdr res_hdr_list;
1063     pjsip_rdata_sdp_info *sdp_info;
1064 
1065     /* Init return arguments. */
1066     if (p_tdata) *p_tdata = NULL;
1067 
1068     /* Verify arguments. */
1069     PJ_ASSERT_RETURN(tmp_pool != NULL && options != NULL, PJ_EINVAL);
1070 
1071     /* Normalize options */
1072     if (*options & PJSIP_INV_REQUIRE_100REL)
1073 	*options |= PJSIP_INV_SUPPORT_100REL;
1074     if (*options & PJSIP_INV_REQUIRE_TIMER)
1075 	*options |= PJSIP_INV_SUPPORT_TIMER;
1076     if (*options & PJSIP_INV_REQUIRE_ICE)
1077 	*options |= PJSIP_INV_SUPPORT_ICE;
1078     if (*options & PJSIP_INV_REQUIRE_TRICKLE_ICE)
1079 	*options |= PJSIP_INV_SUPPORT_TRICKLE_ICE;
1080 
1081     if (rdata) {
1082         /* Get the message in rdata */
1083         msg = rdata->msg_info.msg;
1084 
1085         /* Must be INVITE request. */
1086         PJ_ASSERT_RETURN(msg && msg->type == PJSIP_REQUEST_MSG &&
1087 		         msg->line.req.method.id == PJSIP_INVITE_METHOD,
1088 		         PJ_EINVAL);
1089     }
1090 
1091     /* If tdata is specified, then either dlg or endpt must be specified */
1092     PJ_ASSERT_RETURN((!p_tdata) || (endpt || dlg), PJ_EINVAL);
1093 
1094     /* Get the endpoint */
1095     endpt = endpt ? endpt : dlg->endpt;
1096 
1097     /* Init response header list */
1098     pj_list_init(&res_hdr_list);
1099 
1100     /* Check the Contact header */
1101     if (msg) {
1102         c_hdr = (pjsip_contact_hdr*)
1103 	        pjsip_msg_find_hdr(msg, PJSIP_H_CONTACT, NULL);
1104     }
1105     if (msg && (!c_hdr || !c_hdr->uri)) {
1106         /* Missing Contact header or Contact contains "*" */
1107 	pjsip_warning_hdr *w;
1108 	pj_str_t warn_text;
1109 
1110 	warn_text = pj_str("Bad/missing Contact header");
1111 	w = pjsip_warning_hdr_create(tmp_pool, 399,
1112 				     pjsip_endpt_name(endpt),
1113 				     &warn_text);
1114 	if (w) {
1115 	    pj_list_push_back(&res_hdr_list, w);
1116 	}
1117 
1118 	code = PJSIP_SC_BAD_REQUEST;
1119 	status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
1120 	goto on_return;
1121     }
1122 
1123     /* Ticket #1735: Check Contact/Record-Route header in a secure dialog. */
1124     if (pjsip_cfg()->endpt.disable_secure_dlg_check == PJ_FALSE &&
1125 	msg && PJSIP_URI_SCHEME_IS_SIPS(msg->line.req.uri))
1126     {
1127 	/* Check Contact header */
1128 	if (!PJSIP_URI_SCHEME_IS_SIPS(c_hdr->uri))
1129 	    status = PJSIP_ESESSIONINSECURE;
1130 
1131 	/* Check top Record-Route header */
1132 	if (status == PJ_SUCCESS) {
1133 	    pjsip_rr_hdr *r = (pjsip_rr_hdr*)
1134 			      pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE,
1135 						 NULL);
1136 	    if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) {
1137 		/* Not "sips", check if it is "sip" and has param
1138 		 * "transport=tls".
1139 		 */
1140 		if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) {
1141 		    pjsip_sip_uri *sip_uri = (pjsip_sip_uri*)
1142 				     pjsip_uri_get_uri(r->name_addr.uri);
1143 		    if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0)
1144 			status = PJSIP_ESESSIONINSECURE;
1145 		} else {
1146 		    /* Not "sips" nor "sip", treat it as insecure? */
1147 		    status = PJSIP_ESESSIONINSECURE;
1148 		}
1149 	    }
1150 	}
1151 
1152 	if (status != PJ_SUCCESS) {
1153 	    pjsip_warning_hdr *w;
1154 	    pj_str_t warn_text = pj_str("SIPS Required");
1155 	    w = pjsip_warning_hdr_create(tmp_pool, 381,
1156 					 pjsip_endpt_name(endpt),
1157 					 &warn_text);
1158 	    if (w) {
1159 		pj_list_push_back(&res_hdr_list, w);
1160 	    }
1161 	    code = PJSIP_SC_TEMPORARILY_UNAVAILABLE;
1162 	    goto on_return;
1163 	}
1164     }
1165 
1166     /* Check the request body, see if it's something that we support,
1167      * only when the body hasn't been parsed before.
1168      */
1169     if (r_sdp == NULL && rdata) {
1170 	sdp_info = pjsip_rdata_get_sdp_info(rdata);
1171     } else {
1172 	sdp_info = NULL;
1173     }
1174 
1175     if (r_sdp==NULL && msg && msg->body) {
1176 
1177 	/* Check if body really contains SDP. */
1178 	if (sdp_info->body.ptr == NULL && !PJSIP_INV_ACCEPT_UNKNOWN_BODY) {
1179 	    /* Couldn't find "application/sdp" */
1180 	    code = PJSIP_SC_UNSUPPORTED_MEDIA_TYPE;
1181 	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
1182 
1183 	    if (p_tdata) {
1184 		/* Add Accept header to response */
1185 		pjsip_accept_hdr *acc;
1186 
1187 		acc = pjsip_accept_hdr_create(tmp_pool);
1188 		PJ_ASSERT_RETURN(acc, PJ_ENOMEM);
1189 		acc->values[acc->count++] = pj_str("application/sdp");
1190 		pj_list_push_back(&res_hdr_list, acc);
1191 	    }
1192 
1193 	    goto on_return;
1194 	}
1195 
1196 	if (sdp_info->sdp_err != PJ_SUCCESS) {
1197 	    /* Unparseable or invalid SDP */
1198 	    code = PJSIP_SC_BAD_REQUEST;
1199 
1200 	    if (p_tdata) {
1201 		/* Add Warning header. */
1202 		pjsip_warning_hdr *w;
1203 
1204 		w = pjsip_warning_hdr_create_from_status(tmp_pool,
1205 							 pjsip_endpt_name(endpt),
1206 							 sdp_info->sdp_err);
1207 		PJ_ASSERT_RETURN(w, PJ_ENOMEM);
1208 
1209 		pj_list_push_back(&res_hdr_list, w);
1210 	    }
1211 
1212 	    goto on_return;
1213 	}
1214 
1215 	r_sdp = sdp_info->sdp;
1216     }
1217 
1218     if (r_sdp) {
1219 	/* Negotiate with local SDP */
1220 	if (l_sdp) {
1221 	    pjmedia_sdp_neg *neg;
1222 
1223 	    /* Local SDP must be valid! */
1224 	    status = pjmedia_sdp_validate(l_sdp);
1225 	    if (status != PJ_SUCCESS) {
1226 		pj_assert(!"Invalid local SDP");
1227 		code = PJSIP_SC_INTERNAL_SERVER_ERROR;
1228 		goto on_return;
1229 	    }
1230 
1231 	    /* Create SDP negotiator */
1232 	    status = pjmedia_sdp_neg_create_w_remote_offer(
1233 			    tmp_pool, l_sdp, r_sdp, &neg);
1234 	    if (status != PJ_SUCCESS) {
1235 		pj_assert(!"Failed creating SDP negotiator");
1236 		code = PJSIP_SC_INTERNAL_SERVER_ERROR;
1237 		goto on_return;
1238 	    }
1239 
1240 	    /* Negotiate SDP */
1241 	    status = pjmedia_sdp_neg_negotiate(tmp_pool, neg, 0);
1242 	    if (status != PJ_SUCCESS) {
1243 
1244 		/* Incompatible media */
1245 		code = PJSIP_SC_NOT_ACCEPTABLE_HERE;
1246 
1247 		if (p_tdata) {
1248 		    pjsip_accept_hdr *acc;
1249 		    pjsip_warning_hdr *w;
1250 
1251 		    /* Add Warning header. */
1252 		    w = pjsip_warning_hdr_create_from_status(
1253 					    tmp_pool,
1254 					    pjsip_endpt_name(endpt), status);
1255 		    PJ_ASSERT_RETURN(w, PJ_ENOMEM);
1256 
1257 		    pj_list_push_back(&res_hdr_list, w);
1258 
1259 		    /* Add Accept header to response */
1260 		    acc = pjsip_accept_hdr_create(tmp_pool);
1261 		    PJ_ASSERT_RETURN(acc, PJ_ENOMEM);
1262 		    acc->values[acc->count++] = pj_str("application/sdp");
1263 		    pj_list_push_back(&res_hdr_list, acc);
1264 
1265 		}
1266 
1267 		goto on_return;
1268 	    }
1269 	}
1270     }
1271 
1272     /* Check supported methods, see if peer supports UPDATE.
1273      * We just assume that peer supports standard INVITE, ACK, CANCEL, and BYE
1274      * implicitly by sending this INVITE.
1275      */
1276     if (msg) {
1277         allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg, PJSIP_H_ALLOW,
1278                                                       NULL);
1279     }
1280     if (allow) {
1281 	unsigned i;
1282 	const pj_str_t STR_UPDATE = { "UPDATE", 6 };
1283 
1284 	for (i=0; i<allow->count; ++i) {
1285 	    if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0)
1286 		break;
1287 	}
1288 
1289 	if (i != allow->count) {
1290 	    /* UPDATE is present in Allow */
1291 	    *options |= PJSIP_INV_SUPPORT_UPDATE;
1292 	}
1293 
1294     }
1295 
1296     /* Check Supported header */
1297     if (msg) {
1298         sup_hdr = (pjsip_supported_hdr*)
1299 	          pjsip_msg_find_hdr(msg, PJSIP_H_SUPPORTED, NULL);
1300     }
1301     if (sup_hdr) {
1302 	unsigned i;
1303 	const pj_str_t STR_100REL = { "100rel", 6};
1304 	const pj_str_t STR_TIMER = { "timer", 5};
1305 	const pj_str_t STR_ICE = { "ice", 3 };
1306 	const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 };
1307 
1308 	for (i=0; i<sup_hdr->count; ++i) {
1309 	    if (pj_stricmp(&sup_hdr->values[i], &STR_100REL)==0)
1310 		rem_option |= PJSIP_INV_SUPPORT_100REL;
1311 	    else if (pj_stricmp(&sup_hdr->values[i], &STR_TIMER)==0)
1312 		rem_option |= PJSIP_INV_SUPPORT_TIMER;
1313 	    else if (pj_stricmp(&sup_hdr->values[i], &STR_ICE)==0)
1314 		rem_option |= PJSIP_INV_SUPPORT_ICE;
1315 	    else if (pj_stricmp(&sup_hdr->values[i], &STR_TRICKLE_ICE)==0)
1316 		rem_option |= PJSIP_INV_SUPPORT_TRICKLE_ICE;
1317 	}
1318     }
1319 
1320     /* Check Require header */
1321     if (msg) {
1322         req_hdr = (pjsip_require_hdr*)
1323 	          pjsip_msg_find_hdr(msg, PJSIP_H_REQUIRE, NULL);
1324     }
1325     if (req_hdr) {
1326 	unsigned i;
1327 	const pj_str_t STR_100REL = { "100rel", 6};
1328 	const pj_str_t STR_REPLACES = { "replaces", 8 };
1329 	const pj_str_t STR_TIMER = { "timer", 5 };
1330 	const pj_str_t STR_ICE = { "ice", 3 };
1331 	const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 };
1332 	unsigned unsupp_cnt = 0;
1333 	pj_str_t unsupp_tags[PJSIP_GENERIC_ARRAY_MAX_COUNT];
1334 
1335 	for (i=0; i<req_hdr->count; ++i) {
1336 	    if ((*options & PJSIP_INV_SUPPORT_100REL) &&
1337 		pj_stricmp(&req_hdr->values[i], &STR_100REL)==0)
1338 	    {
1339 		rem_option |= PJSIP_INV_REQUIRE_100REL;
1340 
1341 	    } else if ((*options & PJSIP_INV_SUPPORT_TIMER) &&
1342 		pj_stricmp(&req_hdr->values[i], &STR_TIMER)==0)
1343 	    {
1344 		rem_option |= PJSIP_INV_REQUIRE_TIMER;
1345 
1346 	    } else if (pj_stricmp(&req_hdr->values[i], &STR_REPLACES)==0) {
1347 		pj_bool_t supp;
1348 
1349 		supp = pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED,
1350 						  NULL, &STR_REPLACES);
1351 		if (!supp)
1352 		    unsupp_tags[unsupp_cnt++] = req_hdr->values[i];
1353 	    } else if ((*options & PJSIP_INV_SUPPORT_ICE) &&
1354 		pj_stricmp(&req_hdr->values[i], &STR_ICE)==0)
1355 	    {
1356 		rem_option |= PJSIP_INV_REQUIRE_ICE;
1357 
1358 	    } else if ((*options & PJSIP_INV_SUPPORT_TRICKLE_ICE) &&
1359 		pj_stricmp(&req_hdr->values[i], &STR_TRICKLE_ICE)==0)
1360 	    {
1361 		rem_option |= PJSIP_INV_REQUIRE_TRICKLE_ICE;
1362 
1363 	    } else if (!pjsip_endpt_has_capability(endpt, PJSIP_H_SUPPORTED,
1364 						   NULL, &req_hdr->values[i]))
1365 	    {
1366 		/* Unknown/unsupported extension tag!  */
1367 		unsupp_tags[unsupp_cnt++] = req_hdr->values[i];
1368 	    }
1369 	}
1370 
1371 	/* Check if there are required tags that we don't support */
1372 	if (unsupp_cnt) {
1373 
1374 	    code = PJSIP_SC_BAD_EXTENSION;
1375 	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
1376 
1377 	    if (p_tdata) {
1378 		pjsip_unsupported_hdr *unsupp_hdr;
1379 		const pjsip_hdr *h;
1380 
1381 		/* Add Unsupported header. */
1382 		unsupp_hdr = pjsip_unsupported_hdr_create(tmp_pool);
1383 		PJ_ASSERT_RETURN(unsupp_hdr != NULL, PJ_ENOMEM);
1384 
1385 		unsupp_hdr->count = unsupp_cnt;
1386 		for (i=0; i<unsupp_cnt; ++i)
1387 		    unsupp_hdr->values[i] = unsupp_tags[i];
1388 
1389 		pj_list_push_back(&res_hdr_list, unsupp_hdr);
1390 
1391 		/* Add Supported header. */
1392 		h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED,
1393 					       NULL);
1394 		pj_assert(h);
1395 		if (h) {
1396 		    sup_hdr = (pjsip_supported_hdr*)
1397 			      pjsip_hdr_clone(tmp_pool, h);
1398 		    pj_list_push_back(&res_hdr_list, sup_hdr);
1399 		}
1400 	    }
1401 
1402 	    goto on_return;
1403 	}
1404     }
1405 
1406     /* Check if there are local requirements that are not supported
1407      * by peer.
1408      */
1409     if ( msg && (((*options & PJSIP_INV_REQUIRE_100REL)!=0 &&
1410                   (rem_option & PJSIP_INV_SUPPORT_100REL)==0) ||
1411                  ((*options & PJSIP_INV_REQUIRE_TIMER)!=0 &&
1412                   (rem_option & PJSIP_INV_SUPPORT_TIMER)==0) ||
1413                  ((*options & PJSIP_INV_REQUIRE_TRICKLE_ICE)!=0 &&
1414                   (rem_option & PJSIP_INV_SUPPORT_TRICKLE_ICE)==0)))
1415     {
1416 	code = PJSIP_SC_EXTENSION_REQUIRED;
1417 	status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
1418 
1419 	if (p_tdata) {
1420 	    const pjsip_hdr *h;
1421 
1422 	    /* Add Require header. */
1423 	    req_hdr = pjsip_require_hdr_create(tmp_pool);
1424 	    PJ_ASSERT_RETURN(req_hdr != NULL, PJ_ENOMEM);
1425 
1426 	    if (*options & PJSIP_INV_REQUIRE_100REL)
1427 		req_hdr->values[req_hdr->count++] = pj_str("100rel");
1428 	    if (*options & PJSIP_INV_REQUIRE_TIMER)
1429 		req_hdr->values[req_hdr->count++] = pj_str("timer");
1430 	    if (*options & PJSIP_INV_REQUIRE_TRICKLE_ICE)
1431 		req_hdr->values[req_hdr->count++] = pj_str("trickle-ice");
1432 
1433 	    pj_list_push_back(&res_hdr_list, req_hdr);
1434 
1435 	    /* Add Supported header. */
1436 	    h = pjsip_endpt_get_capability(endpt, PJSIP_H_SUPPORTED,
1437 					   NULL);
1438 	    pj_assert(h);
1439 	    if (h) {
1440 		sup_hdr = (pjsip_supported_hdr*)
1441 			  pjsip_hdr_clone(tmp_pool, h);
1442 		pj_list_push_back(&res_hdr_list, sup_hdr);
1443 	    }
1444 
1445 	}
1446 
1447 	goto on_return;
1448     }
1449 
1450     /* If remote Require something that we support, make us Require
1451      * that feature too.
1452      */
1453     if (rem_option & PJSIP_INV_REQUIRE_100REL) {
1454 	    pj_assert(*options & PJSIP_INV_SUPPORT_100REL);
1455 	    *options |= PJSIP_INV_REQUIRE_100REL;
1456     }
1457     if (rem_option & PJSIP_INV_REQUIRE_TIMER) {
1458 	    pj_assert(*options & PJSIP_INV_SUPPORT_TIMER);
1459 	    *options |= PJSIP_INV_REQUIRE_TIMER;
1460     }
1461     if (rem_option & PJSIP_INV_REQUIRE_TRICKLE_ICE) {
1462 	    pj_assert(*options & PJSIP_INV_SUPPORT_TRICKLE_ICE);
1463 	    *options |= PJSIP_INV_REQUIRE_TRICKLE_ICE;
1464     }
1465 
1466 on_return:
1467 
1468     /* Create response if necessary */
1469     if (code != 200 && p_tdata) {
1470 	pjsip_tx_data *tdata;
1471 	const pjsip_hdr *h;
1472 
1473         if (!rdata) {
1474             return PJSIP_ERRNO_FROM_SIP_STATUS(code);
1475         }
1476 
1477 	if (dlg) {
1478 	    status = pjsip_dlg_create_response(dlg, rdata, code, NULL,
1479 					       &tdata);
1480 	} else {
1481 	    status = pjsip_endpt_create_response(endpt, rdata, code, NULL,
1482 						 &tdata);
1483 	}
1484 
1485 	if (status != PJ_SUCCESS)
1486 	    return status;
1487 
1488 	/* Add response headers. */
1489 	h = res_hdr_list.next;
1490 	while (h != &res_hdr_list) {
1491 	    pjsip_hdr *cloned;
1492 
1493 	    cloned = (pjsip_hdr*) pjsip_hdr_clone(tdata->pool, h);
1494 	    PJ_ASSERT_RETURN(cloned, PJ_ENOMEM);
1495 
1496 	    pjsip_msg_add_hdr(tdata->msg, cloned);
1497 
1498 	    h = h->next;
1499 	}
1500 
1501 	*p_tdata = tdata;
1502 
1503 	/* Can not return PJ_SUCCESS when response message is produced.
1504 	 * Ref: PROTOS test ~#2490
1505 	 */
1506 	if (status == PJ_SUCCESS)
1507 	    status = PJSIP_ERRNO_FROM_SIP_STATUS(code);
1508 
1509     }
1510 
1511     return status;
1512 }
1513 
1514 
1515 /*
1516  * Verify incoming INVITE request.
1517  */
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)1518 PJ_DEF(pj_status_t) pjsip_inv_verify_request2(pjsip_rx_data *rdata,
1519 					      unsigned *options,
1520 					      const pjmedia_sdp_session *r_sdp,
1521 					      const pjmedia_sdp_session *l_sdp,
1522 					      pjsip_dialog *dlg,
1523 					      pjsip_endpoint *endpt,
1524 					      pjsip_tx_data **p_tdata)
1525 {
1526     return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool,
1527                                      options, r_sdp, l_sdp, dlg,
1528 				     endpt, p_tdata);
1529 }
1530 
1531 
1532 /*
1533  * Verify incoming INVITE request.
1534  */
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)1535 PJ_DEF(pj_status_t) pjsip_inv_verify_request( pjsip_rx_data *rdata,
1536 					      unsigned *options,
1537 					      const pjmedia_sdp_session *l_sdp,
1538 					      pjsip_dialog *dlg,
1539 					      pjsip_endpoint *endpt,
1540 					      pjsip_tx_data **p_tdata)
1541 {
1542     return pjsip_inv_verify_request3(rdata, rdata->tp_info.pool,
1543                                      options, NULL, l_sdp, dlg,
1544 				     endpt, p_tdata);
1545 }
1546 
1547 /*
1548  * Create UAS invite session.
1549  */
pjsip_inv_create_uas(pjsip_dialog * dlg,pjsip_rx_data * rdata,const pjmedia_sdp_session * local_sdp,unsigned options,pjsip_inv_session ** p_inv)1550 PJ_DEF(pj_status_t) pjsip_inv_create_uas( pjsip_dialog *dlg,
1551 					  pjsip_rx_data *rdata,
1552 					  const pjmedia_sdp_session *local_sdp,
1553 					  unsigned options,
1554 					  pjsip_inv_session **p_inv)
1555 {
1556     pjsip_inv_session *inv;
1557     struct tsx_inv_data *tsx_inv_data;
1558     pjsip_msg *msg;
1559     pjsip_rdata_sdp_info *sdp_info;
1560     pj_status_t status;
1561 
1562     /* Verify arguments. */
1563     PJ_ASSERT_RETURN(dlg && rdata && p_inv, PJ_EINVAL);
1564 
1565     /* Dialog MUST have been initialised. */
1566     PJ_ASSERT_RETURN(pjsip_rdata_get_tsx(rdata) != NULL, PJ_EINVALIDOP);
1567 
1568     msg = rdata->msg_info.msg;
1569 
1570     /* rdata MUST contain INVITE request */
1571     PJ_ASSERT_RETURN(msg->type == PJSIP_REQUEST_MSG &&
1572 		     msg->line.req.method.id == PJSIP_INVITE_METHOD,
1573 		     PJ_EINVALIDOP);
1574 
1575     /* Lock dialog */
1576     pjsip_dlg_inc_lock(dlg);
1577 
1578     /* Normalize options */
1579     if (options & PJSIP_INV_REQUIRE_100REL)
1580 	options |= PJSIP_INV_SUPPORT_100REL;
1581     if (options & PJSIP_INV_REQUIRE_TIMER)
1582 	options |= PJSIP_INV_SUPPORT_TIMER;
1583 
1584     /* Create the session */
1585     inv = PJ_POOL_ZALLOC_T(dlg->pool, pjsip_inv_session);
1586     pj_assert(inv != NULL);
1587 
1588     status = pj_atomic_create(dlg->pool, 0, &inv->ref_cnt);
1589     if (status != PJ_SUCCESS) {
1590 	pjsip_dlg_dec_lock(dlg);
1591 	return status;
1592     }
1593 
1594     inv->pool = dlg->pool;
1595     inv->role = PJSIP_ROLE_UAS;
1596     inv->state = PJSIP_INV_STATE_NULL;
1597     inv->dlg = dlg;
1598     inv->options = options;
1599     inv->notify = PJ_TRUE;
1600     inv->cause = (pjsip_status_code) 0;
1601 
1602     /* Create flip-flop pool (see ticket #877) */
1603     /* (using inv->obj_name as temporary variable for pool names */
1604     pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg->pool);
1605     inv->pool_prov = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
1606 					     POOL_INIT_SIZE, POOL_INC_SIZE);
1607     inv->pool_active = pjsip_endpt_create_pool(dlg->endpt, inv->obj_name,
1608 					       POOL_INIT_SIZE, POOL_INC_SIZE);
1609 
1610     /* Object name will use the same dialog pointer. */
1611     pj_ansi_snprintf(inv->obj_name, PJ_MAX_OBJ_NAME, "inv%p", dlg);
1612 
1613     /* Process SDP in message body, if present. */
1614     sdp_info = pjsip_rdata_get_sdp_info(rdata);
1615     if (sdp_info->sdp_err) {
1616 	pjsip_dlg_dec_lock(dlg);
1617 	return sdp_info->sdp_err;
1618     }
1619 
1620     /* Create negotiator. */
1621     if (sdp_info->sdp) {
1622 	status = pjmedia_sdp_neg_create_w_remote_offer(inv->pool, local_sdp,
1623 						       sdp_info->sdp,
1624 						       &inv->neg);
1625 
1626     } else if (local_sdp) {
1627 	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool,
1628 						      local_sdp, &inv->neg);
1629     } else {
1630 	status = PJ_SUCCESS;
1631     }
1632 
1633     if (status != PJ_SUCCESS) {
1634 	pjsip_dlg_dec_lock(dlg);
1635 	return status;
1636     }
1637 
1638     /* Register invite as dialog usage. */
1639     status = pjsip_dlg_add_usage(dlg, &mod_inv.mod, inv);
1640     if (status != PJ_SUCCESS) {
1641 	pjsip_dlg_dec_lock(dlg);
1642 	return status;
1643     }
1644 
1645     /* Increment session in the dialog. */
1646     pjsip_dlg_inc_session(dlg, &mod_inv.mod);
1647 
1648     /* Save the invite transaction. */
1649     inv->invite_tsx = pjsip_rdata_get_tsx(rdata);
1650 
1651     /* Attach our data to the transaction. */
1652     tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool, struct tsx_inv_data);
1653     tsx_inv_data->inv = inv;
1654     tsx_inv_data->has_sdp = (sdp_info->sdp!=NULL);
1655     inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
1656 
1657     /* Create 100rel handler */
1658     if (inv->options & PJSIP_INV_REQUIRE_100REL) {
1659 	pjsip_100rel_attach(inv);
1660     }
1661 
1662     /* Done */
1663     pjsip_inv_add_ref(inv);
1664     pjsip_dlg_dec_lock(dlg);
1665     *p_inv = inv;
1666 
1667     PJ_LOG(5,(inv->obj_name, "UAS invite session created for dialog %s",
1668 	      dlg->obj_name));
1669 
1670     return PJ_SUCCESS;
1671 }
1672 
1673 /*
1674  * Forcefully terminate the session.
1675  */
pjsip_inv_terminate(pjsip_inv_session * inv,int st_code,pj_bool_t notify)1676 PJ_DEF(pj_status_t) pjsip_inv_terminate( pjsip_inv_session *inv,
1677 				         int st_code,
1678 					 pj_bool_t notify)
1679 {
1680     PJ_ASSERT_RETURN(inv, PJ_EINVAL);
1681 
1682     /* Lock dialog. */
1683     pjsip_dlg_inc_lock(inv->dlg);
1684 
1685     /* Set callback notify flag. */
1686     inv->notify = notify;
1687 
1688     /* If there's pending transaction, terminate the transaction.
1689      * This may subsequently set the INVITE session state to
1690      * disconnected.
1691      */
1692     if (inv->invite_tsx &&
1693 	inv->invite_tsx->state <= PJSIP_TSX_STATE_COMPLETED)
1694     {
1695 	pjsip_tsx_terminate(inv->invite_tsx, st_code);
1696 
1697     }
1698 
1699     /* Set cause. */
1700     inv_set_cause(inv, st_code, NULL);
1701 
1702     /* Forcefully terminate the session if state is not DISCONNECTED */
1703     if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
1704 	pjsip_event usr_event;
1705 
1706 	PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL);
1707 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, &usr_event);
1708     }
1709 
1710     /* Done.
1711      * The dec_lock() below will actually destroys the dialog if it
1712      * has no other session.
1713      */
1714     pjsip_dlg_dec_lock(inv->dlg);
1715 
1716     return PJ_SUCCESS;
1717 }
1718 
1719 
1720 /*
1721  * Restart UAC session, possibly because app or us wants to re-send the
1722  * INVITE request due to 401/407 challenge or 3xx response.
1723  */
pjsip_inv_uac_restart(pjsip_inv_session * inv,pj_bool_t new_offer)1724 PJ_DEF(pj_status_t) pjsip_inv_uac_restart(pjsip_inv_session *inv,
1725 					  pj_bool_t new_offer)
1726 {
1727     PJ_ASSERT_RETURN(inv, PJ_EINVAL);
1728 
1729     inv->state = PJSIP_INV_STATE_NULL;
1730     inv->invite_tsx = NULL;
1731     if (inv->last_answer) {
1732 	pjsip_tx_data_dec_ref(inv->last_answer);
1733 	inv->last_answer = NULL;
1734     }
1735 
1736     if (new_offer && inv->neg) {
1737 	pjmedia_sdp_neg_state neg_state;
1738 
1739 	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
1740 	if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
1741 	    pjmedia_sdp_neg_cancel_offer(inv->neg);
1742 	}
1743     }
1744 
1745     return PJ_SUCCESS;
1746 }
1747 
1748 
clone_sdp(pj_pool_t * pool,const void * data,unsigned len)1749 static void *clone_sdp(pj_pool_t *pool, const void *data, unsigned len)
1750 {
1751     PJ_UNUSED_ARG(len);
1752     return pjmedia_sdp_session_clone(pool, (const pjmedia_sdp_session*)data);
1753 }
1754 
print_sdp(pjsip_msg_body * body,char * buf,pj_size_t len)1755 static int print_sdp(pjsip_msg_body *body, char *buf, pj_size_t len)
1756 {
1757     return pjmedia_sdp_print((const pjmedia_sdp_session*)body->data, buf, len);
1758 }
1759 
1760 
pjsip_create_sdp_body(pj_pool_t * pool,pjmedia_sdp_session * sdp,pjsip_msg_body ** p_body)1761 PJ_DEF(pj_status_t) pjsip_create_sdp_body( pj_pool_t *pool,
1762 					   pjmedia_sdp_session *sdp,
1763 					   pjsip_msg_body **p_body)
1764 {
1765     const pj_str_t STR_APPLICATION = { "application", 11};
1766     const pj_str_t STR_SDP = { "sdp", 3 };
1767     pjsip_msg_body *body;
1768 
1769     body = PJ_POOL_ZALLOC_T(pool, pjsip_msg_body);
1770     PJ_ASSERT_RETURN(body != NULL, PJ_ENOMEM);
1771 
1772     pjsip_media_type_init(&body->content_type, (pj_str_t*)&STR_APPLICATION,
1773 			  (pj_str_t*)&STR_SDP);
1774     body->data = sdp;
1775     body->len = 0;
1776     body->clone_data = &clone_sdp;
1777     body->print_body = &print_sdp;
1778 
1779     *p_body = body;
1780 
1781     return PJ_SUCCESS;
1782 }
1783 
create_sdp_body(pj_pool_t * pool,const pjmedia_sdp_session * c_sdp)1784 static pjsip_msg_body *create_sdp_body(pj_pool_t *pool,
1785 				       const pjmedia_sdp_session *c_sdp)
1786 {
1787     pjsip_msg_body *body;
1788     pj_status_t status;
1789 
1790     status = pjsip_create_sdp_body(pool,
1791 				   pjmedia_sdp_session_clone(pool, c_sdp),
1792 				   &body);
1793 
1794     if (status != PJ_SUCCESS)
1795 	return NULL;
1796 
1797     return body;
1798 }
1799 
1800 /* Utility to remove a string value from generic array header */
remove_val_from_array_hdr(pjsip_generic_array_hdr * arr_hdr,const pj_str_t * val)1801 static void remove_val_from_array_hdr(pjsip_generic_array_hdr *arr_hdr,
1802 				      const pj_str_t *val)
1803 {
1804     unsigned i;
1805     for (i=0; i<arr_hdr->count; ++i) {
1806 	if (pj_stricmp(&arr_hdr->values[i], val)==0) {
1807 	    pj_array_erase(arr_hdr->values, sizeof(arr_hdr->values[0]),
1808 			   arr_hdr->count, i);
1809 	    --arr_hdr->count;
1810 	    break;
1811 	}
1812     }
1813 }
1814 
1815 
1816 /* Remove disabled extensions, e.g: timer & 100rel, from Allow/Supported
1817  * headers (see ticket #1858).
1818  */
cleanup_allow_sup_hdr(unsigned inv_option,pjsip_tx_data * tdata,pjsip_allow_hdr * allow_hdr,pjsip_supported_hdr * sup_hdr)1819 static void cleanup_allow_sup_hdr(unsigned inv_option,
1820 				  pjsip_tx_data *tdata,
1821 				  pjsip_allow_hdr *allow_hdr,
1822 				  pjsip_supported_hdr *sup_hdr)
1823 {
1824     /* If all extensions are enabled, nothing to do */
1825     if ((inv_option & PJSIP_INV_SUPPORT_100REL) &&
1826 	(inv_option & PJSIP_INV_SUPPORT_TIMER) &&
1827 	(inv_option & PJSIP_INV_SUPPORT_TRICKLE_ICE))
1828     {
1829 	return;
1830     }
1831 
1832     if (!allow_hdr && tdata) {
1833 	allow_hdr = (pjsip_allow_hdr*) pjsip_msg_find_hdr(tdata->msg,
1834 							  PJSIP_H_ALLOW,
1835 							  NULL);
1836     }
1837     if (!sup_hdr && tdata) {
1838 	sup_hdr = (pjsip_supported_hdr*) pjsip_msg_find_hdr(tdata->msg,
1839 							    PJSIP_H_SUPPORTED,
1840 							    NULL);
1841     }
1842 
1843     /* Remove "timer" from Supported header if Session-Timers is
1844      * disabled (https://trac.pjsip.org/repos/ticket/1761)
1845      */
1846     if ((inv_option & PJSIP_INV_SUPPORT_TIMER) == 0 && sup_hdr) {
1847 	const pj_str_t STR_TIMER = { "timer", 5 };
1848 	remove_val_from_array_hdr(sup_hdr, &STR_TIMER);
1849     }
1850 
1851     if ((inv_option & PJSIP_INV_SUPPORT_TRICKLE_ICE) == 0 && sup_hdr) {
1852 	const pj_str_t STR_TRICKLE_ICE = { "trickle-ice", 11 };
1853 	remove_val_from_array_hdr(sup_hdr, &STR_TRICKLE_ICE);
1854     }
1855 
1856     if ((inv_option & PJSIP_INV_SUPPORT_100REL) == 0) {
1857 	const pj_str_t STR_PRACK  = { "PRACK", 5 };
1858 	const pj_str_t STR_100REL = { "100rel", 6 };
1859 
1860 	if (allow_hdr)
1861 	    remove_val_from_array_hdr(allow_hdr, &STR_PRACK);
1862 	if (sup_hdr)
1863 	    remove_val_from_array_hdr(sup_hdr, &STR_100REL);
1864     }
1865 }
1866 
1867 /*
1868  * Create initial INVITE request.
1869  */
pjsip_inv_invite(pjsip_inv_session * inv,pjsip_tx_data ** p_tdata)1870 PJ_DEF(pj_status_t) pjsip_inv_invite( pjsip_inv_session *inv,
1871 				      pjsip_tx_data **p_tdata )
1872 {
1873     pjsip_tx_data *tdata;
1874     const pjsip_hdr *hdr;
1875     pjsip_allow_hdr *allow_hdr = NULL;
1876     pjsip_supported_hdr *sup_hdr = NULL;
1877     pj_bool_t has_sdp;
1878     pj_status_t status;
1879 
1880     /* Verify arguments. */
1881     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
1882 
1883     /* State MUST be NULL or CONFIRMED. */
1884     PJ_ASSERT_RETURN(inv->state == PJSIP_INV_STATE_NULL ||
1885 		     inv->state == PJSIP_INV_STATE_CONFIRMED,
1886 		     PJ_EINVALIDOP);
1887 
1888     /* Lock dialog. */
1889     pjsip_dlg_inc_lock(inv->dlg);
1890 
1891     /* Create the INVITE request. */
1892     status = pjsip_dlg_create_request(inv->dlg, pjsip_get_invite_method(), -1,
1893 				      &tdata);
1894     if (status != PJ_SUCCESS)
1895 	goto on_return;
1896 
1897 
1898     /* If this is the first INVITE, then copy the headers from inv_hdr.
1899      * These are the headers parsed from the request URI when the
1900      * dialog was created.
1901      */
1902     if (inv->state == PJSIP_INV_STATE_NULL) {
1903 	hdr = inv->dlg->inv_hdr.next;
1904 
1905 	while (hdr != &inv->dlg->inv_hdr) {
1906 	    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
1907 			      pjsip_hdr_shallow_clone(tdata->pool, hdr));
1908 	    hdr = hdr->next;
1909 	}
1910     }
1911 
1912     /* See if we have SDP to send. */
1913     if (inv->neg) {
1914 	pjmedia_sdp_neg_state neg_state;
1915 
1916 	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
1917 
1918 	has_sdp = (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER ||
1919 		   (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
1920 		    pjmedia_sdp_neg_has_local_answer(inv->neg)));
1921 
1922 
1923     } else {
1924 	has_sdp = PJ_FALSE;
1925     }
1926 
1927     /* Add SDP, if any. */
1928     if (has_sdp) {
1929 	const pjmedia_sdp_session *offer;
1930 
1931 	status = pjmedia_sdp_neg_get_neg_local(inv->neg, &offer);
1932 	if (status != PJ_SUCCESS) {
1933 	    pjsip_tx_data_dec_ref(tdata);
1934 	    goto on_return;
1935 	}
1936 
1937 	tdata->msg->body = create_sdp_body(tdata->pool, offer);
1938     }
1939 
1940     /* Add Allow header. */
1941     if (inv->dlg->add_allow) {
1942 	hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_ALLOW, NULL);
1943 	if (hdr) {
1944 	    allow_hdr = (pjsip_allow_hdr*)
1945 			pjsip_hdr_shallow_clone(tdata->pool, hdr);
1946 	    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)allow_hdr);
1947 	}
1948     }
1949 
1950     /* Add Supported header */
1951     hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL);
1952     if (hdr) {
1953 	sup_hdr = (pjsip_supported_hdr*)
1954 		   pjsip_hdr_shallow_clone(tdata->pool, hdr);
1955 	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr);
1956     }
1957 
1958     /* Cleanup Allow & Supported headers from disabled extensions */
1959     cleanup_allow_sup_hdr(inv->options, NULL, allow_hdr, sup_hdr);
1960 
1961     /* Add Require header. */
1962     if ((inv->options & PJSIP_INV_REQUIRE_100REL) ||
1963 	(inv->options & PJSIP_INV_REQUIRE_TIMER) ||
1964 	(inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE))
1965     {
1966 	pjsip_require_hdr *hreq;
1967 
1968 	hreq = pjsip_require_hdr_create(tdata->pool);
1969 
1970 	if (inv->options & PJSIP_INV_REQUIRE_100REL)
1971 	    hreq->values[hreq->count++] = pj_str("100rel");
1972 	if (inv->options & PJSIP_INV_REQUIRE_TIMER)
1973 	    hreq->values[hreq->count++] = pj_str("timer");
1974 	if (inv->options & PJSIP_INV_REQUIRE_TRICKLE_ICE)
1975 	    hreq->values[hreq->count++] = pj_str("trickle-ice");
1976 
1977 	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*) hreq);
1978     }
1979 
1980     status = pjsip_timer_update_req(inv, tdata);
1981     if (status != PJ_SUCCESS)
1982 	goto on_return;
1983 
1984     /* Done. */
1985     *p_tdata = tdata;
1986 
1987 
1988 on_return:
1989     pjsip_dlg_dec_lock(inv->dlg);
1990     return status;
1991 }
1992 
1993 
1994 /* Util: swap pool */
swap_pool(pj_pool_t ** p1,pj_pool_t ** p2)1995 static void swap_pool(pj_pool_t **p1, pj_pool_t **p2)
1996 {
1997     pj_pool_t *tmp = *p1;
1998     *p1 = *p2;
1999     *p2 = tmp;
2000 }
2001 
2002 
2003 /*
2004  * Initiate SDP negotiation in the SDP negotiator.
2005  */
inv_negotiate_sdp(pjsip_inv_session * inv)2006 static pj_status_t inv_negotiate_sdp( pjsip_inv_session *inv )
2007 {
2008     pj_status_t status;
2009 
2010     PJ_ASSERT_RETURN(pjmedia_sdp_neg_get_state(inv->neg) ==
2011 		     PJMEDIA_SDP_NEG_STATE_WAIT_NEGO,
2012 		     PJMEDIA_SDPNEG_EINSTATE);
2013 
2014     status = pjmedia_sdp_neg_negotiate(inv->pool_prov, inv->neg, 0);
2015 
2016     PJ_PERROR(4,(inv->obj_name, status, "SDP negotiation done"));
2017 
2018     if (mod_inv.cb.on_media_update && inv->notify)
2019 	(*mod_inv.cb.on_media_update)(inv, status);
2020 
2021     /* Invite session may have been terminated by the application even
2022      * after a successful SDP negotiation, for example when no audio
2023      * codec is present in the offer (see ticket #1034).
2024      */
2025     if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
2026 
2027 	/* Swap the flip-flop pool when SDP negotiation success. */
2028 	if (status == PJ_SUCCESS) {
2029 	    swap_pool(&inv->pool_prov, &inv->pool_active);
2030 	}
2031 
2032 	/* Reset the provisional pool regardless SDP negotiation result. */
2033 	pj_pool_reset(inv->pool_prov);
2034 
2035     } else {
2036 
2037 	status = PJSIP_ERRNO_FROM_SIP_STATUS(inv->cause);
2038     }
2039 
2040     return status;
2041 }
2042 
2043 /*
2044  * Check in incoming message for SDP offer/answer.
2045  */
inv_check_sdp_in_incoming_msg(pjsip_inv_session * inv,pjsip_transaction * tsx,pjsip_rx_data * rdata)2046 static pj_status_t inv_check_sdp_in_incoming_msg( pjsip_inv_session *inv,
2047 						  pjsip_transaction *tsx,
2048 						  pjsip_rx_data *rdata)
2049 {
2050     struct tsx_inv_data *tsx_inv_data;
2051     pj_status_t status;
2052     pjsip_msg *msg;
2053     pjsip_rdata_sdp_info *sdp_info;
2054 
2055     /* Check if SDP is present in the message. */
2056 
2057     msg = rdata->msg_info.msg;
2058     if (msg->body == NULL) {
2059 	/* Message doesn't have body. */
2060 	return PJ_SUCCESS;
2061     }
2062 
2063     sdp_info = pjsip_rdata_get_sdp_info(rdata);
2064     if (sdp_info->body.ptr == NULL) {
2065 	/* Message body is not "application/sdp" */
2066 	return PJMEDIA_SDP_EINSDP;
2067     }
2068 
2069     /* Get/attach invite session's transaction data */
2070     tsx_inv_data = (struct tsx_inv_data*) tsx->mod_data[mod_inv.mod.id];
2071     if (tsx_inv_data == NULL) {
2072 	tsx_inv_data = PJ_POOL_ZALLOC_T(tsx->pool, struct tsx_inv_data);
2073 	tsx_inv_data->inv = inv;
2074 	tsx_inv_data->has_sdp = (sdp_info->sdp!=NULL);
2075 	tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
2076     }
2077 
2078     /* Initialize info that we are following forked media */
2079     inv->following_fork = PJ_FALSE;
2080     inv->updated_sdp_answer = PJ_FALSE;
2081 
2082     /* MUST NOT do multiple SDP offer/answer in a single transaction,
2083      * EXCEPT previous nego was in 18x (early media) and any of the following
2084      * condition is met:
2085      *  - Non-forking scenario:
2086      *	  - 'accept_multiple_sdp_answers' is set, and
2087      *    - previous early response was not reliable (rfc6337 section 3.1.1).
2088      *  - Forking scenario:
2089      *    - This response has different To tag than the previous response, and
2090      *    - This response is 18x/2xx (early or final). If this is 18x,
2091      *      only do multiple SDP nego if 'follow_early_media_fork' is set.
2092      *
2093      * See also tickets #657, #1644, #1764, and #2123 for more info.
2094      */
2095     if (tsx_inv_data->sdp_done) {
2096 	pj_str_t res_tag;
2097 	int st_code;
2098 
2099 	res_tag = rdata->msg_info.to->tag;
2100 	st_code = rdata->msg_info.msg->line.status.code;
2101 
2102 	if (tsx->role == PJSIP_ROLE_UAC && tsx_inv_data->done_early &&
2103 	       (
2104 	           /* Non-forking scenario */
2105 	           (
2106 	               !tsx_inv_data->done_early_rel &&
2107 	               (st_code/100 == 2 || st_code/10 == 18) &&
2108                        pjsip_cfg()->endpt.accept_multiple_sdp_answers &&
2109 	               !pj_stricmp(&tsx_inv_data->done_tag, &res_tag)
2110 	           )
2111 	           ||
2112 	           /* Forking scenario */
2113 	           (
2114 	               (st_code/100 == 2 ||
2115 	                   (st_code/10 == 18 &&
2116 	                       pjsip_cfg()->endpt.follow_early_media_fork)) &&
2117 	               pj_stricmp(&tsx_inv_data->done_tag, &res_tag)
2118 	           )
2119 	       )
2120 	   )
2121 	{
2122 	    const pjmedia_sdp_session *reoffer_sdp = NULL;
2123 
2124 	    if (pjmedia_sdp_neg_get_state(inv->neg) !=
2125 	    	PJMEDIA_SDP_NEG_STATE_DONE)
2126 	    {
2127 	    	PJ_LOG(4,(inv->obj_name, "SDP negotiation in progress, "
2128 	    		  "message body in %s response is ignored",
2129 		          (st_code/10==18? "early" : "final" )));
2130 	    	return PJ_SUCCESS;
2131 	    }
2132 
2133 	    PJ_LOG(4,(inv->obj_name, "Received %s response "
2134 		      "after SDP negotiation has been done in early "
2135 		      "media. Renegotiating SDP..",
2136 		      (st_code/10==18? "early" : "final" )));
2137 
2138 	    /* Retrieve original SDP offer from INVITE request */
2139 	    reoffer_sdp = (const pjmedia_sdp_session*)
2140 			  tsx->last_tx->msg->body->data;
2141 
2142 	    /* Feed the original offer to negotiator */
2143 	    status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov,
2144 							 inv->neg,
2145                                                          inv->sdp_neg_flags,
2146 						         reoffer_sdp);
2147 	    if (status != PJ_SUCCESS) {
2148 		PJ_LOG(1,(inv->obj_name, "Error updating local offer for "
2149 			  "forked 2xx/18x response (err=%d)", status));
2150 		return status;
2151 	    }
2152 
2153 	    inv->following_fork = !!pj_stricmp(&tsx_inv_data->done_tag,
2154 					       &res_tag);
2155 	    inv->updated_sdp_answer = PJ_TRUE;
2156 
2157 	} else {
2158 
2159 	    if (rdata->msg_info.msg->body) {
2160 		PJ_LOG(4,(inv->obj_name, "SDP negotiation done, message "
2161 			  "body is ignored"));
2162 	    }
2163 	    return PJ_SUCCESS;
2164 	}
2165     }
2166 
2167     /* Process the SDP body. */
2168     if (sdp_info->sdp_err) {
2169 	PJ_PERROR(4,(THIS_FILE, sdp_info->sdp_err,
2170 		     "Error parsing SDP in %s",
2171 		     pjsip_rx_data_get_info(rdata)));
2172 	return PJMEDIA_SDP_EINSDP;
2173     }
2174 
2175     pj_assert(sdp_info->sdp != NULL);
2176 
2177     /* The SDP can be an offer or answer, depending on negotiator's state */
2178 
2179     if (inv->neg == NULL ||
2180 	pjmedia_sdp_neg_get_state(inv->neg) == PJMEDIA_SDP_NEG_STATE_DONE)
2181     {
2182 
2183 	/* This is an offer. */
2184 
2185 	PJ_LOG(5,(inv->obj_name, "Got SDP offer in %s",
2186 		  pjsip_rx_data_get_info(rdata)));
2187 
2188 	if (inv->neg == NULL) {
2189 	    status=pjmedia_sdp_neg_create_w_remote_offer(inv->pool, NULL,
2190 							 sdp_info->sdp,
2191 							 &inv->neg);
2192 	} else {
2193 	    status=pjmedia_sdp_neg_set_remote_offer(inv->pool_prov, inv->neg,
2194 						    sdp_info->sdp);
2195 	}
2196 
2197 	if (status != PJ_SUCCESS) {
2198 	    PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP offer in %",
2199 		      pjsip_rx_data_get_info(rdata)));
2200 	    return PJMEDIA_SDP_EINSDP;
2201 	}
2202 
2203 	/* Inform application about remote offer. */
2204 	if (mod_inv.cb.on_rx_offer2 && inv->notify) {
2205 	    struct pjsip_inv_on_rx_offer_cb_param param;
2206 
2207 	    param.offer = sdp_info->sdp;
2208 	    param.rdata = rdata;
2209             (*mod_inv.cb.on_rx_offer2)(inv, &param);
2210 	} else if (mod_inv.cb.on_rx_offer && inv->notify) {
2211             (*mod_inv.cb.on_rx_offer)(inv, sdp_info->sdp);
2212 	}
2213 
2214 	/* application must have supplied an answer at this point. */
2215 	if (pjmedia_sdp_neg_get_state(inv->neg) !=
2216 		PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
2217 	{
2218             if (mod_inv.cb.on_rx_reinvite && inv->notify &&
2219                 msg->type == PJSIP_REQUEST_MSG &&
2220                 msg->line.req.method.id == PJSIP_INVITE_METHOD)
2221             {
2222                 /* Do not return failure first, allow the application
2223                  * to set the answer in the on_rx_reinvite() callback.
2224                  */
2225         	PJ_LOG(5,(inv->obj_name, "Ignoring on_rx_offer() status "
2226         		  "because on_rx_reinvite() is implemented"));
2227                 return PJ_SUCCESS;
2228             }
2229 	    return PJ_EINVALIDOP;
2230 	}
2231 
2232     } else if (pjmedia_sdp_neg_get_state(inv->neg) ==
2233 		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
2234     {
2235 	int status_code;
2236 
2237 	/* This is an answer.
2238 	 * Process and negotiate remote answer.
2239 	 */
2240 
2241 	PJ_LOG(5,(inv->obj_name, "Got SDP answer in %s",
2242 		  pjsip_rx_data_get_info(rdata)));
2243 
2244 	status = pjmedia_sdp_neg_set_remote_answer(inv->pool_prov, inv->neg,
2245 						   sdp_info->sdp);
2246 
2247 	if (status != PJ_SUCCESS) {
2248 	    PJ_PERROR(4,(THIS_FILE, status, "Error processing SDP answer in %s",
2249 		      pjsip_rx_data_get_info(rdata)));
2250 	    return PJMEDIA_SDP_EINSDP;
2251 	}
2252 
2253 	/* Negotiate SDP */
2254 
2255 	inv_negotiate_sdp(inv);
2256 
2257 	/* Mark this transaction has having SDP offer/answer done, and
2258 	 * save the reference to the To tag
2259 	 */
2260 
2261 	tsx_inv_data->sdp_done = 1;
2262 	status_code = rdata->msg_info.msg->line.status.code;
2263 	tsx_inv_data->done_early = (status_code/100==1);
2264 	tsx_inv_data->done_early_rel = tsx_inv_data->done_early &&
2265 				       pjsip_100rel_is_reliable(rdata);
2266 	pj_strdup(tsx->pool, &tsx_inv_data->done_tag,
2267 		  &rdata->msg_info.to->tag);
2268 
2269     } else {
2270 
2271 	PJ_LOG(5,(THIS_FILE, "Ignored SDP in %s: negotiator state is %s",
2272 	      pjsip_rx_data_get_info(rdata),
2273 	      pjmedia_sdp_neg_state_str(pjmedia_sdp_neg_get_state(inv->neg))));
2274     }
2275 
2276     return PJ_SUCCESS;
2277 }
2278 
2279 
2280 /*
2281  * Process INVITE answer, for both initial and subsequent re-INVITE
2282  */
process_answer(pjsip_inv_session * inv,int st_code,pjsip_tx_data * tdata,const pjmedia_sdp_session * local_sdp)2283 static pj_status_t process_answer( pjsip_inv_session *inv,
2284 				   int st_code,
2285 				   pjsip_tx_data *tdata,
2286 				   const pjmedia_sdp_session *local_sdp)
2287 {
2288     pj_status_t status;
2289     const pjmedia_sdp_session *sdp = NULL;
2290 
2291     /* If local_sdp is specified, then we MUST NOT have answered the
2292      * offer before.
2293      */
2294     if (local_sdp && (st_code/100==1 || st_code/100==2)) {
2295 
2296 	if (inv->neg == NULL) {
2297 	    status = pjmedia_sdp_neg_create_w_local_offer(inv->pool,
2298 							  local_sdp,
2299 							  &inv->neg);
2300 	} else if (pjmedia_sdp_neg_get_state(inv->neg)==
2301 		   PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER)
2302 	{
2303 	    status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov, inv->neg,
2304 						      local_sdp);
2305 	} else {
2306 
2307 	    /* Can not specify local SDP at this state. */
2308 	    pj_assert(0);
2309 	    status = PJMEDIA_SDPNEG_EINSTATE;
2310 	}
2311 
2312 	if (status != PJ_SUCCESS)
2313 	    return status;
2314 
2315     }
2316 
2317 
2318      /* If SDP negotiator is ready, start negotiation. */
2319     if (st_code/100==2 || (st_code/10==18 && st_code!=180 && st_code!=181)) {
2320 
2321 	pjmedia_sdp_neg_state neg_state;
2322 
2323 	/* Start nego when appropriate. */
2324 	neg_state = inv->neg ? pjmedia_sdp_neg_get_state(inv->neg) :
2325 		    PJMEDIA_SDP_NEG_STATE_NULL;
2326 
2327 	if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
2328 
2329 	    status = pjmedia_sdp_neg_get_neg_local(inv->neg, &sdp);
2330 
2331 	} else if (neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO &&
2332 		   pjmedia_sdp_neg_has_local_answer(inv->neg) )
2333 	{
2334 	    struct tsx_inv_data *tsx_inv_data;
2335 
2336 	    /* Get invite session's transaction data */
2337 	    tsx_inv_data = (struct tsx_inv_data*)
2338 		           inv->invite_tsx->mod_data[mod_inv.mod.id];
2339 
2340 	    status = inv_negotiate_sdp(inv);
2341 	    if (status != PJ_SUCCESS)
2342 		return status;
2343 
2344 	    /* Mark this transaction has having SDP offer/answer done. */
2345 	    tsx_inv_data->sdp_done = 1;
2346 
2347 	    status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
2348 	}
2349     }
2350 
2351     /* Include SDP when it's available for 2xx and 18x (but not 180 and 181)
2352      * response. Subsequent response will include this SDP.
2353      *
2354      * Note note:
2355      *	- When offer/answer has been completed in reliable 183, we MUST NOT
2356      *	  send SDP in 2xx response. So if we don't have SDP to send, clear
2357      *	  the SDP in the message body ONLY if 100rel is active in this
2358      *    session.
2359      */
2360     if (sdp) {
2361 	tdata->msg->body = create_sdp_body(tdata->pool, sdp);
2362     } else {
2363 	if (inv->options & PJSIP_INV_REQUIRE_100REL) {
2364 	    tdata->msg->body = NULL;
2365 	}
2366     }
2367 
2368     /* Cancel SDP negotiation if this is a negative reply to a re-INVITE */
2369     if (st_code >= 300 && inv->neg != NULL &&
2370         inv->state == PJSIP_INV_STATE_CONFIRMED)
2371     {
2372         pjmedia_sdp_neg_state neg_state;
2373         neg_state = pjmedia_sdp_neg_get_state(inv->neg);
2374         if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER) {
2375             pjmedia_sdp_neg_cancel_offer(inv->neg);
2376         }
2377     }
2378 
2379     return PJ_SUCCESS;
2380 }
2381 
2382 
2383 /*
2384  * Create first response to INVITE
2385  */
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)2386 PJ_DEF(pj_status_t) pjsip_inv_initial_answer(	pjsip_inv_session *inv,
2387 						pjsip_rx_data *rdata,
2388 						int st_code,
2389 						const pj_str_t *st_text,
2390 						const pjmedia_sdp_session *sdp,
2391 						pjsip_tx_data **p_tdata)
2392 {
2393     pjsip_tx_data *tdata;
2394     pj_status_t status;
2395     pjsip_status_code st_code2;
2396 
2397     /* Verify arguments. */
2398     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
2399 
2400     /* Must have INVITE transaction. */
2401     PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG);
2402 
2403     pj_log_push_indent();
2404 
2405     pjsip_dlg_inc_lock(inv->dlg);
2406 
2407     /* Create response */
2408     status = pjsip_dlg_create_response(inv->dlg, rdata, st_code, st_text,
2409 				       &tdata);
2410     if (status != PJ_SUCCESS)
2411 	goto on_return;
2412 
2413     /* Invoke Session Timers module */
2414     status = pjsip_timer_process_req(inv, rdata, &st_code2);
2415     if (status != PJ_SUCCESS) {
2416 	pj_status_t status2;
2417 
2418 	status2 = pjsip_dlg_modify_response(inv->dlg, tdata, st_code2, NULL);
2419 	if (status2 != PJ_SUCCESS) {
2420 	    pjsip_tx_data_dec_ref(tdata);
2421 	    goto on_return;
2422 	}
2423 	status2 = pjsip_timer_update_resp(inv, tdata);
2424 	if (status2 == PJ_SUCCESS)
2425 	    *p_tdata = tdata;
2426 	else
2427 	    pjsip_tx_data_dec_ref(tdata);
2428 
2429 	goto on_return;
2430     }
2431 
2432     /* Process SDP in answer */
2433     status = process_answer(inv, st_code, tdata, sdp);
2434     if (status != PJ_SUCCESS) {
2435 	pjsip_tx_data_dec_ref(tdata);
2436 	goto on_return;
2437     }
2438 
2439     /* Cleanup Allow & Supported headers from disabled extensions */
2440     cleanup_allow_sup_hdr(inv->options, tdata, NULL, NULL);
2441 
2442     /* Save this answer */
2443     inv->last_answer = tdata;
2444     pjsip_tx_data_add_ref(inv->last_answer);
2445     PJ_LOG(5,(inv->dlg->obj_name, "Initial answer %s",
2446 	      pjsip_tx_data_get_info(inv->last_answer)));
2447 
2448     /* Invoke Session Timers */
2449     pjsip_timer_update_resp(inv, tdata);
2450 
2451     *p_tdata = tdata;
2452 
2453 on_return:
2454     pjsip_dlg_dec_lock(inv->dlg);
2455     pj_log_pop_indent();
2456     return status;
2457 }
2458 
2459 
2460 /*
2461  * Answer INVITE request.
2462  */
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)2463 PJ_DEF(pj_status_t) pjsip_inv_answer(	pjsip_inv_session *inv,
2464 					int st_code,
2465 					const pj_str_t *st_text,
2466 					const pjmedia_sdp_session *local_sdp,
2467 					pjsip_tx_data **p_tdata )
2468 {
2469     pjsip_tx_data *last_res;
2470     pjsip_tx_data *old_res;
2471     pj_status_t status;
2472 
2473     /* Verify arguments. */
2474     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
2475 
2476     /* Must have INVITE transaction. */
2477     PJ_ASSERT_RETURN(inv->invite_tsx, PJ_EBUG);
2478 
2479     /* Must have created an answer before */
2480     PJ_ASSERT_RETURN(inv->last_answer, PJ_EINVALIDOP);
2481 
2482     pj_log_push_indent();
2483 
2484     pjsip_dlg_inc_lock(inv->dlg);
2485 
2486     /* Clone last response.
2487      * The tdata (last_answer) is a shared object used by the transaction.
2488      * Modifying a shared object might lead to a deadlock.
2489      * Refer to ticket #2137 for more detail.
2490      */
2491     status = pjsip_tx_data_clone(inv->last_answer, 0, &last_res);
2492     if (status != PJ_SUCCESS)
2493 	goto on_return;
2494 
2495     /* Modify last response. */
2496     status = pjsip_dlg_modify_response(inv->dlg, last_res, st_code, st_text);
2497     if (status != PJ_SUCCESS) {
2498 	pjsip_tx_data_dec_ref(last_res);
2499 	goto on_return;
2500     }
2501 
2502     /* For non-2xx final response, strip message body */
2503     if (st_code >= 300) {
2504 	last_res->msg->body = NULL;
2505     }
2506 
2507     /* Process SDP in answer */
2508     status = process_answer(inv, st_code, last_res, local_sdp);
2509     if (status != PJ_SUCCESS) {
2510 	pjsip_tx_data_dec_ref(last_res);
2511 	goto on_return;
2512     }
2513 
2514     /* Invoke Session Timers */
2515     pjsip_timer_update_resp(inv, last_res);
2516 
2517     /* Cleanup Allow & Supported headers from disabled extensions */
2518     cleanup_allow_sup_hdr(inv->options, last_res, NULL, NULL);
2519 
2520     /* Update last_answer */
2521     old_res = inv->last_answer;
2522     inv->last_answer = last_res;
2523 
2524     /* Release old answer */
2525     pjsip_tx_data_dec_ref(old_res);
2526 
2527     *p_tdata = last_res;
2528 
2529 on_return:
2530     pjsip_dlg_dec_lock(inv->dlg);
2531     pj_log_pop_indent();
2532     return status;
2533 }
2534 
2535 
2536 /*
2537  * Set local SDP offer/answer.
2538  */
pjsip_inv_set_local_sdp(pjsip_inv_session * inv,const pjmedia_sdp_session * sdp)2539 PJ_DEF(pj_status_t) pjsip_inv_set_local_sdp(pjsip_inv_session *inv,
2540 					    const pjmedia_sdp_session *sdp )
2541 {
2542     const pjmedia_sdp_session *offer;
2543     pj_status_t status;
2544 
2545     PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL);
2546 
2547     /* If we have remote SDP offer, set local answer to respond to the offer,
2548      * otherwise we set/modify our local offer (and create an SDP negotiator
2549      * if we don't have one yet).
2550      */
2551     if (inv->neg) {
2552         pjmedia_sdp_neg_state neg_state = pjmedia_sdp_neg_get_state(inv->neg);
2553 
2554         if ((neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER ||
2555 	     neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO) &&
2556             pjmedia_sdp_neg_get_neg_remote(inv->neg, &offer) == PJ_SUCCESS)
2557         {
2558             status = pjsip_inv_set_sdp_answer(inv, sdp);
2559         }  else if (neg_state == PJMEDIA_SDP_NEG_STATE_DONE) {
2560             status = pjmedia_sdp_neg_modify_local_offer2(inv->pool, inv->neg,
2561                                                          inv->sdp_neg_flags,
2562                                                          sdp);
2563         } else
2564             return PJMEDIA_SDPNEG_EINSTATE;
2565     } else {
2566 	status = pjmedia_sdp_neg_create_w_local_offer(inv->pool,
2567 						      sdp, &inv->neg);
2568     }
2569 
2570     return status;
2571 }
2572 
2573 
2574 /*
2575  * Set SDP answer.
2576  */
pjsip_inv_set_sdp_answer(pjsip_inv_session * inv,const pjmedia_sdp_session * sdp)2577 PJ_DEF(pj_status_t) pjsip_inv_set_sdp_answer( pjsip_inv_session *inv,
2578 					      const pjmedia_sdp_session *sdp )
2579 {
2580     pj_status_t status;
2581 
2582     PJ_ASSERT_RETURN(inv && sdp, PJ_EINVAL);
2583 
2584     pjsip_dlg_inc_lock(inv->dlg);
2585     status = pjmedia_sdp_neg_set_local_answer( inv->pool_prov, inv->neg, sdp);
2586     pjsip_dlg_dec_lock(inv->dlg);
2587 
2588     return status;
2589 }
2590 
2591 
2592 /*
2593  * End session.
2594  */
pjsip_inv_end_session(pjsip_inv_session * inv,int st_code,const pj_str_t * st_text,pjsip_tx_data ** p_tdata)2595 PJ_DEF(pj_status_t) pjsip_inv_end_session(  pjsip_inv_session *inv,
2596 					    int st_code,
2597 					    const pj_str_t *st_text,
2598 					    pjsip_tx_data **p_tdata )
2599 {
2600     pjsip_tx_data *tdata;
2601     pj_status_t status;
2602 
2603     /* Verify arguments. */
2604     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
2605 
2606     pj_log_push_indent();
2607 
2608     /* Set cause code. */
2609     inv_set_cause(inv, st_code, st_text);
2610 
2611     /* Create appropriate message. */
2612     switch (inv->state) {
2613     case PJSIP_INV_STATE_CALLING:
2614     case PJSIP_INV_STATE_EARLY:
2615     case PJSIP_INV_STATE_INCOMING:
2616 
2617 	if (inv->role == PJSIP_ROLE_UAC) {
2618 
2619 	    /* For UAC when session has not been confirmed, create CANCEL. */
2620 
2621 	    /* MUST have the original UAC INVITE transaction. */
2622 	    PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG);
2623 
2624 	    /* But CANCEL should only be called when we have received a
2625 	     * provisional response. If we haven't received any responses,
2626 	     * just destroy the transaction.
2627 	     */
2628 	    if (inv->invite_tsx->status_code < 100) {
2629 
2630 		/* Do not stop INVITE retransmission, see ticket #506 */
2631 		//pjsip_tsx_stop_retransmit(inv->invite_tsx);
2632 		inv->cancelling = PJ_TRUE;
2633 		inv->pending_cancel = PJ_TRUE;
2634 		*p_tdata = NULL;
2635 		PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no "
2636 			   "provisional response is received yet"));
2637 		pj_log_pop_indent();
2638 		return PJ_SUCCESS;
2639 	    }
2640 
2641 	    /* The CSeq here assumes that the dialog is started with an
2642 	     * INVITE session. This may not be correct; dialog can be
2643 	     * started as SUBSCRIBE session.
2644 	     * So fix this!
2645 	     */
2646 	    status = pjsip_endpt_create_cancel(inv->dlg->endpt,
2647 					       inv->invite_tsx->last_tx,
2648 					       &tdata);
2649 	    if (status != PJ_SUCCESS) {
2650 		pj_log_pop_indent();
2651 		return status;
2652 	    }
2653 
2654 	    /* Set timeout for the INVITE transaction, in case UAS is not
2655 	     * able to respond the INVITE with 487 final response. The
2656 	     * timeout value is 64*T1.
2657 	     */
2658 	    pjsip_tsx_set_timeout(inv->invite_tsx, 64 * pjsip_cfg()->tsx.t1);
2659 
2660 	} else {
2661 
2662 	    /* For UAS, send a final response. */
2663 	    tdata = inv->invite_tsx->last_tx;
2664 	    PJ_ASSERT_RETURN(tdata != NULL, PJ_EINVALIDOP);
2665 
2666 	    //status = pjsip_dlg_modify_response(inv->dlg, tdata, st_code,
2667 	    //				       st_text);
2668 	    status = pjsip_inv_answer(inv, st_code, st_text, NULL, &tdata);
2669 	}
2670 	break;
2671 
2672     case PJSIP_INV_STATE_CONNECTING:
2673     case PJSIP_INV_STATE_CONFIRMED:
2674 	/* End Session Timer */
2675 	pjsip_timer_end_session(inv);
2676 
2677 	/* For established dialog, send BYE */
2678 	status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(),
2679 					  -1, &tdata);
2680 	break;
2681 
2682     case PJSIP_INV_STATE_DISCONNECTED:
2683 	/* No need to do anything. */
2684 	pj_log_pop_indent();
2685 	return PJSIP_ESESSIONTERMINATED;
2686 
2687     default:
2688 	pj_assert(!"Invalid operation!");
2689 	pj_log_pop_indent();
2690 	return PJ_EINVALIDOP;
2691     }
2692 
2693     if (status != PJ_SUCCESS) {
2694 	pj_log_pop_indent();
2695 	return status;
2696     }
2697 
2698 
2699     /* Done */
2700 
2701     inv->cancelling = PJ_TRUE;
2702     *p_tdata = tdata;
2703 
2704     pj_log_pop_indent();
2705     return PJ_SUCCESS;
2706 }
2707 
2708 /*
2709  * Cancel re-INVITE transaction.
2710  */
pjsip_inv_cancel_reinvite(pjsip_inv_session * inv,pjsip_tx_data ** p_tdata)2711 PJ_DEF(pj_status_t) pjsip_inv_cancel_reinvite( pjsip_inv_session *inv,
2712                                                pjsip_tx_data **p_tdata )
2713 {
2714     pjsip_tx_data *tdata;
2715     pj_status_t status;
2716 
2717     /* Verify arguments. */
2718     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
2719 
2720     pj_log_push_indent();
2721 
2722     /* Create appropriate message. */
2723     switch (inv->state) {
2724     case PJSIP_INV_STATE_CONFIRMED:
2725         /* MUST have the original UAC INVITE transaction  */
2726         PJ_ASSERT_RETURN(inv->invite_tsx != NULL, PJ_EBUG);
2727 
2728         /* CANCEL should only be called when we have received a
2729          * provisional response.
2730          */
2731         if (inv->invite_tsx->status_code < 100) {
2732             inv->cancelling = PJ_TRUE;
2733             inv->pending_cancel = PJ_TRUE;
2734             *p_tdata = NULL;
2735             PJ_LOG(4, (inv->obj_name, "Delaying CANCEL since no "
2736                        "provisional response is received yet"));
2737             pj_log_pop_indent();
2738             return PJ_SUCCESS;
2739         }
2740 
2741         status = pjsip_endpt_create_cancel(inv->dlg->endpt,
2742                                            inv->invite_tsx->last_tx,
2743                                            &tdata);
2744         if (status != PJ_SUCCESS) {
2745             pj_log_pop_indent();
2746             return status;
2747         }
2748 	break;
2749 
2750     default:
2751         /* We cannot send CANCEL to a re-INVITE if the INVITE session is
2752          * not confirmed.
2753          */
2754         pj_log_pop_indent();
2755         return PJ_EINVALIDOP;
2756     }
2757 
2758     pj_log_pop_indent();
2759 
2760     *p_tdata = tdata;
2761     return PJ_SUCCESS;
2762 }
2763 
2764 /* Following redirection recursion, get next target from the target set and
2765  * notify user.
2766  *
2767  * Returns PJ_FALSE if recursion fails (either because there's no more target
2768  * or user rejects the recursion). If we return PJ_FALSE, caller should
2769  * disconnect the session.
2770  *
2771  * Note:
2772  *   the event 'e' argument may be NULL.
2773  */
inv_uac_recurse(pjsip_inv_session * inv,int code,const pj_str_t * reason,pjsip_event * e)2774 static pj_bool_t inv_uac_recurse(pjsip_inv_session *inv, int code,
2775 				 const pj_str_t *reason, pjsip_event *e)
2776 {
2777     pjsip_redirect_op op;
2778     pjsip_target *target;
2779 
2780     /* Won't redirect if the callback is not implemented. */
2781     if (mod_inv.cb.on_redirected == NULL)
2782 	return PJ_FALSE;
2783 
2784     if (reason == NULL)
2785 	reason = pjsip_get_status_text(code);
2786 
2787     /* Set status of current target */
2788     pjsip_target_assign_status(inv->dlg->target_set.current, inv->dlg->pool,
2789 			       code, reason);
2790 
2791     /* Fetch next target from the target set. We only want to
2792      * process SIP/SIPS URI for now.
2793      */
2794     for (;;) {
2795 	target = pjsip_target_set_get_next(&inv->dlg->target_set);
2796 	if (target == NULL) {
2797 	    /* No more target. */
2798 	    return PJ_FALSE;
2799 	}
2800 
2801 	if (!PJSIP_URI_SCHEME_IS_SIP(target->uri) &&
2802 	    !PJSIP_URI_SCHEME_IS_SIPS(target->uri))
2803 	{
2804 	    code = PJSIP_SC_UNSUPPORTED_URI_SCHEME;
2805 	    reason = pjsip_get_status_text(code);
2806 
2807 	    /* Mark this target as unusable and fetch next target. */
2808 	    pjsip_target_assign_status(target, inv->dlg->pool, code, reason);
2809 	} else {
2810 	    /* Found a target */
2811 	    break;
2812 	}
2813     }
2814 
2815     /* We have target in 'target'. Set this target as current target
2816      * and notify callback.
2817      */
2818     pjsip_target_set_set_current(&inv->dlg->target_set, target);
2819 
2820     op = (*mod_inv.cb.on_redirected)(inv, target->uri, e);
2821 
2822 
2823     /* Check what the application wants to do now */
2824     switch (op) {
2825     case PJSIP_REDIRECT_ACCEPT:
2826     case PJSIP_REDIRECT_ACCEPT_REPLACE:
2827     case PJSIP_REDIRECT_STOP:
2828 	/* Must increment session counter, that's the convention of the
2829 	 * pjsip_inv_process_redirect().
2830 	 */
2831 	pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod);
2832 
2833 	/* Act on the recursion */
2834 	pjsip_inv_process_redirect(inv, op, e);
2835 	return PJ_TRUE;
2836 
2837     case PJSIP_REDIRECT_PENDING:
2838 	/* Increment session so that the dialog/session is not destroyed
2839 	 * while we're waiting for user confirmation.
2840 	 */
2841 	pjsip_dlg_inc_session(inv->dlg, &mod_inv.mod);
2842 
2843 	/* Also clear the invite_tsx variable, otherwise when this tsx is
2844 	 * terminated, it will also terminate the session.
2845 	 */
2846 	inv->invite_tsx = NULL;
2847 
2848 	/* Done. The processing will continue once the application calls
2849 	 * pjsip_inv_process_redirect().
2850 	 */
2851 	return PJ_TRUE;
2852 
2853     case PJSIP_REDIRECT_REJECT:
2854 	/* Recursively call  this function again to fetch next target, if any.
2855 	 */
2856 	return inv_uac_recurse(inv, PJSIP_SC_REQUEST_TERMINATED, NULL, e);
2857 
2858     }
2859 
2860     pj_assert(!"Should not reach here");
2861     return PJ_FALSE;
2862 }
2863 
2864 
2865 /* Process redirection/recursion */
pjsip_inv_process_redirect(pjsip_inv_session * inv,pjsip_redirect_op op,pjsip_event * e)2866 PJ_DEF(pj_status_t) pjsip_inv_process_redirect( pjsip_inv_session *inv,
2867 						pjsip_redirect_op op,
2868 						pjsip_event *e)
2869 {
2870     const pjsip_status_code cancel_code = PJSIP_SC_REQUEST_TERMINATED;
2871     pjsip_event usr_event;
2872     pj_status_t status = PJ_SUCCESS;
2873 
2874     PJ_ASSERT_RETURN(inv && op != PJSIP_REDIRECT_PENDING, PJ_EINVAL);
2875 
2876     if (e == NULL) {
2877 	PJSIP_EVENT_INIT_USER(usr_event, NULL, NULL, NULL, NULL);
2878 	e = &usr_event;
2879     }
2880 
2881     pjsip_dlg_inc_lock(inv->dlg);
2882 
2883     /* Decrement session. That's the convention here to prevent the dialog
2884      * or session from being destroyed while we're waiting for user
2885      * confirmation.
2886      */
2887     pjsip_dlg_dec_session(inv->dlg, &mod_inv.mod);
2888 
2889     /* See what the application wants to do now */
2890     switch (op) {
2891     case PJSIP_REDIRECT_ACCEPT:
2892     case PJSIP_REDIRECT_ACCEPT_REPLACE:
2893 	/* User accept the redirection. Reset the session and resend the
2894 	 * INVITE request.
2895 	 */
2896 	{
2897 	    pjsip_tx_data *tdata;
2898 	    pjsip_via_hdr *via;
2899 
2900 	    /* Get the original INVITE request. */
2901 	    tdata = inv->invite_req;
2902 	    pjsip_tx_data_add_ref(tdata);
2903 
2904 	    /* Restore strict route set.
2905 	     * See http://trac.pjsip.org/repos/ticket/492
2906 	     */
2907 	    pjsip_restore_strict_route_set(tdata);
2908 
2909 	    /* Set target */
2910 	    tdata->msg->line.req.uri = (pjsip_uri*)
2911 	       pjsip_uri_clone(tdata->pool, inv->dlg->target_set.current->uri);
2912 
2913 	    /* Remove branch param in Via header. */
2914 	    via = (pjsip_via_hdr*)
2915 		  pjsip_msg_find_hdr(tdata->msg, PJSIP_H_VIA, NULL);
2916 	    via->branch_param.slen = 0;
2917 
2918 	    /* Process PJSIP_REDIRECT_ACCEPT_REPLACE */
2919 	    if (op == PJSIP_REDIRECT_ACCEPT_REPLACE) {
2920 		pjsip_to_hdr *to;
2921 		pjsip_dialog *dlg = inv->dlg;
2922 		enum { TMP_LEN = PJSIP_MAX_URL_SIZE };
2923 		char tmp[TMP_LEN];
2924 		int len;
2925 
2926 		/* Replace To header */
2927 		to = PJSIP_MSG_TO_HDR(tdata->msg);
2928 		to->uri = (pjsip_uri*)
2929 			  pjsip_uri_clone(tdata->pool,
2930 				          dlg->target_set.current->uri);
2931 		to->tag.slen = 0;
2932 		pj_list_init(&to->other_param);
2933 
2934 		/* Re-init dialog remote info */
2935 		dlg->remote.info = (pjsip_to_hdr*)
2936 				   pjsip_hdr_clone(dlg->pool, to);
2937 
2938 		/* Remove header param from remote info */
2939 		if (PJSIP_URI_SCHEME_IS_SIP(dlg->remote.info->uri) ||
2940 		    PJSIP_URI_SCHEME_IS_SIPS(dlg->remote.info->uri))
2941 		{
2942 		    pjsip_sip_uri *sip_uri = (pjsip_sip_uri *)
2943 				   pjsip_uri_get_uri(dlg->remote.info->uri);
2944 		    if (!pj_list_empty(&sip_uri->header_param)) {
2945 			/* Remove all header param */
2946 			pj_list_init(&sip_uri->header_param);
2947 		    }
2948 		}
2949 
2950 		/* Print the remote info. */
2951 		len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR,
2952 				      dlg->remote.info->uri, tmp, TMP_LEN);
2953 		if (len < 1) {
2954 		    pj_ansi_strcpy(tmp, "<-error: uri too long->");
2955 		    len = (int)pj_ansi_strlen(tmp);
2956 		}
2957 		pj_strdup2_with_null(dlg->pool, &dlg->remote.info_str, tmp);
2958 
2959 		/* Secure? */
2960 		dlg->secure = PJSIP_URI_SCHEME_IS_SIPS(to->uri);
2961 	    }
2962 
2963 	    /* Reset message destination info (see #1248). */
2964 	    pj_bzero(&tdata->dest_info, sizeof(tdata->dest_info));
2965 
2966 	    /* Must invalidate the message! */
2967 	    pjsip_tx_data_invalidate_msg(tdata);
2968 
2969 	    /* Reset the session */
2970 	    pjsip_inv_uac_restart(inv, PJ_FALSE);
2971 
2972 	    /* (re)Send the INVITE request */
2973 	    status = pjsip_inv_send_msg(inv, tdata);
2974 	}
2975 	break;
2976 
2977     case PJSIP_REDIRECT_STOP:
2978 	/* User doesn't want the redirection. Disconnect the session now. */
2979 	inv_set_cause(inv, cancel_code, pjsip_get_status_text(cancel_code));
2980 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
2981 
2982 	/* Caller should expect that the invite session is gone now, so
2983 	 * we don't need to set status to PJSIP_ESESSIONTERMINATED here.
2984 	 */
2985 	break;
2986 
2987     case PJSIP_REDIRECT_REJECT:
2988 	/* Current target is rejected. Fetch next target if any. */
2989 	if (inv_uac_recurse(inv, cancel_code, NULL, NULL) == PJ_FALSE) {
2990 	    inv_set_cause(inv, cancel_code,
2991 			  pjsip_get_status_text(cancel_code));
2992 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
2993 
2994 	    /* Tell caller that the invite session is gone now */
2995 	    status = PJSIP_ESESSIONTERMINATED;
2996 	}
2997 	break;
2998 
2999 
3000     case PJSIP_REDIRECT_PENDING:
3001 	pj_assert(!"Should not happen");
3002 	break;
3003     }
3004 
3005 
3006     pjsip_dlg_dec_lock(inv->dlg);
3007 
3008     return status;
3009 }
3010 
3011 
3012 /*
3013  * Create re-INVITE.
3014  */
pjsip_inv_reinvite(pjsip_inv_session * inv,const pj_str_t * new_contact,const pjmedia_sdp_session * new_offer,pjsip_tx_data ** p_tdata)3015 PJ_DEF(pj_status_t) pjsip_inv_reinvite( pjsip_inv_session *inv,
3016 					const pj_str_t *new_contact,
3017 					const pjmedia_sdp_session *new_offer,
3018 					pjsip_tx_data **p_tdata )
3019 {
3020     pj_status_t status;
3021     pjsip_contact_hdr *contact_hdr = NULL;
3022 
3023     /* Check arguments. */
3024     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
3025 
3026     /* Must NOT have a pending INVITE transaction */
3027     if (inv->invite_tsx!=NULL)
3028 	return PJ_EINVALIDOP;
3029 
3030     pj_log_push_indent();
3031 
3032     pjsip_dlg_inc_lock(inv->dlg);
3033 
3034     if (new_contact) {
3035 	pj_str_t tmp;
3036 	const pj_str_t STR_CONTACT = { "Contact", 7 };
3037 
3038 	pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact);
3039 	contact_hdr = (pjsip_contact_hdr*)
3040 		      pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT,
3041 				      tmp.ptr, tmp.slen, NULL);
3042 	if (!contact_hdr) {
3043 	    status = PJSIP_EINVALIDURI;
3044 	    goto on_return;
3045 	}
3046     }
3047 
3048 
3049     if (new_offer) {
3050 	if (!inv->neg) {
3051 	    status = pjmedia_sdp_neg_create_w_local_offer(inv->pool,
3052 							  new_offer,
3053 							  &inv->neg);
3054 	    if (status != PJ_SUCCESS)
3055 		goto on_return;
3056 
3057 	} else switch (pjmedia_sdp_neg_get_state(inv->neg)) {
3058 
3059 	    case PJMEDIA_SDP_NEG_STATE_NULL:
3060 		pj_assert(!"Unexpected SDP neg state NULL");
3061 		status = PJ_EBUG;
3062 		goto on_return;
3063 
3064 	    case PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER:
3065 		PJ_LOG(4,(inv->obj_name,
3066 			  "pjsip_inv_reinvite: already have an offer, new "
3067 			  "offer is ignored"));
3068 		break;
3069 
3070 	    case PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER:
3071 		status = pjmedia_sdp_neg_set_local_answer(inv->pool_prov,
3072 							  inv->neg,
3073 							  new_offer);
3074 		if (status != PJ_SUCCESS)
3075 		    goto on_return;
3076 		break;
3077 
3078 	    case PJMEDIA_SDP_NEG_STATE_WAIT_NEGO:
3079 		PJ_LOG(4,(inv->obj_name,
3080 			  "pjsip_inv_reinvite: SDP in WAIT_NEGO state, new "
3081 			  "offer is ignored"));
3082 		break;
3083 
3084 	    case PJMEDIA_SDP_NEG_STATE_DONE:
3085 		status = pjmedia_sdp_neg_modify_local_offer2(
3086                              inv->pool_prov, inv->neg,
3087                              inv->sdp_neg_flags, new_offer);
3088 		if (status != PJ_SUCCESS)
3089 		    goto on_return;
3090 		break;
3091 	}
3092     }
3093 
3094     if (contact_hdr)
3095 	inv->dlg->local.contact = contact_hdr;
3096 
3097     status = pjsip_inv_invite(inv, p_tdata);
3098 
3099 on_return:
3100     pjsip_dlg_dec_lock(inv->dlg);
3101     pj_log_pop_indent();
3102     return status;
3103 }
3104 
3105 /*
3106  * Create UPDATE.
3107  */
pjsip_inv_update(pjsip_inv_session * inv,const pj_str_t * new_contact,const pjmedia_sdp_session * offer,pjsip_tx_data ** p_tdata)3108 PJ_DEF(pj_status_t) pjsip_inv_update (	pjsip_inv_session *inv,
3109 					const pj_str_t *new_contact,
3110 					const pjmedia_sdp_session *offer,
3111 					pjsip_tx_data **p_tdata )
3112 {
3113     pjsip_contact_hdr *contact_hdr = NULL;
3114     pjsip_tx_data *tdata = NULL;
3115     pjmedia_sdp_session *sdp_copy;
3116     const pjsip_hdr *hdr;
3117     pjsip_supported_hdr *sup_hdr = NULL;
3118     pj_status_t status = PJ_SUCCESS;
3119 
3120     /* Verify arguments. */
3121     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
3122 
3123     /* Dialog must have been established */
3124     PJ_ASSERT_RETURN(inv->dlg->state == PJSIP_DIALOG_STATE_ESTABLISHED,
3125 		     PJ_EINVALIDOP);
3126 
3127     /* Invite session must not have been disconnected */
3128     PJ_ASSERT_RETURN(inv->state < PJSIP_INV_STATE_DISCONNECTED,
3129 		     PJ_EINVALIDOP);
3130 
3131     pj_log_push_indent();
3132 
3133     /* Lock dialog. */
3134     pjsip_dlg_inc_lock(inv->dlg);
3135 
3136     /* Process offer, if any */
3137     if (offer) {
3138 	if (pjmedia_sdp_neg_get_state(inv->neg)!=PJMEDIA_SDP_NEG_STATE_DONE) {
3139 	    PJ_LOG(4,(inv->dlg->obj_name,
3140 		      "Invalid SDP offer/answer state for UPDATE"));
3141 	    status = PJ_EINVALIDOP;
3142 	    goto on_error;
3143 	}
3144 
3145 	/* Notify negotiator about the new offer. This will fix the offer
3146 	 * with correct SDP origin.
3147 	 */
3148 	status = pjmedia_sdp_neg_modify_local_offer2(inv->pool_prov, inv->neg,
3149 						     inv->sdp_neg_flags, offer);
3150 	if (status != PJ_SUCCESS)
3151 	    goto on_error;
3152 
3153 	/* Retrieve the "fixed" offer from negotiator */
3154 	pjmedia_sdp_neg_get_neg_local(inv->neg, &offer);
3155     }
3156 
3157     /* Update Contact if required */
3158     if (new_contact) {
3159 	pj_str_t tmp;
3160 	const pj_str_t STR_CONTACT = { "Contact", 7 };
3161 
3162 	pj_strdup_with_null(inv->dlg->pool, &tmp, new_contact);
3163 	contact_hdr = (pjsip_contact_hdr*)
3164 		      pjsip_parse_hdr(inv->dlg->pool, &STR_CONTACT,
3165 				      tmp.ptr, tmp.slen, NULL);
3166 	if (!contact_hdr) {
3167 	    status = PJSIP_EINVALIDURI;
3168 	    goto on_error;
3169 	}
3170 
3171 	inv->dlg->local.contact = contact_hdr;
3172     }
3173 
3174     /* Create request */
3175     status = pjsip_dlg_create_request(inv->dlg, &pjsip_update_method,
3176 				      -1, &tdata);
3177     if (status != PJ_SUCCESS)
3178 	    goto on_error;
3179 
3180     /* Attach SDP body */
3181     if (offer) {
3182 	sdp_copy = pjmedia_sdp_session_clone(tdata->pool, offer);
3183 	pjsip_create_sdp_body(tdata->pool, sdp_copy, &tdata->msg->body);
3184     }
3185 
3186     /* Session Timers spec (RFC 4028) says that Supported header MUST be put
3187      * in refresh requests. So here we'll just put the Supported header in
3188      * all cases regardless of whether session timers is used or not, just
3189      * in case this is a common behavior.
3190      */
3191     hdr = pjsip_endpt_get_capability(inv->dlg->endpt, PJSIP_H_SUPPORTED, NULL);
3192     if (hdr) {
3193 	sup_hdr = (pjsip_supported_hdr*)
3194 		   pjsip_hdr_shallow_clone(tdata->pool, hdr);
3195 	pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)sup_hdr);
3196     }
3197 
3198     status = pjsip_timer_update_req(inv, tdata);
3199     if (status != PJ_SUCCESS)
3200 	goto on_error;
3201 
3202     /* Cleanup Allow & Supported headers from disabled extensions */
3203     cleanup_allow_sup_hdr(inv->options, NULL, NULL, sup_hdr);
3204 
3205     /* Unlock dialog. */
3206     pjsip_dlg_dec_lock(inv->dlg);
3207 
3208     *p_tdata = tdata;
3209 
3210     pj_log_pop_indent();
3211     return PJ_SUCCESS;
3212 
3213 on_error:
3214     if (tdata)
3215 	pjsip_tx_data_dec_ref(tdata);
3216 
3217     /* Unlock dialog. */
3218     pjsip_dlg_dec_lock(inv->dlg);
3219 
3220     pj_log_pop_indent();
3221     return status;
3222 }
3223 
3224 /*
3225  * Create an ACK request.
3226  */
pjsip_inv_create_ack(pjsip_inv_session * inv,int cseq,pjsip_tx_data ** p_tdata)3227 PJ_DEF(pj_status_t) pjsip_inv_create_ack(pjsip_inv_session *inv,
3228 					 int cseq,
3229 					 pjsip_tx_data **p_tdata)
3230 {
3231     const pjmedia_sdp_session *sdp = NULL;
3232     pj_status_t status;
3233 
3234     PJ_ASSERT_RETURN(inv && p_tdata, PJ_EINVAL);
3235 
3236     /* Lock dialog. */
3237     pjsip_dlg_inc_lock(inv->dlg);
3238 
3239     /* Destroy last_ack */
3240     if (inv->last_ack) {
3241 	pjsip_tx_data_dec_ref(inv->last_ack);
3242 	inv->last_ack = NULL;
3243     }
3244 
3245     /* Create new ACK request */
3246     status = pjsip_dlg_create_request(inv->dlg, pjsip_get_ack_method(),
3247 				      cseq, &inv->last_ack);
3248     if (status != PJ_SUCCESS) {
3249 	pjsip_dlg_dec_lock(inv->dlg);
3250 	return status;
3251     }
3252 
3253     /* See if we have pending SDP answer to send */
3254     sdp = inv_has_pending_answer(inv, inv->invite_tsx);
3255     if (sdp) {
3256 	inv->last_ack->msg->body = create_sdp_body(inv->last_ack->pool, sdp);
3257     }
3258 
3259     /* Keep this for subsequent response retransmission */
3260     inv->last_ack_cseq = cseq;
3261     pjsip_tx_data_add_ref(inv->last_ack);
3262 
3263     /* Done */
3264     *p_tdata = inv->last_ack;
3265 
3266     /* Unlock dialog. */
3267     pjsip_dlg_dec_lock(inv->dlg);
3268 
3269     return PJ_SUCCESS;
3270 }
3271 
3272 /*
3273  * Send a request or response message.
3274  */
pjsip_inv_send_msg(pjsip_inv_session * inv,pjsip_tx_data * tdata)3275 PJ_DEF(pj_status_t) pjsip_inv_send_msg( pjsip_inv_session *inv,
3276 					pjsip_tx_data *tdata)
3277 {
3278     pj_status_t status;
3279 
3280     /* Verify arguments. */
3281     PJ_ASSERT_RETURN(inv && tdata, PJ_EINVAL);
3282 
3283     pj_log_push_indent();
3284 
3285     PJ_LOG(5,(inv->obj_name, "Sending %s",
3286 	      pjsip_tx_data_get_info(tdata)));
3287 
3288     if (tdata->msg->type == PJSIP_REQUEST_MSG) {
3289 	struct tsx_inv_data *tsx_inv_data;
3290 
3291 	pjsip_dlg_inc_lock(inv->dlg);
3292 
3293 	/* Check again that we didn't receive incoming re-INVITE */
3294 	if (tdata->msg->line.req.method.id==PJSIP_INVITE_METHOD &&
3295 	    inv->invite_tsx)
3296 	{
3297 	    pjsip_tx_data_dec_ref(tdata);
3298 	    pjsip_dlg_dec_lock(inv->dlg);
3299 	    status = PJ_EINVALIDOP;
3300 	    goto on_error;
3301 	}
3302 
3303 	/* Don't send BYE before ACK is received
3304 	 * http://trac.pjsip.org/repos/ticket/1712
3305 	 */
3306 	if (tdata->msg->line.req.method.id == PJSIP_BYE_METHOD &&
3307 	    inv->role == PJSIP_ROLE_UAS &&
3308 	    inv->state == PJSIP_INV_STATE_CONNECTING &&
3309 	    inv->cause != PJSIP_SC_REQUEST_TIMEOUT &&
3310 	    inv->cause != PJSIP_SC_TSX_TRANSPORT_ERROR)
3311 	{
3312 	    if (inv->pending_bye)
3313 		pjsip_tx_data_dec_ref(inv->pending_bye);
3314 
3315 	    inv->pending_bye = tdata;
3316 	    PJ_LOG(4, (inv->obj_name, "Delaying BYE request until "
3317 		       "ACK is received"));
3318 	    pjsip_dlg_dec_lock(inv->dlg);
3319 	    goto on_return;
3320 	}
3321 
3322 	/* Associate our data in outgoing invite transaction */
3323 	tsx_inv_data = PJ_POOL_ZALLOC_T(inv->pool, struct tsx_inv_data);
3324 	tsx_inv_data->inv = inv;
3325 	tsx_inv_data->has_sdp = tx_data_has_sdp(tdata);
3326 
3327 	pjsip_dlg_dec_lock(inv->dlg);
3328 
3329 	status = pjsip_dlg_send_request(inv->dlg, tdata, mod_inv.mod.id,
3330 					tsx_inv_data);
3331 	if (status != PJ_SUCCESS) {
3332 	    goto on_error;
3333 	}
3334 
3335 	/* Check if this is delayed manual ACK (see #416) */
3336 	if (mod_inv.cb.on_send_ack &&
3337 	    tdata->msg->line.req.method.id == PJSIP_ACK_METHOD &&
3338 	    tdata == inv->last_ack)
3339 	{
3340 	    pjsip_dlg_inc_lock(inv->dlg);
3341 
3342 	    /* Set state to CONFIRMED (if we're not in CONFIRMED yet).
3343 	     * But don't set it to CONFIRMED if we're already DISCONNECTED
3344 	     * (this may have been a late 200/OK response.
3345 	     */
3346 	    if (inv->state < PJSIP_INV_STATE_CONFIRMED) {
3347 		pjsip_event ack_e;
3348 		PJSIP_EVENT_INIT_TX_MSG(ack_e, inv->last_ack);
3349 		inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, &ack_e);
3350 	    } else if (inv->state == PJSIP_INV_STATE_DISCONNECTED) {
3351 		/* Avoid possible leaked tdata when invite session is
3352 		 * already destroyed.
3353 		 * https://github.com/pjsip/pjproject/pull/2432
3354 		 */
3355 		pjsip_tx_data_dec_ref(inv->last_ack);
3356 		inv->last_ack = NULL;
3357 	    }
3358 
3359 	    pjsip_dlg_dec_lock(inv->dlg);
3360 	}
3361 
3362     } else {
3363 	pjsip_cseq_hdr *cseq;
3364 
3365 	/* Can only do this to send response to original INVITE
3366 	 * request.
3367 	 */
3368 	PJ_ASSERT_RETURN((cseq=(pjsip_cseq_hdr*)pjsip_msg_find_hdr(tdata->msg, PJSIP_H_CSEQ, NULL))!=NULL
3369 			  && (cseq->cseq == inv->invite_tsx->cseq),
3370 			 PJ_EINVALIDOP);
3371 
3372 	if (inv->options & PJSIP_INV_REQUIRE_100REL) {
3373 	    status = pjsip_100rel_tx_response(inv, tdata);
3374 	} else
3375 	{
3376 	    status = pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata);
3377 	}
3378 
3379 	if (status != PJ_SUCCESS) {
3380 	    goto on_error;
3381 	}
3382     }
3383 
3384     /* Done */
3385 on_return:
3386     pj_log_pop_indent();
3387     return PJ_SUCCESS;
3388 
3389 on_error:
3390     pj_log_pop_indent();
3391     return status;
3392 }
3393 
3394 
3395 /*
3396  * Respond to incoming CANCEL request.
3397  */
inv_respond_incoming_cancel(pjsip_inv_session * inv,pjsip_transaction * cancel_tsx,pjsip_event * e)3398 static void inv_respond_incoming_cancel(pjsip_inv_session *inv,
3399 					pjsip_transaction *cancel_tsx,
3400 					pjsip_event *e)
3401 {
3402     pjsip_tx_data *tdata;
3403     pjsip_transaction *invite_tsx;
3404     pjsip_rx_data *rdata;
3405     pj_str_t key;
3406     pj_status_t status;
3407 
3408     pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
3409     rdata = e->body.tsx_state.src.rdata;
3410 
3411     /* https://trac.pjsip.org/repos/ticket/1651
3412      * Special treatment for CANCEL. Since here we're responding to CANCEL
3413      * automatically (including 487 to INVITE), application will see the
3414      * 200/OK response to CANCEL first in the callback, and then 487 to
3415      * INVITE, before the CANCEL request itself. And worse, pjsua application
3416      * may not see the CANCEL request at all because by the time the CANCEL
3417      * request is reported, call has been disconnected and further events
3418      * from the INVITE session has been suppressed.
3419      */
3420     if (mod_inv.cb.on_tsx_state_changed && inv->notify)
3421 	(*mod_inv.cb.on_tsx_state_changed)(inv, cancel_tsx, e);
3422 
3423     /* See if we have matching INVITE server transaction: */
3424 
3425     pjsip_tsx_create_key(rdata->tp_info.pool, &key, PJSIP_ROLE_UAS,
3426 			 pjsip_get_invite_method(), rdata);
3427     invite_tsx = pjsip_tsx_layer_find_tsx2(&key, PJ_TRUE);
3428 
3429     if (invite_tsx == NULL) {
3430 
3431 	/* Invite transaction not found!
3432 	 * Respond CANCEL with 481 (RFC 3261 Section 9.2 page 55)
3433 	 */
3434 	status = pjsip_dlg_create_response( inv->dlg, rdata, 481, NULL,
3435 					    &tdata);
3436 
3437     } else {
3438 	/* Always answer CANCEL will 200 (OK) regardless of
3439 	 * the state of the INVITE transaction.
3440 	 */
3441 	status = pjsip_dlg_create_response( inv->dlg, rdata, 200, NULL,
3442 					    &tdata);
3443     }
3444 
3445     /* See if we have created the response successfully. */
3446     if (status != PJ_SUCCESS) return;
3447 
3448     /* Send the CANCEL response */
3449     status = pjsip_dlg_send_response(inv->dlg, cancel_tsx, tdata);
3450     if (status != PJ_SUCCESS) return;
3451 
3452 
3453     /* See if we need to terminate the UAS INVITE transaction
3454      * with 487 (Request Terminated) response.
3455      */
3456     if (invite_tsx && invite_tsx->status_code < 200) {
3457 
3458 	pj_assert(invite_tsx->last_tx != NULL);
3459 
3460 	tdata = invite_tsx->last_tx;
3461 
3462 	status = pjsip_dlg_modify_response(inv->dlg, tdata, 487, NULL);
3463 	if (status == PJ_SUCCESS) {
3464 	    /* Remove the message body */
3465 	    tdata->msg->body = NULL;
3466 	    if (inv->options & PJSIP_INV_REQUIRE_100REL) {
3467 		status = pjsip_100rel_tx_response(inv, tdata);
3468 	    } else {
3469 		status = pjsip_dlg_send_response(inv->dlg, invite_tsx,
3470 						 tdata);
3471 	    }
3472 	}
3473     }
3474 
3475     if (invite_tsx)
3476 	pj_grp_lock_dec_ref(invite_tsx->grp_lock);
3477 }
3478 
3479 
3480 /*
3481  * Respond to incoming BYE request.
3482  */
inv_respond_incoming_bye(pjsip_inv_session * inv,pjsip_transaction * bye_tsx,pjsip_rx_data * rdata,pjsip_event * e)3483 static void inv_respond_incoming_bye( pjsip_inv_session *inv,
3484 				      pjsip_transaction *bye_tsx,
3485 				      pjsip_rx_data *rdata,
3486 				      pjsip_event *e )
3487 {
3488     pj_status_t status;
3489     pjsip_tx_data *tdata;
3490 
3491     /* Respond BYE with 200: */
3492 
3493     status = pjsip_dlg_create_response(inv->dlg, rdata, 200, NULL, &tdata);
3494     if (status != PJ_SUCCESS) return;
3495 
3496     status = pjsip_dlg_send_response(inv->dlg, bye_tsx, tdata);
3497     if (status != PJ_SUCCESS) return;
3498 
3499     /* Terminate session: */
3500 
3501     if (inv->state != PJSIP_INV_STATE_DISCONNECTED) {
3502 	inv_set_cause(inv, PJSIP_SC_OK, NULL);
3503 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
3504     }
3505 }
3506 
3507 /*
3508  * Respond to BYE request.
3509  */
inv_handle_bye_response(pjsip_inv_session * inv,pjsip_transaction * tsx,pjsip_rx_data * rdata,pjsip_event * e)3510 static void inv_handle_bye_response( pjsip_inv_session *inv,
3511 				     pjsip_transaction *tsx,
3512 				     pjsip_rx_data *rdata,
3513 				     pjsip_event *e )
3514 {
3515     pj_status_t status;
3516 
3517     if (e->body.tsx_state.type != PJSIP_EVENT_RX_MSG) {
3518 	inv_set_cause(inv, PJSIP_SC_OK, NULL);
3519 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
3520 	return;
3521     }
3522 
3523     /* Handle 401/407 challenge. */
3524     if (tsx->status_code == 401 || tsx->status_code == 407) {
3525 
3526 	pjsip_tx_data *tdata;
3527 
3528 	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess,
3529 					    rdata,
3530 					    tsx->last_tx,
3531 					    &tdata);
3532 
3533 	if (status != PJ_SUCCESS) {
3534 
3535 	    /* Does not have proper credentials.
3536 	     * End the session anyway.
3537 	     */
3538 	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
3539 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
3540 
3541 	} else {
3542 	    struct tsx_inv_data *tsx_inv_data;
3543 
3544 	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
3545 	    if (tsx_inv_data)
3546 		tsx_inv_data->retrying = PJ_TRUE;
3547 
3548 	    /* Re-send BYE. */
3549 	    status = pjsip_inv_send_msg(inv, tdata);
3550 	}
3551 
3552     } else {
3553 
3554 	/* End the session. */
3555 	inv_set_cause(inv, PJSIP_SC_OK, NULL);
3556 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
3557     }
3558 
3559 }
3560 
3561 /*
3562  * Respond to incoming UPDATE request.
3563  */
inv_respond_incoming_update(pjsip_inv_session * inv,pjsip_event * e)3564 static void inv_respond_incoming_update(pjsip_inv_session *inv,
3565 					pjsip_event *e)
3566 {
3567     pjmedia_sdp_neg_state neg_state;
3568     pj_status_t status;
3569     pjsip_tx_data *tdata = NULL;
3570     pjsip_rx_data *rdata;
3571     pjsip_status_code st_code;
3572 
3573     pj_assert(e->type == PJSIP_EVENT_TSX_STATE &&
3574 	      e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
3575     rdata = e->body.tsx_state.src.rdata;
3576 
3577     /* Check routing URI scheme for secure dialog */
3578     if (!inv_check_secure_dlg(inv, e))
3579 	return;
3580 
3581     /* Invoke Session Timers module */
3582     status = pjsip_timer_process_req(inv, rdata, &st_code);
3583     if (status != PJ_SUCCESS) {
3584 	status = pjsip_dlg_create_response(inv->dlg, rdata, st_code,
3585 					   NULL, &tdata);
3586 	goto on_return;
3587     }
3588 
3589     neg_state = pjmedia_sdp_neg_get_state(inv->neg);
3590 
3591     /* If UPDATE doesn't contain SDP, just respond with 200/OK.
3592      * This is a valid scenario according to session-timer draft.
3593      */
3594     if (rdata->msg_info.msg->body == NULL) {
3595 
3596 	status = pjsip_dlg_create_response(inv->dlg, rdata,
3597 					   200, NULL, &tdata);
3598     }
3599     /* Send 491 if we receive UPDATE while we're waiting for an answer */
3600     else if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER) {
3601 	status = pjsip_dlg_create_response(inv->dlg, rdata,
3602 					   PJSIP_SC_REQUEST_PENDING, NULL,
3603 					   &tdata);
3604     }
3605     /* Send 500 with Retry-After header set randomly between 0 and 10 if we
3606      * receive UPDATE while we haven't sent answer.
3607      */
3608     else if (neg_state == PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER ||
3609 	     neg_state == PJMEDIA_SDP_NEG_STATE_WAIT_NEGO)
3610     {
3611         pjsip_retry_after_hdr *ra_hdr;
3612 	int val;
3613 
3614         status = pjsip_dlg_create_response(inv->dlg, rdata,
3615 					   PJSIP_SC_INTERNAL_SERVER_ERROR,
3616 					   NULL, &tdata);
3617 
3618         val = (pj_rand() % 10);
3619         ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val);
3620         pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr);
3621 
3622     } else {
3623 	/* We receive new offer from remote */
3624 	inv_check_sdp_in_incoming_msg(inv, pjsip_rdata_get_tsx(rdata), rdata);
3625 
3626 	/* Application MUST have supplied the answer by now.
3627 	 * If so, negotiate the SDP.
3628 	 */
3629 	neg_state = pjmedia_sdp_neg_get_state(inv->neg);
3630 	if (neg_state != PJMEDIA_SDP_NEG_STATE_WAIT_NEGO ||
3631 	    (status=inv_negotiate_sdp(inv)) != PJ_SUCCESS)
3632 	{
3633 	    /* Negotiation has failed. If negotiator is still
3634 	     * stuck at non-DONE state, cancel any ongoing offer.
3635 	     */
3636 	    neg_state = pjmedia_sdp_neg_get_state(inv->neg);
3637 	    if (neg_state != PJMEDIA_SDP_NEG_STATE_DONE) {
3638 		pjmedia_sdp_neg_cancel_offer(inv->neg);
3639 	    }
3640 
3641 	    status = pjsip_dlg_create_response(inv->dlg, rdata,
3642 					       PJSIP_SC_NOT_ACCEPTABLE_HERE,
3643 					       NULL, &tdata);
3644 	} else {
3645 	    /* New media has been negotiated successfully, send 200/OK */
3646 	    status = pjsip_dlg_create_response(inv->dlg, rdata,
3647 					       PJSIP_SC_OK, NULL, &tdata);
3648 	    if (status == PJ_SUCCESS) {
3649 		const pjmedia_sdp_session *sdp;
3650 		status = pjmedia_sdp_neg_get_active_local(inv->neg, &sdp);
3651 		if (status == PJ_SUCCESS)
3652 		    tdata->msg->body = create_sdp_body(tdata->pool, sdp);
3653 	    }
3654 	}
3655     }
3656 
3657 on_return:
3658     /* Invoke Session Timers */
3659     if (status == PJ_SUCCESS)
3660 	status = pjsip_timer_update_resp(inv, tdata);
3661 
3662     if (status != PJ_SUCCESS) {
3663 	if (tdata != NULL) {
3664 	    pjsip_tx_data_dec_ref(tdata);
3665 	    tdata = NULL;
3666 	}
3667 	return;
3668     }
3669 
3670     pjsip_dlg_send_response(inv->dlg, pjsip_rdata_get_tsx(rdata), tdata);
3671 }
3672 
3673 
3674 /*
3675  * Handle incoming response to UAC UPDATE request.
3676  */
inv_handle_update_response(pjsip_inv_session * inv,pjsip_event * e)3677 static pj_bool_t inv_handle_update_response( pjsip_inv_session *inv,
3678                                              pjsip_event *e)
3679 {
3680     pjsip_transaction *tsx = e->body.tsx_state.tsx;
3681     struct tsx_inv_data *tsx_inv_data;
3682     pj_bool_t handled = PJ_FALSE;
3683     pj_status_t status = -1;
3684 
3685     tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
3686     pj_assert(tsx_inv_data);
3687 
3688     /* Handle 401/407 challenge. */
3689     if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
3690 	(tsx->status_code == 401 || tsx->status_code == 407))
3691     {
3692 	pjsip_tx_data *tdata;
3693 
3694 	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess,
3695 					    e->body.tsx_state.src.rdata,
3696 					    tsx->last_tx,
3697 					    &tdata);
3698 
3699 	if (status != PJ_SUCCESS) {
3700 
3701 	    /* Somehow failed. Probably it's not a good idea to terminate
3702 	     * the session since this is just a request within dialog. And
3703 	     * even if we terminate we should send BYE.
3704 	     */
3705 	    /*
3706 	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
3707 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
3708 	    */
3709 
3710 	} else {
3711 	    if (tsx_inv_data)
3712 		tsx_inv_data->retrying = PJ_TRUE;
3713 
3714 	    /* Re-send request. */
3715 	    status = pjsip_inv_send_msg(inv, tdata);
3716 	}
3717 
3718 	handled = PJ_TRUE;
3719     }
3720 
3721     /* Process 422 response */
3722     else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
3723 	     tsx->status_code == 422)
3724     {
3725 	status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
3726 				       PJ_FALSE);
3727 	handled = PJ_TRUE;
3728     }
3729 
3730     /* Process 2xx response */
3731     else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
3732 	tsx->status_code/100 == 2)
3733     {
3734 	pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
3735 
3736 	/* Check routing URI scheme for secure dialog */
3737 	if (inv_check_secure_dlg(inv, e)) {
3738 
3739 	    status = handle_timer_response(inv, rdata, PJ_FALSE);
3740 
3741 	    if (rdata->msg_info.msg->body) {
3742 		/* Only process remote SDP if we have sent local offer */
3743 		if (inv->neg && pjmedia_sdp_neg_get_state(inv->neg) ==
3744 					    PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
3745 		{
3746 		    status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata);
3747 		} else {
3748 		    PJ_LOG(5,(THIS_FILE, "Ignored message body in %s as no "
3749 					 "local offer was sent",
3750 					 pjsip_rx_data_get_info(rdata)));
3751 		}
3752 	    }
3753 	}
3754 
3755         handled = PJ_TRUE;
3756     }
3757 
3758     /* Process 502/503 error */
3759     else if ((tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
3760 	     (tsx->status_code == 503 || tsx->status_code == 502))
3761     {
3762 	status = pjsip_timer_handle_refresh_error(inv, e);
3763 
3764 	handled = PJ_TRUE;
3765     }
3766 
3767     /* Get/attach invite session's transaction data */
3768     else
3769     {
3770 	/* Session-Timer needs to see any error responses, to determine
3771 	 * whether peer supports UPDATE with empty body.
3772 	 */
3773 	if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
3774 	    tsx->role == PJSIP_ROLE_UAC)
3775 	{
3776 	    status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
3777 					   PJ_FALSE);
3778 	    handled = PJ_TRUE;
3779 	}
3780     }
3781 
3782     /* Cancel the negotiation if we don't get successful negotiation by now,
3783      * unless it's authentication challenge and the request is being retried.
3784      */
3785     if (pjmedia_sdp_neg_get_state(inv->neg) ==
3786 		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
3787 	tsx_inv_data && tsx_inv_data->sdp_done == PJ_FALSE &&
3788 	!tsx_inv_data->retrying && tsx_inv_data->has_sdp)
3789     {
3790 	pjmedia_sdp_neg_cancel_offer(inv->neg);
3791 
3792 	/* Prevent from us cancelling different offer! */
3793 	tsx_inv_data->sdp_done = PJ_TRUE;
3794     }
3795 
3796     return handled;
3797 }
3798 
3799 
3800 /*
3801  * Handle incoming reliable response.
3802  */
inv_handle_incoming_reliable_response(pjsip_inv_session * inv,pjsip_rx_data * rdata)3803 static void inv_handle_incoming_reliable_response(pjsip_inv_session *inv,
3804 						  pjsip_rx_data *rdata)
3805 {
3806     pjsip_tx_data *tdata;
3807     const pjmedia_sdp_session *sdp;
3808     pj_status_t status;
3809 
3810     /* Create PRACK */
3811     status = pjsip_100rel_create_prack(inv, rdata, &tdata);
3812     if (status != PJ_SUCCESS)
3813 	return;
3814 
3815     /* See if we need to attach SDP answer on the PRACK request */
3816     sdp = inv_has_pending_answer(inv, pjsip_rdata_get_tsx(rdata));
3817     if (sdp) {
3818 	tdata->msg->body = create_sdp_body(tdata->pool, sdp);
3819     }
3820 
3821     /* Send PRACK (must be using 100rel module!) */
3822     pjsip_100rel_send_prack(inv, tdata);
3823 }
3824 
3825 
3826 /*
3827  * Handle incoming PRACK.
3828  */
inv_respond_incoming_prack(pjsip_inv_session * inv,pjsip_rx_data * rdata)3829 static void inv_respond_incoming_prack(pjsip_inv_session *inv,
3830 				       pjsip_rx_data *rdata)
3831 {
3832     pj_status_t status;
3833 
3834     /* Run through 100rel module to see if we can accept this
3835      * PRACK request. The 100rel will send 200/OK to PRACK request.
3836      */
3837     status = pjsip_100rel_on_rx_prack(inv, rdata);
3838     if (status != PJ_SUCCESS)
3839 	return;
3840 
3841     /* Now check for SDP answer in the PRACK request */
3842     if (rdata->msg_info.msg->body) {
3843 	status = inv_check_sdp_in_incoming_msg(inv,
3844 					pjsip_rdata_get_tsx(rdata), rdata);
3845     } else {
3846 	/* No SDP body */
3847 	status = -1;
3848     }
3849 
3850     /* If SDP negotiation has been successful, also mark the
3851      * SDP negotiation flag in the invite transaction to be
3852      * done too.
3853      */
3854     if (status == PJ_SUCCESS && inv->invite_tsx) {
3855 	struct tsx_inv_data *tsx_inv_data;
3856 
3857 	/* Get/attach invite session's transaction data */
3858 	tsx_inv_data = (struct tsx_inv_data*)
3859 		       inv->invite_tsx->mod_data[mod_inv.mod.id];
3860 	if (tsx_inv_data == NULL) {
3861 	    tsx_inv_data = PJ_POOL_ZALLOC_T(inv->invite_tsx->pool,
3862 					    struct tsx_inv_data);
3863 	    tsx_inv_data->inv = inv;
3864 	    tsx_inv_data->has_sdp = PJ_TRUE;
3865 	    inv->invite_tsx->mod_data[mod_inv.mod.id] = tsx_inv_data;
3866 	}
3867 
3868 	tsx_inv_data->sdp_done = PJ_TRUE;
3869     }
3870 }
3871 
3872 
3873 /* Ticket #1735: If this is a secure dialog, make sure that any incoming
3874  * initial/subsequent INVITE/UPDATE request or the 2xx response to INVITE/
3875  * UPDATE specifies secure Contact and Record-Route headers.
3876  */
inv_check_secure_dlg(pjsip_inv_session * inv,pjsip_event * e)3877 static pj_bool_t inv_check_secure_dlg(pjsip_inv_session *inv,
3878 				      pjsip_event *e)
3879 {
3880     pjsip_transaction *tsx = e->body.tsx_state.tsx;
3881     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
3882 
3883     if (pjsip_cfg()->endpt.disable_secure_dlg_check == PJ_FALSE &&
3884 	dlg->secure && e->body.tsx_state.type==PJSIP_EVENT_RX_MSG &&
3885 	((tsx->role==PJSIP_ROLE_UAC && tsx->status_code/100 == 2) ||
3886 	 (tsx->role==PJSIP_ROLE_UAS && tsx->state == PJSIP_TSX_STATE_TRYING))
3887 	&&
3888 	(tsx->method.id==PJSIP_INVITE_METHOD ||
3889 	 pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0))
3890     {
3891 	const pjsip_msg *msg = e->body.tsx_state.src.rdata->msg_info.msg;
3892 	pj_status_t status = PJ_SUCCESS;
3893 	pjsip_contact_hdr *c;
3894 
3895 	/* Check Contact header */
3896 	c = (pjsip_contact_hdr*)
3897 	    pjsip_msg_find_hdr(msg,PJSIP_H_CONTACT, NULL);
3898 	if (!(c && c->uri && PJSIP_URI_SCHEME_IS_SIPS(c->uri)))
3899 	    status = PJSIP_ESESSIONINSECURE;
3900 
3901 	/* Check top Record-Route header */
3902 	if (status == PJ_SUCCESS) {
3903 	    pjsip_rr_hdr *r = (pjsip_rr_hdr*)
3904 			      pjsip_msg_find_hdr(msg, PJSIP_H_RECORD_ROUTE,
3905 						 NULL);
3906 	    if (r && !PJSIP_URI_SCHEME_IS_SIPS(&r->name_addr)) {
3907 		/* Not "sips", check if it is "sip" and has param
3908 		 * "transport=tls".
3909 		 */
3910 		if (PJSIP_URI_SCHEME_IS_SIP(&r->name_addr)) {
3911 		    pjsip_sip_uri *sip_uri = (pjsip_sip_uri*)
3912 				     pjsip_uri_get_uri(r->name_addr.uri);
3913 		    if (pj_stricmp2(&sip_uri->transport_param, "tls")!=0)
3914 			status = PJSIP_ESESSIONINSECURE;
3915 		} else {
3916 		    /* Not "sips" nor "sip", treat it as insecure? */
3917 		    status = PJSIP_ESESSIONINSECURE;
3918 		}
3919 	    }
3920 	}
3921 
3922 	if (status == PJSIP_ESESSIONINSECURE) {
3923 	    /* Found non-SIPS scheme in Contact/Record-Route header */
3924 
3925 	    pj_str_t warn_text = pj_str("SIPS Required");
3926 
3927 	    if (tsx->role == PJSIP_ROLE_UAC) {
3928 
3929 		/* If we are UAC, terminate the session */
3930 		pjsip_tx_data *bye;
3931 
3932 		PJ_LOG(4,(inv->obj_name,
3933 			  "Secure dialog requires SIPS scheme in Contact and "
3934 			  "Record-Route headers, ending the session"));
3935 
3936 		status = pjsip_inv_end_session(inv, 480, NULL, &bye);
3937 		if (status == PJ_SUCCESS && bye) {
3938 		    pjsip_warning_hdr *w;
3939 		    w = pjsip_warning_hdr_create(bye->pool, 381,
3940 						 pjsip_endpt_name(dlg->endpt),
3941 						 &warn_text);
3942 		    if (w)
3943 			pjsip_msg_add_hdr(bye->msg, (pjsip_hdr*)w);
3944 
3945 		    status = pjsip_inv_send_msg(inv, bye);
3946 		}
3947 
3948 	    } else {
3949 
3950 		/* If we are UAS, reject the request */
3951 		pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
3952 		pjsip_tx_data *tdata;
3953 
3954 		PJ_LOG(4,(inv->obj_name,
3955 			  "Secure dialog requires SIPS scheme in Contact and "
3956 			  "Route headers, rejecting the request"));
3957 
3958 		status = pjsip_dlg_create_response(inv->dlg, rdata, 480,
3959 						   NULL, &tdata);
3960 		if (status == PJ_SUCCESS) {
3961 		    pjsip_warning_hdr *w;
3962 		    w = pjsip_warning_hdr_create(tdata->pool, 381,
3963 						 pjsip_endpt_name(dlg->endpt),
3964 						 &warn_text);
3965 		    if (w)
3966 			pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w);
3967 
3968 		    pjsip_dlg_send_response(dlg, tsx, tdata);
3969 		}
3970 
3971 	    }
3972 
3973     	    return PJ_FALSE;
3974 	}
3975     }
3976 
3977     return PJ_TRUE;
3978 }
3979 
3980 
3981 
3982 /*
3983  * State NULL is before anything is sent/received.
3984  */
inv_on_state_null(pjsip_inv_session * inv,pjsip_event * e)3985 static void inv_on_state_null( pjsip_inv_session *inv, pjsip_event *e)
3986 {
3987     pjsip_transaction *tsx = e->body.tsx_state.tsx;
3988     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
3989 
3990     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
3991 
3992     if (tsx->method.id == PJSIP_INVITE_METHOD) {
3993 
3994 	/* Keep the initial INVITE transaction. */
3995 	if (inv->invite_tsx == NULL)
3996 	    inv->invite_tsx = tsx;
3997 
3998 	if (dlg->role == PJSIP_ROLE_UAC) {
3999 
4000 	    /* Save the original INVITE request.
4001              * We may need to resend the INVITE if we receive redirection
4002              * or session timer too small response.
4003 	     */
4004 	    if (1) {
4005 		if (inv->invite_req) {
4006 		    pjsip_tx_data_dec_ref(inv->invite_req);
4007 		    inv->invite_req = NULL;
4008 		}
4009 		inv->invite_req = tsx->last_tx;
4010 		pjsip_tx_data_add_ref(inv->invite_req);
4011 	    }
4012 
4013 	    switch (tsx->state) {
4014 	    case PJSIP_TSX_STATE_CALLING:
4015 		inv_set_state(inv, PJSIP_INV_STATE_CALLING, e);
4016 		break;
4017 	    default:
4018 		inv_on_state_calling(inv, e);
4019 		break;
4020 	    }
4021 
4022 	} else {
4023 	    switch (tsx->state) {
4024 	    case PJSIP_TSX_STATE_TRYING:
4025 		inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
4026 		break;
4027 	    case PJSIP_TSX_STATE_PROCEEDING:
4028 		inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
4029 		if (tsx->status_code > 100)
4030 		    inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
4031 		break;
4032 	    case PJSIP_TSX_STATE_TERMINATED:
4033 		/* there is a failure in sending response. */
4034 		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4035 		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4036 		break;
4037 	    default:
4038 		inv_on_state_incoming(inv, e);
4039 		break;
4040 	    }
4041 	}
4042 
4043     } else {
4044 	pj_assert(!"Unexpected transaction type");
4045     }
4046 }
4047 
4048 /*
4049  * Generic UAC transaction handler:
4050  *  - resend request on 401 or 407 response.
4051  *  - terminate dialog on 408 and 481 response.
4052  *  - resend request on 422 response.
4053  */
handle_uac_tsx_response(pjsip_inv_session * inv,pjsip_event * e)4054 static pj_bool_t handle_uac_tsx_response(pjsip_inv_session *inv,
4055 					 pjsip_event *e)
4056 {
4057     /* RFC 3261 Section 12.2.1.2:
4058      *  If the response for a request within a dialog is a 481
4059      *  (Call/Transaction Does Not Exist) or a 408 (Request Timeout), the UAC
4060      *  SHOULD terminate the dialog.  A UAC SHOULD also terminate a dialog if
4061      *  no response at all is received for the request (the client
4062      *  transaction would inform the TU about the timeout.)
4063      *
4064      *  For INVITE initiated dialogs, terminating the dialog consists of
4065      *  sending a BYE.
4066      *
4067      * Note:
4068      *  according to X, this should terminate dialog usage only, not the
4069      *  dialog.
4070      */
4071     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4072 
4073     pj_assert(tsx->role == PJSIP_UAC_ROLE);
4074 
4075     /* Note that 481 response to CANCEL does not terminate dialog usage,
4076      * but only the transaction.
4077      */
4078     if (inv->state != PJSIP_INV_STATE_DISCONNECTED &&
4079 	((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST &&
4080 	    tsx->method.id != PJSIP_CANCEL_METHOD) ||
4081 	 tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT ||
4082 	 tsx->status_code == PJSIP_SC_TSX_TIMEOUT))
4083     {
4084 	pjsip_tx_data *bye;
4085 	pj_status_t status;
4086 
4087 	inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4088 	inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4089 
4090 	/* Send BYE */
4091 	status = pjsip_dlg_create_request(inv->dlg, pjsip_get_bye_method(),
4092 					  -1, &bye);
4093 	if (status == PJ_SUCCESS) {
4094 	    pjsip_inv_send_msg(inv, bye);
4095 	}
4096 
4097 	return PJ_TRUE; /* Handled */
4098 
4099     }
4100     /* Handle 401/407 challenge. */
4101     else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
4102 	     (tsx->status_code == PJSIP_SC_UNAUTHORIZED ||
4103 	      tsx->status_code == PJSIP_SC_PROXY_AUTHENTICATION_REQUIRED))
4104     {
4105 	pjsip_tx_data *tdata;
4106 	pj_status_t status;
4107 
4108 	if (tsx->method.id == PJSIP_INVITE_METHOD)
4109 	    inv->invite_tsx = NULL;
4110 
4111 	status = pjsip_auth_clt_reinit_req( &inv->dlg->auth_sess,
4112 					    e->body.tsx_state.src.rdata,
4113 					    tsx->last_tx, &tdata);
4114 
4115 	if (status != PJ_SUCCESS) {
4116 	    /* Somehow failed. Probably it's not a good idea to terminate
4117 	     * the session since this is just a request within dialog. And
4118 	     * even if we terminate we should send BYE.
4119 	     */
4120 	    /*
4121 	    inv_set_cause(inv, PJSIP_SC_OK, NULL);
4122 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4123 	    */
4124 
4125 	} else {
4126 	    struct tsx_inv_data *tsx_inv_data;
4127 
4128 	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
4129 	    if (tsx_inv_data)
4130 		tsx_inv_data->retrying = PJ_TRUE;
4131 
4132 	    /* Re-send request. */
4133 	    status = pjsip_inv_send_msg(inv, tdata);
4134 	}
4135 
4136 	return PJ_TRUE;	/* Handled */
4137     }
4138 
4139     /* Handle session timer 422 response. */
4140     else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
4141 	     tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL)
4142     {
4143 	handle_timer_response(inv, e->body.tsx_state.src.rdata,
4144 			      PJ_FALSE);
4145 
4146 	return PJ_TRUE;	/* Handled */
4147 
4148     }
4149 
4150     else {
4151 	return PJ_FALSE; /* Unhandled */
4152     }
4153 }
4154 
4155 
4156 /* Handle call rejection, especially with regard to processing call
4157  * redirection. We need to handle the following scenarios:
4158  *  - 3xx response is received -- see if on_redirected() callback is
4159  *    implemented. If so, add the Contact URIs in the response to the
4160  *    target set and notify user.
4161  *  - 4xx - 6xx resposne is received -- see if we're currently recursing,
4162  *    if so fetch the next target if any and notify the on_redirected()
4163  *    callback.
4164  *  - for other cases -- disconnect the session.
4165  */
handle_uac_call_rejection(pjsip_inv_session * inv,pjsip_event * e)4166 static void handle_uac_call_rejection(pjsip_inv_session *inv, pjsip_event *e)
4167 {
4168     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4169     pj_status_t status;
4170 
4171     if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 300)) {
4172 
4173 	if (mod_inv.cb.on_redirected == NULL) {
4174 
4175 	    /* Redirection callback is not implemented, disconnect the
4176 	     * call.
4177 	     */
4178 	    goto terminate_session;
4179 
4180 	} else {
4181 	    const pjsip_msg *res_msg;
4182 
4183 	    res_msg = e->body.tsx_state.src.rdata->msg_info.msg;
4184 
4185 	    /* Gather all Contact URI's in the response and add them
4186 	     * to target set. The function will take care of removing
4187 	     * duplicate URI's.
4188 	     */
4189 	    pjsip_target_set_add_from_msg(&inv->dlg->target_set,
4190 					  inv->dlg->pool, res_msg);
4191 
4192 	    /* Recurse to alternate targets if application allows us */
4193 	    if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e))
4194 	    {
4195 		/* Recursion fails, terminate session now */
4196 		goto terminate_session;
4197 	    }
4198 
4199 	    /* Done */
4200 	}
4201 
4202     } else if ((tsx->status_code==401 || tsx->status_code==407) &&
4203 		!inv->cancelling)
4204     {
4205 
4206 	/* Handle authentication failure:
4207 	 * Resend the request with Authorization header.
4208 	 */
4209 	pjsip_tx_data *tdata;
4210 
4211 	status = pjsip_auth_clt_reinit_req(&inv->dlg->auth_sess,
4212 					   e->body.tsx_state.src.rdata,
4213 					   tsx->last_tx,
4214 					   &tdata);
4215 
4216 	if (status != PJ_SUCCESS) {
4217 
4218 	    /* Does not have proper credentials. If we are currently
4219 	     * recursing, try the next target. Otherwise end the session.
4220 	     */
4221 	    if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e))
4222 	    {
4223 		/* Recursion fails, terminate session now */
4224 		goto terminate_session;
4225 	    }
4226 
4227 	} else {
4228 
4229 	    /* Restart session. */
4230 	    pjsip_inv_uac_restart(inv, PJ_FALSE);
4231 
4232 	    /* Send the request. */
4233 	    status = pjsip_inv_send_msg(inv, tdata);
4234 	}
4235 
4236     } else if (tsx->state == PJSIP_TSX_STATE_COMPLETED &&
4237 	       tsx->status_code == PJSIP_SC_SESSION_TIMER_TOO_SMALL)
4238     {
4239 	/* Handle session timer 422 response:
4240 	 * Resend the request with requested session timer setting.
4241 	 */
4242 	status = handle_timer_response(inv, e->body.tsx_state.src.rdata,
4243 				       PJ_FALSE);
4244 	if (status != PJ_SUCCESS)
4245 	    goto terminate_session;
4246 
4247     } else if (PJSIP_IS_STATUS_IN_CLASS(tsx->status_code, 600)) {
4248 	/* Global error */
4249 	goto terminate_session;
4250 
4251     } else {
4252 	/* See if we have alternate target to try */
4253 	if (!inv_uac_recurse(inv, tsx->status_code, &tsx->status_text, e)) {
4254 	    /* Recursion fails, terminate session now */
4255 	    goto terminate_session;
4256 	}
4257     }
4258     return;
4259 
4260 terminate_session:
4261     inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4262     inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4263 }
4264 
4265 
4266 /*
4267  * State CALLING is after sending initial INVITE request but before
4268  * any response (with tag) is received.
4269  */
inv_on_state_calling(pjsip_inv_session * inv,pjsip_event * e)4270 static void inv_on_state_calling( pjsip_inv_session *inv, pjsip_event *e)
4271 {
4272     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4273     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4274     pj_status_t status;
4275 
4276     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
4277 
4278     if (tsx == inv->invite_tsx) {
4279 
4280 	switch (tsx->state) {
4281 
4282 	case PJSIP_TSX_STATE_CALLING:
4283 	    inv_set_state(inv, PJSIP_INV_STATE_CALLING, e);
4284 	    break;
4285 
4286 	case PJSIP_TSX_STATE_PROCEEDING:
4287 	    if (inv->pending_cancel) {
4288 		pjsip_tx_data *cancel;
4289 
4290 		inv->pending_cancel = PJ_FALSE;
4291 
4292 		status = pjsip_inv_end_session(inv, 487, NULL, &cancel);
4293 		if (status == PJ_SUCCESS && cancel)
4294 		    status = pjsip_inv_send_msg(inv, cancel);
4295 	    }
4296 
4297 	    if (tsx->status_code != 100) {
4298 
4299 		if (inv->role == PJSIP_ROLE_UAC) {
4300 		    pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
4301 		    pjsip_allow_hdr *allow = NULL;
4302 		    pjsip_msg *msg = rdata->msg_info.msg;
4303 
4304 		    if (msg) {
4305 			allow = (pjsip_allow_hdr*) pjsip_msg_find_hdr(msg,
4306                                  PJSIP_H_ALLOW, NULL);
4307 		    }
4308 		    if (allow) {
4309 			unsigned i;
4310 			const pj_str_t STR_UPDATE = { "UPDATE", 6 };
4311 
4312 			for (i=0; i<allow->count; ++i) {
4313 			    if (pj_stricmp(&allow->values[i], &STR_UPDATE)==0) {
4314 				/* UPDATE is present in Allow */
4315 				inv->options |= PJSIP_INV_SUPPORT_UPDATE;
4316 				break;
4317 			    }
4318 			}
4319 		    }
4320 		}
4321 
4322 		if (dlg->remote.info->tag.slen)
4323 		    inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
4324 
4325 		inv_check_sdp_in_incoming_msg(inv, tsx,
4326 					      e->body.tsx_state.src.rdata);
4327 
4328 		if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) {
4329 		    inv_handle_incoming_reliable_response(
4330 			inv, e->body.tsx_state.src.rdata);
4331 		}
4332 
4333 	    } else {
4334 		/* Ignore 100 (Trying) response, as it doesn't change
4335 		 * session state. It only ceases retransmissions.
4336 		 */
4337 	    }
4338 	    break;
4339 
4340 	case PJSIP_TSX_STATE_COMPLETED:
4341 	    if (tsx->status_code/100 == 2) {
4342 
4343 		/* This should not happen.
4344 		 * When transaction receives 2xx, it should be terminated
4345 		 */
4346 		pj_assert(0);
4347 
4348 		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
4349 
4350 		/* Check routing URI scheme for secure dialog */
4351 		if (!inv_check_secure_dlg(inv, e))
4352 		    break;
4353 
4354 		/* Process session timer response. */
4355 		status = handle_timer_response(inv,
4356 					       e->body.tsx_state.src.rdata,
4357 					       PJ_TRUE);
4358 		if (status != PJ_SUCCESS)
4359 		    break;
4360 
4361 		inv_check_sdp_in_incoming_msg(inv, tsx,
4362 					      e->body.tsx_state.src.rdata);
4363 
4364 	    } else {
4365 		handle_uac_call_rejection(inv, e);
4366 	    }
4367 	    break;
4368 
4369 	case PJSIP_TSX_STATE_TERMINATED:
4370 	    /* INVITE transaction can be terminated either because UAC
4371 	     * transaction received 2xx response or because of transport
4372 	     * error.
4373 	     */
4374 	    if (tsx->status_code/100 == 2) {
4375 		/* This must be receipt of 2xx response */
4376 		pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
4377 
4378 		/* Set state to CONNECTING */
4379 		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
4380 
4381 		/* Check routing URI scheme for secure dialog */
4382 		if (!inv_check_secure_dlg(inv, e))
4383 		    break;
4384 
4385 		/* Process session timer response. */
4386 		status = handle_timer_response(inv,
4387 					       e->body.tsx_state.src.rdata,
4388 					       PJ_TRUE);
4389 		if (status != PJ_SUCCESS)
4390 		    break;
4391 
4392 		inv_check_sdp_in_incoming_msg(inv, tsx,
4393 					      e->body.tsx_state.src.rdata);
4394 		/* Send ACK */
4395 		inv_send_ack(inv, e);
4396 
4397 	    } else  {
4398 		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4399 		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4400 	    }
4401 	    break;
4402 
4403 	default:
4404 	    break;
4405 	}
4406 
4407     } else if (tsx->role == PJSIP_ROLE_UAC) {
4408 	/*
4409 	 * Handle case when outgoing request is answered with 481 (Call/
4410 	 * Transaction Does Not Exist), 408, or when it's timed out. In these
4411 	 * cases, disconnect session (i.e. dialog usage only).
4412 	 * Note that 481 response to CANCEL does not terminate dialog usage,
4413 	 * but only the transaction.
4414 	 */
4415 	if ((tsx->status_code == PJSIP_SC_CALL_TSX_DOES_NOT_EXIST &&
4416 		tsx->method.id != PJSIP_CANCEL_METHOD) ||
4417 	    tsx->status_code == PJSIP_SC_REQUEST_TIMEOUT ||
4418 	    tsx->status_code == PJSIP_SC_TSX_TIMEOUT)
4419 	{
4420 	    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4421 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4422 	}
4423     } else if (tsx->role == PJSIP_ROLE_UAS &&
4424 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4425 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
4426     {
4427 	/*
4428 	 * Handle a very early UPDATE
4429 	 */
4430 	inv_respond_incoming_update(inv, e);
4431 
4432 
4433     }
4434 }
4435 
4436 /*
4437  * State INCOMING is after we received the request, but before
4438  * responses with tag are sent.
4439  */
inv_on_state_incoming(pjsip_inv_session * inv,pjsip_event * e)4440 static void inv_on_state_incoming( pjsip_inv_session *inv, pjsip_event *e)
4441 {
4442     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4443     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4444 
4445     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
4446 
4447     if (tsx == inv->invite_tsx) {
4448 
4449 	/*
4450 	 * Handle the INVITE state transition.
4451 	 */
4452 
4453 	switch (tsx->state) {
4454 
4455 	case PJSIP_TSX_STATE_TRYING:
4456 	    inv_set_state(inv, PJSIP_INV_STATE_INCOMING, e);
4457 	    break;
4458 
4459 	case PJSIP_TSX_STATE_PROCEEDING:
4460 	    /*
4461 	     * Transaction sent provisional response.
4462 	     */
4463 	    if (tsx->status_code > 100)
4464 		inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
4465 	    break;
4466 
4467 	case PJSIP_TSX_STATE_COMPLETED:
4468 	    /*
4469 	     * Transaction sent final response.
4470 	     */
4471 	    if (tsx->status_code/100 == 2) {
4472 		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
4473 	    } else {
4474 		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4475 		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4476 	    }
4477 	    break;
4478 
4479 	case PJSIP_TSX_STATE_TERMINATED:
4480 	    /*
4481 	     * This happens on transport error (e.g. failed to send
4482 	     * response)
4483 	     */
4484 	    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4485 	    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4486 	    break;
4487 
4488 	default:
4489 	    pj_assert(!"Unexpected INVITE state");
4490 	    break;
4491 	}
4492 
4493     } else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
4494 	       tsx->role == PJSIP_ROLE_UAS &&
4495 	       tsx->state < PJSIP_TSX_STATE_COMPLETED &&
4496 	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG )
4497     {
4498 
4499 	/*
4500 	 * Handle incoming CANCEL request.
4501 	 */
4502 
4503 	inv_respond_incoming_cancel(inv, tsx, e);
4504 
4505     }
4506 }
4507 
4508 /*
4509  * State EARLY is for both UAS and UAC, after response with To tag
4510  * is sent/received.
4511  */
inv_on_state_early(pjsip_inv_session * inv,pjsip_event * e)4512 static void inv_on_state_early( pjsip_inv_session *inv, pjsip_event *e)
4513 {
4514     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4515     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4516 
4517     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
4518 
4519     if (tsx == inv->invite_tsx) {
4520 
4521 	/*
4522 	 * Handle the INVITE state progress.
4523 	 */
4524 
4525 	switch (tsx->state) {
4526 
4527 	case PJSIP_TSX_STATE_PROCEEDING:
4528 	    /* Send/received another provisional response. */
4529 	    inv_set_state(inv, PJSIP_INV_STATE_EARLY, e);
4530 
4531 	    if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
4532 		inv_check_sdp_in_incoming_msg(inv, tsx,
4533 					      e->body.tsx_state.src.rdata);
4534 
4535 		if (pjsip_100rel_is_reliable(e->body.tsx_state.src.rdata)) {
4536 		    inv_handle_incoming_reliable_response(
4537 			inv, e->body.tsx_state.src.rdata);
4538 		}
4539 	    }
4540 	    break;
4541 
4542 	case PJSIP_TSX_STATE_COMPLETED:
4543 	    if (tsx->status_code/100 == 2) {
4544 		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
4545 		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
4546 		    pj_status_t status;
4547 
4548 		    /* Check routing URI scheme for secure dialog */
4549 		    if (!inv_check_secure_dlg(inv, e))
4550 			break;
4551 
4552 		    /* Process session timer response. */
4553 		    status = handle_timer_response(inv,
4554 						   e->body.tsx_state.src.rdata,
4555 						   PJ_TRUE);
4556 		    if (status != PJ_SUCCESS)
4557 			break;
4558 
4559 		    inv_check_sdp_in_incoming_msg(inv, tsx,
4560 						  e->body.tsx_state.src.rdata);
4561 		}
4562 
4563 	    } else if (tsx->role == PJSIP_ROLE_UAC) {
4564 
4565 		handle_uac_call_rejection(inv, e);
4566 
4567 	    } else {
4568 		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4569 		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4570 	    }
4571 	    break;
4572 
4573 	case PJSIP_TSX_STATE_CONFIRMED:
4574 	    /* For some reason can go here (maybe when ACK for 2xx has
4575 	     * the same branch value as the INVITE transaction) */
4576 
4577 	case PJSIP_TSX_STATE_TERMINATED:
4578 	    /* INVITE transaction can be terminated either because UAC
4579 	     * transaction received 2xx response or because of transport
4580 	     * error.
4581 	     */
4582 	    if (tsx->status_code/100 == 2) {
4583 
4584 		/* This must be receipt of 2xx response */
4585 
4586 		/* Set state to CONNECTING */
4587 		inv_set_state(inv, PJSIP_INV_STATE_CONNECTING, e);
4588 
4589 		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
4590 		    pj_status_t status;
4591 
4592 		    /* Check routing URI scheme for secure dialog */
4593 		    if (!inv_check_secure_dlg(inv, e))
4594 			break;
4595 
4596 		    /* Process session timer response. */
4597 		    status = handle_timer_response(inv,
4598 						   e->body.tsx_state.src.rdata,
4599 						   PJ_TRUE);
4600 		    if (status != PJ_SUCCESS)
4601 			break;
4602 
4603 		    inv_check_sdp_in_incoming_msg(inv, tsx,
4604 						  e->body.tsx_state.src.rdata);
4605 		}
4606 
4607 		/* if UAC, send ACK and move state to confirmed. */
4608 		if (tsx->role == PJSIP_ROLE_UAC) {
4609 		    pj_assert(e->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
4610 
4611 		    inv_send_ack(inv, e);
4612 		}
4613 
4614 	    } else  {
4615 		inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4616 		inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4617 	    }
4618 	    break;
4619 
4620 	default:
4621 	    pj_assert(!"Unexpected INVITE tsx state");
4622 	    break;
4623 	}
4624 
4625     } else if (inv->role == PJSIP_ROLE_UAS &&
4626 	       tsx->role == PJSIP_ROLE_UAS &&
4627 	       tsx->method.id == PJSIP_CANCEL_METHOD &&
4628 	       tsx->state < PJSIP_TSX_STATE_COMPLETED &&
4629 	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG )
4630     {
4631 
4632 	/*
4633 	 * Handle incoming CANCEL request.
4634 	 */
4635 
4636 	inv_respond_incoming_cancel(inv, tsx, e);
4637 
4638     } else if (tsx->role == PJSIP_ROLE_UAS &&
4639 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4640 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
4641     {
4642 	/*
4643 	 * Handle incoming UPDATE
4644 	 */
4645 	inv_respond_incoming_update(inv, e);
4646 
4647 
4648     } else if (tsx->role == PJSIP_ROLE_UAC &&
4649 	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
4650 	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
4651 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
4652     {
4653 	/*
4654 	 * Handle response to outgoing UPDATE request.
4655 	 */
4656 	inv_handle_update_response(inv, e);
4657 
4658     } else if (tsx->role == PJSIP_ROLE_UAS &&
4659 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4660 	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
4661     {
4662 	/*
4663 	 * Handle incoming PRACK
4664 	 */
4665 	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
4666 
4667     } else if (tsx->role == PJSIP_ROLE_UAC) {
4668 
4669 	/* Generic handling for UAC tsx completion */
4670 	handle_uac_tsx_response(inv, e);
4671 
4672     } else if (tsx->role == PJSIP_ROLE_UAS &&
4673 	       tsx->method.id == PJSIP_BYE_METHOD &&
4674 	       tsx->status_code < 200 &&
4675 	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
4676     {
4677 	/* Received BYE before the 2xx/OK response to INVITE.
4678 	 * Assume that the 2xx/OK response is lost and the BYE
4679 	 * arrives earlier.
4680 	 */
4681 	inv_respond_incoming_bye(inv, tsx, e->body.tsx_state.src.rdata, e);
4682 
4683 	if (inv->invite_tsx->role == PJSIP_ROLE_UAC) {
4684 	    /* Set timer just in case we will never get the final response
4685 	     * for INVITE.
4686 	     */
4687 	    pjsip_tsx_set_timeout(inv->invite_tsx, 64*pjsip_cfg()->tsx.t1);
4688 	} else if (inv->invite_tsx->status_code < 200) {
4689 	    pjsip_tx_data *tdata;
4690 	    pjsip_msg *msg;
4691 
4692 	    /* For UAS, send a final response. */
4693 	    tdata = inv->invite_tsx->last_tx;
4694 	    PJ_ASSERT_ON_FAIL(tdata != NULL, return);
4695 
4696 	    msg = tdata->msg;
4697 	    msg->line.status.code = PJSIP_SC_REQUEST_TERMINATED;
4698 	    msg->line.status.reason =
4699 		    *pjsip_get_status_text(PJSIP_SC_REQUEST_TERMINATED);
4700 	    msg->body = NULL;
4701 
4702 	    pjsip_tx_data_invalidate_msg(tdata);
4703 	    pjsip_tx_data_add_ref(tdata);
4704 
4705 	    pjsip_dlg_send_response(inv->dlg, inv->invite_tsx, tdata);
4706 	}
4707     }
4708 }
4709 
4710 /*
4711  * State CONNECTING is after 2xx response to INVITE is sent/received.
4712  */
inv_on_state_connecting(pjsip_inv_session * inv,pjsip_event * e)4713 static void inv_on_state_connecting( pjsip_inv_session *inv, pjsip_event *e)
4714 {
4715     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4716     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4717 
4718     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
4719 
4720     if (tsx == inv->invite_tsx) {
4721 
4722 	/*
4723 	 * Handle INVITE state progression.
4724 	 */
4725 	switch (tsx->state) {
4726 
4727 	case PJSIP_TSX_STATE_CONFIRMED:
4728 	    /* It can only go here if incoming ACK request has the same Via
4729 	     * branch parameter as the INVITE transaction.
4730 	     */
4731 	    if (tsx->status_code/100 == 2) {
4732 		if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
4733 		    inv_check_sdp_in_incoming_msg(inv, tsx,
4734 						  e->body.tsx_state.src.rdata);
4735 		}
4736 
4737 		inv_set_state(inv, PJSIP_INV_STATE_CONFIRMED, e);
4738 
4739 		/* Send pending BYE if any:
4740 		 *   http://trac.pjsip.org/repos/ticket/1712
4741 		 * Do this after setting the state to CONFIRMED, so that we
4742 		 * have consistent CONFIRMED state between caller and callee.
4743 		 */
4744 		if (inv->pending_bye)
4745 		    inv_perform_pending_bye(inv);
4746 
4747 	    }
4748 	    break;
4749 
4750 	case PJSIP_TSX_STATE_TERMINATED:
4751 	    /* INVITE transaction can be terminated either because UAC
4752 	     * transaction received 2xx response or because of transport
4753 	     * error.
4754 	     */
4755 	    if (tsx->status_code/100 != 2) {
4756 		if (tsx->role == PJSIP_ROLE_UAC) {
4757 		    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4758 		    inv_set_state(inv, PJSIP_INV_STATE_DISCONNECTED, e);
4759 		} else {
4760 		    pjsip_tx_data *bye;
4761 		    pj_status_t status;
4762 
4763 		    inv_set_cause(inv, tsx->status_code, &tsx->status_text);
4764 
4765 		    /* Send BYE */
4766 		    status = pjsip_dlg_create_request(inv->dlg,
4767 						      pjsip_get_bye_method(),
4768 						      -1, &bye);
4769 		    if (status == PJ_SUCCESS) {
4770 			pjsip_inv_send_msg(inv, bye);
4771 
4772 			if (inv->pending_bye) {
4773 			    pjsip_tx_data_dec_ref(inv->pending_bye);
4774 			    inv->pending_bye = NULL;
4775 			}
4776 		    }
4777 		}
4778 	    }
4779 	    break;
4780 
4781 	case PJSIP_TSX_STATE_DESTROYED:
4782 	    /* Do nothing. */
4783 	    break;
4784 
4785 	default:
4786 	    pj_assert(!"Unexpected state");
4787 	    break;
4788 	}
4789 
4790     } else if (tsx->role == PJSIP_ROLE_UAS &&
4791 	       tsx->method.id == PJSIP_BYE_METHOD &&
4792 	       tsx->status_code < 200 &&
4793 	       e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
4794     {
4795 
4796 	/*
4797 	 * Handle incoming BYE.
4798 	 */
4799 
4800 	inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e );
4801 
4802     } else if (tsx->method.id == PJSIP_BYE_METHOD &&
4803 	       tsx->role == PJSIP_ROLE_UAC &&
4804 	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
4805 	        tsx->state == PJSIP_TSX_STATE_TERMINATED))
4806     {
4807 
4808 	/*
4809 	 * Outgoing BYE
4810 	 */
4811 	inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e);
4812 
4813     }
4814     else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
4815 	     tsx->role == PJSIP_ROLE_UAS &&
4816 	     tsx->status_code < 200 &&
4817 	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
4818     {
4819 
4820 	/*
4821 	 * Handle strandled incoming CANCEL or CANCEL for re-INVITE
4822 	 */
4823         inv_respond_incoming_cancel(inv, tsx, e);
4824 
4825     } else if (tsx->role == PJSIP_ROLE_UAS &&
4826 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4827 	       pjsip_method_cmp(&tsx->method, pjsip_get_invite_method())==0)
4828     {
4829 	pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
4830 	pjsip_tx_data *tdata;
4831 	pj_status_t status;
4832 
4833 	/* See https://trac.pjsip.org/repos/ticket/1455
4834 	 * Handle incoming re-INVITE before current INVITE is confirmed.
4835 	 * According to RFC 5407:
4836 	 *  - answer with 200 if we don't have pending offer-answer
4837 	 *  - answer with 491 if we *have* pending offer-answer
4838 	 *
4839 	 *  But unfortunately accepting the re-INVITE would mean we have
4840 	 *  two outstanding INVITEs, and we don't support that because
4841 	 *  we will get confused when we handle the ACK.
4842 	 */
4843 	status = pjsip_dlg_create_response(inv->dlg, rdata,
4844 					   PJSIP_SC_REQUEST_PENDING,
4845 					   NULL, &tdata);
4846 	if (status != PJ_SUCCESS)
4847 	    return;
4848 	pjsip_timer_update_resp(inv, tdata);
4849 	status = pjsip_dlg_send_response(dlg, tsx, tdata);
4850 
4851     } else if (tsx->role == PJSIP_ROLE_UAS &&
4852 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4853 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
4854     {
4855 	/*
4856 	 * Handle incoming UPDATE
4857 	 */
4858 	inv_respond_incoming_update(inv, e);
4859 
4860 
4861     } else if (tsx->role == PJSIP_ROLE_UAC &&
4862 	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
4863 	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
4864 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
4865     {
4866 	/*
4867 	 * Handle response to outgoing UPDATE request.
4868 	 */
4869 	if (inv_handle_update_response(inv, e) == PJ_FALSE)
4870 	    handle_uac_tsx_response(inv, e);
4871 
4872     } else if (tsx->role == PJSIP_ROLE_UAS &&
4873 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
4874 	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
4875     {
4876 	/*
4877 	 * Handle incoming PRACK
4878 	 */
4879 	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
4880 
4881     } else if (tsx->role == PJSIP_ROLE_UAC) {
4882 
4883 	/* Generic handling for UAC tsx completion */
4884 	handle_uac_tsx_response(inv, e);
4885 
4886     }
4887 
4888 }
4889 
4890 /*
4891  * State CONFIRMED is after ACK is sent/received.
4892  */
inv_on_state_confirmed(pjsip_inv_session * inv,pjsip_event * e)4893 static void inv_on_state_confirmed( pjsip_inv_session *inv, pjsip_event *e)
4894 {
4895     pjsip_transaction *tsx = e->body.tsx_state.tsx;
4896     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
4897 
4898     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
4899 
4900 
4901     if (tsx->method.id == PJSIP_BYE_METHOD &&
4902 	tsx->role == PJSIP_ROLE_UAC &&
4903 	(tsx->state == PJSIP_TSX_STATE_COMPLETED ||
4904 	 tsx->state == PJSIP_TSX_STATE_TERMINATED))
4905     {
4906 
4907 	/*
4908 	 * Outgoing BYE
4909 	 */
4910 
4911 	inv_handle_bye_response( inv, tsx, e->body.tsx_state.src.rdata, e);
4912 
4913     }
4914     else if (tsx->method.id == PJSIP_BYE_METHOD &&
4915 	     tsx->role == PJSIP_ROLE_UAS &&
4916 	     tsx->status_code < 200 &&
4917 	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
4918     {
4919 
4920 	/*
4921 	 * Handle incoming BYE.
4922 	 */
4923 
4924 	inv_respond_incoming_bye( inv, tsx, e->body.tsx_state.src.rdata, e );
4925 
4926     }
4927     else if (tsx->method.id == PJSIP_CANCEL_METHOD &&
4928 	     tsx->role == PJSIP_ROLE_UAS &&
4929 	     tsx->status_code < 200 &&
4930 	     e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
4931     {
4932 
4933 	/*
4934 	 * Handle strandled incoming CANCEL or CANCEL for re-INVITE
4935 	 */
4936         inv_respond_incoming_cancel(inv, tsx, e);
4937     }
4938     else if (tsx->method.id == PJSIP_INVITE_METHOD &&
4939 	     tsx->role == PJSIP_ROLE_UAS)
4940     {
4941 
4942 	/*
4943 	 * Handle incoming re-INVITE
4944 	 */
4945 	if (tsx->state == PJSIP_TSX_STATE_TRYING) {
4946 
4947 	    pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
4948 	    pjsip_tx_data *tdata;
4949 	    pj_status_t status;
4950 	    pjsip_rdata_sdp_info *sdp_info = NULL;
4951 	    pjsip_status_code st_code;
4952 
4953 	    /* Check if we have INVITE pending. */
4954 	    if (inv->invite_tsx && inv->invite_tsx!=tsx) {
4955 		int code;
4956 		pj_str_t reason;
4957 
4958 		reason = pj_str("Another INVITE transaction in progress");
4959 
4960 		if (inv->invite_tsx->role == PJSIP_ROLE_UAC)
4961 		    code = 491;
4962 		else
4963 		    code = 500;
4964 
4965 		/* Can not receive re-INVITE while another one is pending. */
4966 		status = pjsip_dlg_create_response( inv->dlg, rdata, code,
4967 						    &reason, &tdata);
4968 		if (status != PJ_SUCCESS)
4969 		    return;
4970 
4971 		if (code == 500) {
4972 		    /* MUST include Retry-After header with random value
4973 		     * between 0-10.
4974 		     */
4975 		    pjsip_retry_after_hdr *ra_hdr;
4976 		    int val = (pj_rand() % 10);
4977 
4978 		    ra_hdr = pjsip_retry_after_hdr_create(tdata->pool, val);
4979 		    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)ra_hdr);
4980 		}
4981 
4982 		status = pjsip_dlg_send_response( inv->dlg, tsx, tdata);
4983 
4984 
4985 		return;
4986 	    }
4987 
4988 	    /* Check routing URI scheme for secure dialog */
4989 	    if (!inv_check_secure_dlg(inv, e))
4990 		return;
4991 
4992 	    /* Save the invite transaction. */
4993 	    inv->invite_tsx = tsx;
4994 
4995 	    /* Process session timers headers in the re-INVITE */
4996 	    status = pjsip_timer_process_req(inv, rdata, &st_code);
4997 	    if (status != PJ_SUCCESS) {
4998 		status = pjsip_dlg_create_response(inv->dlg, rdata, st_code,
4999 						   NULL, &tdata);
5000 		if (status != PJ_SUCCESS)
5001 		    return;
5002 
5003 		pjsip_timer_update_resp(inv, tdata);
5004 		status = pjsip_dlg_send_response(dlg, tsx, tdata);
5005 		return;
5006 	    }
5007 
5008 	    /* Send 491 if we receive re-INVITE while another offer/answer
5009 	     * negotiation is in progress
5010 	     */
5011 	    if (pjmedia_sdp_neg_get_state(inv->neg) !=
5012 		    PJMEDIA_SDP_NEG_STATE_DONE)
5013 	    {
5014 		status = pjsip_dlg_create_response(inv->dlg, rdata,
5015 						   PJSIP_SC_REQUEST_PENDING,
5016 						   NULL, &tdata);
5017 		if (status != PJ_SUCCESS)
5018 		    return;
5019 		pjsip_timer_update_resp(inv, tdata);
5020 		status = pjsip_dlg_send_response(dlg, tsx, tdata);
5021 		return;
5022 	    }
5023 
5024 	    /* Process SDP in incoming message. */
5025 	    status = inv_check_sdp_in_incoming_msg(inv, tsx, rdata);
5026 
5027             if (status == PJ_SUCCESS && mod_inv.cb.on_rx_reinvite &&
5028                 inv->notify)
5029             {
5030         	pj_status_t rc;
5031 
5032 	        sdp_info = pjsip_rdata_get_sdp_info(rdata);
5033                 rc = (*mod_inv.cb.on_rx_reinvite)(inv, sdp_info->sdp,
5034                 				  rdata);
5035                 if (rc == PJ_SUCCESS) {
5036                     /* Application will send its own response.
5037                      * Our job is done. */
5038 		    PJ_LOG(5,(inv->obj_name, "on_rx_reinvite() returns %d",
5039 			      rc));
5040                     return;
5041                 }
5042 
5043                 /* If application lets us answer the re-INVITE which contains
5044 		 * SDP, application must set the SDP answer with
5045                  * #pjsip_inv_set_sdp_answer().
5046                  */
5047                 if (sdp_info->sdp &&
5048 		    (pjmedia_sdp_neg_get_state(inv->neg) !=
5049 			PJMEDIA_SDP_NEG_STATE_WAIT_NEGO))
5050                 {
5051                     status = PJ_EINVALIDOP;
5052                 }
5053             }
5054 
5055 	    if (status != PJ_SUCCESS) {
5056 		pj_bool_t reject_message = PJ_TRUE;
5057 
5058 		if (status == PJMEDIA_SDP_EINSDP)
5059 		{
5060 		    sdp_info = pjsip_rdata_get_sdp_info(rdata);
5061 		    if (sdp_info->body.ptr == NULL &&
5062 			PJSIP_INV_ACCEPT_UNKNOWN_BODY)
5063 		    {
5064 			/* Message body is not "application/sdp" */
5065 			reject_message = PJ_FALSE;
5066 		    }
5067 		}
5068 
5069 		if (reject_message) {
5070 		    /* Not Acceptable */
5071 		    const pjsip_hdr *accept;
5072 
5073 		    /* The incoming SDP is unacceptable. If the SDP negotiator
5074 		     * state has just been changed, i.e: DONE -> REMOTE_OFFER,
5075 		     * revert it back.
5076 		     */
5077 		    if (pjmedia_sdp_neg_get_state(inv->neg) ==
5078 			PJMEDIA_SDP_NEG_STATE_REMOTE_OFFER)
5079 		    {
5080 			pjmedia_sdp_neg_cancel_offer(inv->neg);
5081 		    }
5082 
5083 		    status = pjsip_dlg_create_response(inv->dlg, rdata,
5084 					 (status == PJMEDIA_SDP_EINSDP)?415:488,
5085 					  NULL, &tdata);
5086 
5087 		    if (status != PJ_SUCCESS)
5088 			return;
5089 
5090 
5091 		    accept = pjsip_endpt_get_capability(dlg->endpt,
5092 							PJSIP_H_ACCEPT,
5093 							NULL);
5094 		    if (accept) {
5095 			pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)
5096 					  pjsip_hdr_clone(tdata->pool, accept));
5097 		    }
5098 
5099 		    status = pjsip_dlg_send_response(dlg, tsx, tdata);
5100 
5101 		    return;
5102 		}
5103 	    }
5104 
5105 	    /* Create 2xx ANSWER */
5106 	    status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata);
5107 	    if (status != PJ_SUCCESS)
5108 		return;
5109 
5110 	    /* If the INVITE request has SDP body, send answer.
5111 	     * Otherwise generate offer from local active SDP.
5112 	     */
5113             if (!sdp_info)
5114                 sdp_info = pjsip_rdata_get_sdp_info(rdata);
5115 	    if (sdp_info->sdp != NULL) {
5116 		status = process_answer(inv, 200, tdata, NULL);
5117 	    } else {
5118 		/* INVITE does not have SDP.
5119 		 * If on_create_offer() callback is implemented, ask app.
5120 		 * to generate an offer, otherwise just send active local
5121 		 * SDP to signal that nothing gets modified.
5122 		 */
5123 		pjmedia_sdp_session *sdp = NULL;
5124 
5125 		if (mod_inv.cb.on_create_offer)  {
5126 		    (*mod_inv.cb.on_create_offer)(inv, &sdp);
5127 		    if (sdp) {
5128 			/* Notify negotiator about the new offer. This will
5129 			 * fix the offer with correct SDP origin.
5130 			 */
5131 			status =
5132 			    pjmedia_sdp_neg_modify_local_offer2(
5133                                 inv->pool_prov, inv->neg,
5134                                 inv->sdp_neg_flags, sdp);
5135 
5136 			/* Retrieve the "fixed" offer from negotiator */
5137 			if (status==PJ_SUCCESS) {
5138 			    const pjmedia_sdp_session *lsdp = NULL;
5139 			    pjmedia_sdp_neg_get_neg_local(inv->neg, &lsdp);
5140 			    sdp = (pjmedia_sdp_session*)lsdp;
5141 			}
5142 		    }
5143 		}
5144 
5145 		if (sdp == NULL) {
5146 		    const pjmedia_sdp_session *active_sdp = NULL;
5147 		    status = pjmedia_sdp_neg_send_local_offer(inv->pool_prov,
5148 							      inv->neg,
5149 							      &active_sdp);
5150 		    if (status == PJ_SUCCESS)
5151 			sdp = (pjmedia_sdp_session*) active_sdp;
5152 		}
5153 
5154 		if (sdp) {
5155 		    tdata->msg->body = create_sdp_body(tdata->pool, sdp);
5156 		}
5157 	    }
5158 
5159 	    if (status != PJ_SUCCESS) {
5160 		/*
5161 		 * SDP negotiation has failed.
5162 		 */
5163 		pj_status_t rc;
5164 		pj_str_t reason;
5165 
5166 		/* Delete the 2xx answer */
5167 		pjsip_tx_data_dec_ref(tdata);
5168 
5169 		/* Create 500 response */
5170 		reason = pj_str("SDP negotiation failed");
5171 		rc = pjsip_dlg_create_response(dlg, rdata, 500, &reason,
5172 					       &tdata);
5173 		if (rc == PJ_SUCCESS) {
5174 		    pjsip_warning_hdr *w;
5175 		    const pj_str_t *endpt_name;
5176 
5177 		    endpt_name = pjsip_endpt_name(dlg->endpt);
5178 		    w = pjsip_warning_hdr_create_from_status(tdata->pool,
5179 							     endpt_name,
5180 							     status);
5181 		    if (w)
5182 			pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)w);
5183 
5184 		    pjsip_inv_send_msg(inv, tdata);
5185 		}
5186 		return;
5187 	    }
5188 
5189 	    /* Invoke Session Timers */
5190 	    pjsip_timer_update_resp(inv, tdata);
5191 
5192 	    /* Send 2xx regardless of the status of negotiation */
5193 	    status = pjsip_inv_send_msg(inv, tdata);
5194 
5195 	} else if (tsx->state == PJSIP_TSX_STATE_CONFIRMED) {
5196 	    /* This is the case where ACK has the same branch as
5197 	     * the INVITE request.
5198 	     */
5199 	    if (tsx->status_code/100 == 2 &&
5200 		e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
5201 	    {
5202 		inv_check_sdp_in_incoming_msg(inv, tsx,
5203 					      e->body.tsx_state.src.rdata);
5204 
5205 		/* Check if local offer got no SDP answer */
5206 		if (pjmedia_sdp_neg_get_state(inv->neg)==
5207 		    PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
5208 		{
5209 		    pjmedia_sdp_neg_cancel_offer(inv->neg);
5210 		}
5211 	    }
5212 
5213 	}
5214 
5215     }
5216     else if (tsx->method.id == PJSIP_INVITE_METHOD &&
5217 	     tsx->role == PJSIP_ROLE_UAC)
5218     {
5219 
5220 	/*
5221 	 * Handle outgoing re-INVITE
5222 	 */
5223 	if (tsx->state == PJSIP_TSX_STATE_CALLING) {
5224 
5225 	    /* Must not have other pending INVITE transaction */
5226 	    pj_assert(inv->invite_tsx==NULL || tsx==inv->invite_tsx);
5227 
5228 	    /* Save pending invite transaction */
5229 	    inv->invite_tsx = tsx;
5230 
5231         } else if (tsx->state == PJSIP_TSX_STATE_PROCEEDING) {
5232 
5233             /* CANCEL the re-INVITE if necessary */
5234             if (inv->pending_cancel) {
5235 	        pj_status_t status;
5236 		pjsip_tx_data *cancel;
5237 
5238 		inv->pending_cancel = PJ_FALSE;
5239 
5240 		status = pjsip_inv_cancel_reinvite(inv, &cancel);
5241 		if (status == PJ_SUCCESS && cancel)
5242 		    status = pjsip_inv_send_msg(inv, cancel);
5243             }
5244 
5245 	} else if (tsx->state == PJSIP_TSX_STATE_TERMINATED &&
5246 		   tsx->status_code/100 == 2)
5247 	{
5248 	    pj_status_t status;
5249 
5250 	    /* Re-INVITE was accepted. */
5251 
5252 	    /* Check routing URI scheme for secure dialog */
5253 	    if (!inv_check_secure_dlg(inv, e))
5254 		return;
5255 
5256 	    /* Process session timer response. */
5257 	    status = handle_timer_response(inv,
5258 					   e->body.tsx_state.src.rdata,
5259 					   PJ_TRUE);
5260 	    if (status != PJ_SUCCESS)
5261 		return;
5262 
5263 	    /* Process SDP */
5264 	    inv_check_sdp_in_incoming_msg(inv, tsx,
5265 					  e->body.tsx_state.src.rdata);
5266 
5267 	    /* Check if local offer got no SDP answer */
5268 	    if (pjmedia_sdp_neg_get_state(inv->neg)==
5269 		PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER)
5270 	    {
5271 		pjmedia_sdp_neg_cancel_offer(inv->neg);
5272 	    }
5273 
5274 	    /* Send ACK */
5275 	    inv_send_ack(inv, e);
5276 
5277 	} else if (handle_uac_tsx_response(inv, e)) {
5278 
5279 	    /* Handle response that terminates dialog */
5280 	    /* Nothing to do (already handled) */
5281 
5282 	} else if (tsx->status_code >= 300 && tsx->status_code < 700 &&
5283 		   e->body.tsx_state.prev_state != PJSIP_TSX_STATE_COMPLETED)
5284 	{
5285 	    /* Ticket #1654: do not cancel SDP offer when tsx state changing
5286 	     * from 'completed' to 'terminated', as it should have already
5287 	     * been cancelled when tsx state is 'completed'.
5288 	     */
5289 
5290 	    pjmedia_sdp_neg_state neg_state;
5291 	    struct tsx_inv_data *tsx_inv_data;
5292 
5293 	    tsx_inv_data = (struct tsx_inv_data*)tsx->mod_data[mod_inv.mod.id];
5294 
5295 	    /* Outgoing INVITE transaction has failed, cancel SDP nego */
5296 	    neg_state = pjmedia_sdp_neg_get_state(inv->neg);
5297 	    if (neg_state == PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER &&
5298 		tsx_inv_data->retrying == PJ_FALSE)
5299 	    {
5300 		pjmedia_sdp_neg_cancel_offer(inv->neg);
5301 	    }
5302 
5303 	    if (tsx == inv->invite_tsx)
5304 		inv->invite_tsx = NULL;
5305 
5306 	    /* Process 502/503 error for session timer refresh */
5307 	    if (tsx->status_code == 503 || tsx->status_code == 502) {
5308 		pjsip_timer_handle_refresh_error(inv, e);
5309 	    }
5310 	}
5311 
5312     } else if (tsx->role == PJSIP_ROLE_UAS &&
5313 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
5314 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
5315     {
5316 	/*
5317 	 * Handle incoming UPDATE
5318 	 */
5319 	inv_respond_incoming_update(inv, e);
5320 
5321     } else if (tsx->role == PJSIP_ROLE_UAC &&
5322 	       (tsx->state == PJSIP_TSX_STATE_COMPLETED ||
5323 	        tsx->state == PJSIP_TSX_STATE_TERMINATED) &&
5324 	       pjsip_method_cmp(&tsx->method, &pjsip_update_method)==0)
5325     {
5326 	/*
5327 	 * Handle response to outgoing UPDATE request.
5328 	 */
5329 	if (inv_handle_update_response(inv, e) == PJ_FALSE)
5330 	    handle_uac_tsx_response(inv, e);
5331 
5332     } else if (tsx->role == PJSIP_ROLE_UAS &&
5333 	       tsx->state == PJSIP_TSX_STATE_TRYING &&
5334 	       pjsip_method_cmp(&tsx->method, &pjsip_prack_method)==0)
5335     {
5336 	/*
5337 	 * Handle strandled incoming PRACK
5338 	 */
5339 	inv_respond_incoming_prack(inv, e->body.tsx_state.src.rdata);
5340 
5341     } else if (tsx->role == PJSIP_ROLE_UAC) {
5342 	/*
5343 	 * Handle 401/407/408/481/422 response
5344 	 */
5345 	handle_uac_tsx_response(inv, e);
5346     }
5347 
5348 }
5349 
5350 /*
5351  * After session has been terminated, but before dialog is destroyed
5352  * (because dialog has other usages, or because dialog is waiting for
5353  * the last transaction to terminate).
5354  */
inv_on_state_disconnected(pjsip_inv_session * inv,pjsip_event * e)5355 static void inv_on_state_disconnected( pjsip_inv_session *inv, pjsip_event *e)
5356 {
5357     pjsip_transaction *tsx = e->body.tsx_state.tsx;
5358     pjsip_dialog *dlg = pjsip_tsx_get_dlg(tsx);
5359 
5360     PJ_ASSERT_ON_FAIL(tsx && dlg, return);
5361 
5362     if (tsx->role == PJSIP_ROLE_UAS &&
5363 	tsx->status_code < 200 &&
5364 	e->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
5365     {
5366 	pjsip_rx_data *rdata = e->body.tsx_state.src.rdata;
5367 
5368 	/*
5369 	 * Respond BYE with 200/OK
5370 	 */
5371 	if (tsx->method.id == PJSIP_BYE_METHOD) {
5372 	    inv_respond_incoming_bye( inv, tsx, rdata, e );
5373 	} else if (tsx->method.id == PJSIP_CANCEL_METHOD) {
5374 	    /*
5375 	     * Respond CANCEL with 200/OK too.
5376 	     */
5377 	    pjsip_tx_data *tdata;
5378 	    pj_status_t status;
5379 
5380 	    status = pjsip_dlg_create_response(dlg, rdata, 200, NULL, &tdata);
5381 	    if (status != PJ_SUCCESS) return;
5382 
5383 	    status = pjsip_dlg_send_response(dlg, tsx, tdata);
5384 	    if (status != PJ_SUCCESS) return;
5385 
5386 	}
5387 
5388     } else if (tsx->role == PJSIP_ROLE_UAC) {
5389 	/*
5390 	 * Handle 401/407/408/481/422 response
5391 	 */
5392 	handle_uac_tsx_response(inv, e);
5393     }
5394 }
5395 
5396