nua_session.c 66.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2006 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

/**@CFILE nua_session.c
26
 * @brief SIP session handling
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 *
 * @date Created: Wed Mar  8 16:17:27 EET 2006 ppessi
 */

#include "config.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <assert.h>

#include <sofia-sip/string0.h>
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/sip_status.h>
#include <sofia-sip/sip_util.h>

#define NTA_LEG_MAGIC_T      struct nua_handle_s
#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
#define NTA_INCOMING_MAGIC_T struct nua_handle_s
#define NTA_RELIABLE_MAGIC_T struct nua_handle_s

#include "nua_stack.h"
#include <sofia-sip/soa.h>

55 56 57 58
#if !defined(random) && defined(_WIN32)
#define random rand
#endif

59 60 61 62 63 64 65 66 67 68
#ifndef SDP_H
typedef struct sdp_session_s sdp_session_t;
#endif

/* ---------------------------------------------------------------------- */
/* Session event usage */

struct session_usage;

static char const *nua_session_usage_name(nua_dialog_usage_t const *du);
69
static int nua_session_usage_add(nua_handle_t *nh,
70 71
				 nua_dialog_state_t *ds,
				 nua_dialog_usage_t *du);
72
static void nua_session_usage_remove(nua_handle_t *nh,
73 74 75 76 77
				     nua_dialog_state_t *ds,
				     nua_dialog_usage_t *du);

static nua_usage_class const nua_session_usage[1] = {
  {
Pekka Pessi's avatar
Pekka Pessi committed
78
    0 /* sizeof (struct session_usage) */,
79 80 81 82 83 84 85 86 87 88 89
    sizeof nua_session_usage,
    nua_session_usage_add,
    nua_session_usage_remove,
    nua_session_usage_name,
  }};

static char const *nua_session_usage_name(nua_dialog_usage_t const *du)
{
  return "session";
}

90 91
static
int nua_session_usage_add(nua_handle_t *nh,
92 93 94 95 96 97 98 99 100
			   nua_dialog_state_t *ds,
			   nua_dialog_usage_t *du)
{
  if (ds->ds_has_session)
    return -1;
  ds->ds_has_session = 1;
  return 0;
}

101 102
static
void nua_session_usage_remove(nua_handle_t *nh,
103 104 105 106 107 108 109 110 111 112 113 114 115 116
			       nua_dialog_state_t *ds,
			       nua_dialog_usage_t *du)
{
  ds->ds_has_session = 0;
}

/* ======================================================================== */
/* INVITE and call (session) processing */

static int ua_invite2(nua_t *, nua_handle_t *, nua_event_t e,
		      int restarted, tagi_t const *tags);
static int process_response_to_invite(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip);
117
static int process_100rel(nua_handle_t *nh,
118 119
			  nta_outgoing_t *orq,
			  sip_t const *sip);
120
static void
121 122 123 124 125 126 127 128 129 130 131 132
  cancel_invite(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now),
  refresh_invite(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now),
  session_timeout(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now);

static void restart_invite(nua_handle_t *nh, tagi_t *tags);

static int process_response_to_prack(nua_handle_t *nh,
				     nta_outgoing_t *orq,
				     sip_t const *sip);

static void nsession_destroy(nua_handle_t *nh);

133 134
static int  use_session_timer(nua_handle_t *nh, int uas, msg_t *msg, sip_t *);
static int  init_session_timer(nua_handle_t *nh, sip_t const *);
135 136
static void set_session_timer(nua_handle_t *nh);

137 138 139
static int nh_referral_check(nua_handle_t *nh, tagi_t const *tags);
static void nh_referral_respond(nua_handle_t *,
				int status, char const *phrase);
140

141
static void signal_call_state_change(nua_handle_t *nh,
142 143 144 145 146 147
				     int status, char const *phrase,
				     enum nua_callstate next_state,
				     char const *oa_recv,
				     char const *oa_sent);

static
148
int session_get_description(msg_t *msg,
149
			    sip_t const *sip,
150
			    char const **return_sdp,
151 152 153
			    size_t *return_len);

static
154 155
int session_include_description(soa_session_t *soa,
				msg_t *msg,
156 157 158
				sip_t *sip);

static
159 160
int session_make_description(su_home_t *home,
			     soa_session_t *soa,
161 162 163 164 165 166 167 168 169 170 171
			     sip_content_disposition_t **return_cd,
			     sip_content_type_t **return_ct,
			     sip_payload_t **return_pl);

static
int session_process_response(nua_handle_t *nh,
			     struct nua_client_request *cr,
			     nta_outgoing_t *orq,
			     sip_t const *sip,
			     char const **return_received);

172 173 174
int
nua_stack_invite(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		 tagi_t const *tags)
175 176 177 178 179 180 181 182 183 184
{
  nua_session_state_t *ss = nh->nh_ss;
  struct nua_client_request *cr = ss->ss_crequest;
  char const *what;

  if (nh_is_special(nh))
    what = "Invalid handle for INVITE";
  else if (cr->cr_orq) {
    what = "INVITE request already in progress";
  }
185
  else if (nh_referral_check(nh, tags) < 0) {
186 187
    what = "Invalid referral";
  }
188
  else if (nua_stack_init_handle(nua, nh, nh_has_invite, NULL,
189 190 191 192 193 194
				 TAG_NEXT(tags)) < 0) {
    what = "Handle initialization failed";
  }
  else
    return ua_invite2(nua, nh, e, 0, tags);

195
  UA_EVENT2(e, 900, what);
196

197
  signal_call_state_change(nh, 900, what, nua_callstate_init, 0, 0);
198 199 200 201 202

  return e;
}

static int
203
ua_invite2(nua_t *nua, nua_handle_t *nh, nua_event_t e, int restarted,
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	   tagi_t const *tags)
{
  nua_session_state_t *ss = nh->nh_ss;
  struct nua_client_request *cr = ss->ss_crequest;
  nua_dialog_usage_t *du;
  int offer_sent = 0;

  msg_t *msg = NULL;
  sip_t *sip;

  char const *what;

  if (ss->ss_state == nua_callstate_terminated)
    ss->ss_state = nua_callstate_init;

  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
220
  what = nua_internal_error;		/* Internal error */
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

  msg = du ? nua_creq_msg(nua, nh, cr, restarted,
			      SIP_METHOD_INVITE,
			      NUTAG_USE_DIALOG(1),
			      NUTAG_ADD_CONTACT(1),
			      TAG_NEXT(tags)) : NULL;
  sip = sip_object(msg);

  if (du && sip && nh->nh_soa) {
    soa_init_offer_answer(nh->nh_soa);

    if (sip->sip_payload)
      offer_sent = 0;
    else if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0)
      offer_sent = -1;
    else
      offer_sent = 1;
  }

  assert(cr->cr_orq == NULL);

  if (du && sip && offer_sent >= 0) {
243
    sip_time_t invite_timeout = NH_PGET(nh, invite_timeout);
244
    if (invite_timeout == 0)
245
      invite_timeout = UINT_MAX;
246
    /* Cancel if we don't get response */
247
    nua_dialog_usage_set_refresh(du, invite_timeout);
248 249

    /* Add session timer headers */
250
    use_session_timer(nh, 0, msg, sip);
251 252 253 254 255 256 257 258

    ss->ss_100rel = NH_PGET(nh, early_media);
    ss->ss_precondition = sip_has_feature(sip->sip_require, "precondition");

    if (ss->ss_precondition)
      ss->ss_update_needed = ss->ss_100rel = 1;

    if (offer_sent > 0 &&
259
	session_include_description(nh->nh_soa, msg, sip) < 0)
260
      sip = NULL, what = "Internal media error";
261

262
    if (sip && nh->nh_soa &&
263
	NH_PGET(nh, media_features) && !nua_dialog_is_established(nh->nh_ds) &&
264 265 266 267 268 269
	!sip->sip_accept_contact && !sip->sip_reject_contact) {
      sip_accept_contact_t ac[1];
      sip_accept_contact_init(ac);

      ac->cp_params = (msg_param_t *)
	soa_media_features(nh->nh_soa, 1, msg_home(msg));
270

271 272 273 274 275 276
      if (ac->cp_params) {
	msg_header_replace_param(msg_home(msg), ac->cp_common, "explicit");
	sip_add_dup(msg, sip, (sip_header_t *)ac);
      }
    }

277 278 279 280
    if (sip && nh->nh_auth) {
      if (auc_authorize(&nh->nh_auth, msg, sip) < 0)
	sip = NULL, what = "Internal authentication error";
    }
281 282 283 284 285 286 287 288 289 290 291
    if (sip)
      cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
					process_response_to_invite, nh, NULL,
					msg,
					NTATAG_REL100(ss->ss_100rel),
					SIPTAG_END(), TAG_NEXT(tags));

    if (cr->cr_orq) {
      cr->cr_offer_sent = offer_sent;
      cr->cr_usage = du;
      du->du_pending = cancel_invite;
292
      du->du_refresh = 0;
293 294 295 296 297 298 299 300
      signal_call_state_change(nh, 0, "INVITE sent",
			       nua_callstate_calling, 0,
			       offer_sent ? "offer" : 0);
      return cr->cr_event = e;
    }
  }

  msg_destroy(msg);
301
  if (du && !du->du_ready)
302 303
    nua_dialog_usage_remove(nh, nh->nh_ds, du);

304 305
  UA_EVENT2(e, 900, what);
  signal_call_state_change(nh, 900, what, nua_callstate_init, 0, 0);
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

  return e;
}

static int process_response_to_invite(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip)
{
  nua_t *nua = nh->nh_nua;
  nua_session_state_t *ss = nh->nh_ss;
  nua_client_request_t *cr = ss->ss_crequest;
  nua_dialog_usage_t *du = cr->cr_usage;
  int status = sip->sip_status->st_status;
  char const *phrase = sip->sip_status->st_phrase;
  int terminated = 0;
  int gracefully = 1;
  char const *received = NULL;

  assert(du);

#if HAVE_SOFIA_SMIME
  if (status < 300) {
    int sm_status;
    msg_t *response;

    /* decrypt sdp payload if it's S/MIME */
    /* XXX msg had a problem!!?? */
    response = nta_outgoing_getresponse(orq);

    sm_status = sm_decode_message(nua->sm, response, sip);

    switch (sm_status) {
    case SM_SMIME_DISABLED:
    case SM_ERROR:
      status = 493, phrase = "Undecipherable";
      break;
    case SM_SUCCESS:
      break;
    default:
      break;
    }
  }
#endif

  if (status >= 300) {
    if (sip->sip_retry_after)
      gracefully = 0;

354
    terminated = sip_response_terminates_dialog(status, sip_method_invite,
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
						&gracefully);

    if (!terminated) {
      if (nua_creq_check_restart(nh, cr, orq, sip, restart_invite))
	return 0;

      if (nh->nh_ss->ss_state < nua_callstate_ready)
	terminated = 1;
    }
  }
  else if (status >= 200) {

    du->du_ready = 1;
    if (!ss->ss_usage)
      ss->ss_usage = du;
    cr->cr_usage = NULL;
371

372 373
    /* XXX - check remote tag, handle forks */
    /* Set route, contact, nh_ds->ds_remote_tag */
374
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
375
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
376

377
    init_session_timer(nh, sip);
378 379 380 381 382 383 384

    set_session_timer(nh);

    /* signal_call_state_change */
    if (session_process_response(nh, cr, orq, sip, &received) >= 0) {
      ss->ss_ack_needed = received ? received : "";

385
      if (NH_PGET(nh, auto_ack) ||
386
	  /* Auto-ACK response to re-INVITE unless auto_ack is set to 0 */
387
	  (ss->ss_state == nua_callstate_ready &&
388 389 390
	   !NH_PISSET(nh, auto_ack)))
	nua_stack_ack(nua, nh, nua_r_ack, NULL);
      else
391
	signal_call_state_change(nh, status, phrase,
392 393 394 395 396
				 nua_callstate_completing, received, 0);
      nh_referral_respond(nh, SIP_200_OK);
      return 0;
    }

397
    status = 900, phrase = "Malformed Session in Response";
398 399 400 401 402 403 404 405 406 407 408 409 410 411

    nua_stack_ack(nua, nh, nua_r_ack, NULL);
    gracefully = 1;
  }
  else if (sip->sip_rseq) {
    /* Reliable provisional response */
    nh_referral_respond(nh, status, phrase);

    return process_100rel(nh, orq, sip); /* signal_call_state_change */
  }
  else {
    /* Provisional response */
    nh_referral_respond(nh, status, phrase);
    session_process_response(nh, cr, orq, sip, &received);
412
    signal_call_state_change(nh, status, phrase,
413 414 415 416 417 418 419 420 421 422
			     nua_callstate_proceeding, received, 0);
    return 0;
  }

  cr->cr_usage = NULL;

  nh_referral_respond(nh, status, phrase);
  nua_stack_process_response(nh, cr, orq, sip, TAG_END());

  if (terminated)
423
    signal_call_state_change(nh, status, phrase,
424 425 426 427 428 429 430 431 432
			     nua_callstate_terminated, 0, 0);

  if (terminated < 0) {
    nua_dialog_terminated(nh, nh->nh_ds, status, phrase);
  }
  else if (terminated > 0) {
    nua_dialog_usage_remove(nh, nh->nh_ds, du);
  }
  else if (gracefully) {
433
    char *reason =
434 435
      su_sprintf(NULL, "SIP;cause=%u;text=\"%s\"", status, phrase);

436
    signal_call_state_change(nh, status, phrase,
437 438
			     nua_callstate_terminating, 0, 0);

439 440 441
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
442 443 444 445 446 447 448

    su_free(NULL, reason);
  }

  return 0;
}

449 450
int nua_stack_ack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		  tagi_t const *tags)
451 452 453 454 455 456 457 458 459 460 461
{
  nua_session_state_t *ss = nh->nh_ss;
  struct nua_client_request *cr = ss->ss_crequest;
  nta_outgoing_t *ack = NULL;
  msg_t *msg;
  sip_t *sip;
  int status = 200;
  char const *phrase = "OK", *reason = NULL, *sent = NULL;
  char const *received = ss->ss_ack_needed;

  if (!ss->ss_ack_needed)
462
    return UA_EVENT2(nua_i_error, 900, "No response to ACK");
463 464 465 466 467 468 469 470 471 472

  ss->ss_ack_needed = 0;

  if (!received[0])
    received = NULL;

  if (tags) {
    nua_stack_set_params(nua, nh, nua_r_ack, tags);
  }

473 474
  msg = nua_creq_msg(nua, nh, cr, 0,
			 SIP_METHOD_ACK,
475 476 477 478 479 480 481 482 483 484
			 /* NUTAG_COPY(0), */
			 TAG_NEXT(tags));
  sip = sip_object(msg);

  if (sip && nh->nh_soa) {
    if (tags)
      soa_set_params(nh->nh_soa, TAG_NEXT(tags));

    if (cr->cr_offer_recv && !cr->cr_answer_sent) {
      if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
485
	  session_include_description(nh->nh_soa, msg, sip) < 0) {
486
	reason = soa_error_as_sip_reason(nh->nh_soa);
487
	status = 900, phrase = "Internal media error";
488 489 490 491 492 493 494 495 496 497 498
	reason = "SIP;cause=500;text=\"Internal media error\"";
      }
      else {
	cr->cr_answer_sent = 1;
	soa_activate(nh->nh_soa, NULL);

	/* signal that O/A round is complete */
	sent = "answer";
      }
    }

499
    if (!reason &&
500 501 502
	/* ss->ss_offer_sent && !ss->ss_answer_recv */
	!soa_is_complete(nh->nh_soa)) {
      /* No SDP answer in 2XX response -> terminate call */
503 504
      status = 988, phrase = "Incomplete offer/answer";
      reason = "SIP;cause=488;text=\"Incomplete offer/answer\"";
505 506 507 508
    }
  }

  if (sip)
509
    ack = nta_outgoing_mcreate(nua->nua_nta, NULL, NULL, NULL, msg,
510 511 512 513
			       SIPTAG_END(), TAG_NEXT(tags));

  if (!ack) {
    if (!reason) {
514
      status = 900, phrase = "Cannot send ACK";
515 516 517 518 519 520 521 522 523
      reason = "SIP;cause=500;text=\"Internal Error\"";
    }
    msg_destroy(msg);
  }

  nua_creq_deinit(cr, NULL);	/* Destroy INVITE transaction */
  nta_outgoing_destroy(ack);	/* TR engine keeps this around for T2 */

  if (status < 300) {
524
    signal_call_state_change(nh, status, phrase, nua_callstate_ready,
525 526 527
			     received, sent);
  }
  else {
528 529 530 531 532
    signal_call_state_change(nh, status, phrase, nua_callstate_terminating,
			     0, 0);
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
533 534 535 536 537
  }

  return 0;
}

538
static int
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
process_100rel(nua_handle_t *nh,
	       nta_outgoing_t *orq,
	       sip_t const *sip)
{
  struct nua_session_state *ss = nh->nh_ss;
  struct nua_client_request *cr_invite = ss->ss_crequest;
  struct nua_client_request *cr_prack = nh->nh_cr;

  /* Reliable provisional response */
  sip_content_disposition_t *cd = NULL;
  sip_content_type_t *ct = NULL;
  sip_payload_t *pl = NULL;

  nta_outgoing_t *prack;

  char const *recv = NULL, *sent = NULL;
555
  int status = 408;
556 557 558 559 560
  int offer_sent_in_prack = 0, answer_sent_in_prack = 0;

  su_home_t home[1] = { SU_HOME_INIT(home) };

  if (cr_prack->cr_orq) {
561
    SU_DEBUG_3(("nua(%p): cannot send PRACK because %s is pending\n", nh,
562 563 564 565
		nta_outgoing_method_name(cr_prack->cr_orq)));
    return 0;			/* We have to wait! */
  }

566 567 568
  if (sip && sip->sip_status)
    status = sip->sip_status->st_status;

569 570
  if (!nua_dialog_is_established(nh->nh_ds)) {
    /* Tag the INVITE request */
571 572
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
573

574
    cr_invite->cr_orq =
575 576 577 578 579 580 581 582 583 584 585
      nta_outgoing_tagged(orq, process_response_to_invite, nh,
			  sip->sip_to->a_tag, sip->sip_rseq);
    nta_outgoing_destroy(orq);
    orq = cr_invite->cr_orq;
  }

  if (session_process_response(nh, cr_invite, orq, sip, &recv) < 0) {
    /* XXX */
  }
  else if (cr_invite->cr_offer_recv && !cr_invite->cr_answer_sent) {
    if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
586
	session_make_description(home, nh->nh_soa, &cd, &ct, &pl) < 0)
587 588 589 590 591 592
      /* XXX */;
    else {
      answer_sent_in_prack = 1, sent = "answer";
      soa_activate(nh->nh_soa, NULL);
    }
  }
593
  else if (ss->ss_precondition && status == 183) { /* XXX */
594
    if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
595
	session_make_description(home, nh->nh_soa, &cd, &ct, &pl) < 0)
596 597 598 599 600
      /* XXX */;
    else
      offer_sent_in_prack = 1, sent = "offer";
  }

601
  prack = nta_outgoing_prack(nh->nh_ds->ds_leg, orq,
602
			     process_response_to_prack, nh, NULL,
603
			     sip,
604 605 606 607 608 609 610 611 612 613 614 615 616
			     SIPTAG_CONTENT_DISPOSITION(cd),
			     SIPTAG_CONTENT_TYPE(ct),
			     SIPTAG_PAYLOAD(pl),
			     TAG_END());

  if (prack) {
    cr_prack->cr_event = nua_r_prack;
    cr_prack->cr_orq = prack;
    if (answer_sent_in_prack)
      cr_invite->cr_answer_sent = 1;
    else if (offer_sent_in_prack)
      cr_prack->cr_offer_sent = 1;

617 618 619
    signal_call_state_change(nh,
			     sip->sip_status->st_status,
			     sip->sip_status->st_phrase,
620 621 622 623
			     nua_callstate_proceeding, recv, sent);
  }
  else {
    /* XXX - call state? */
624
    nua_stack_event(nh->nh_nua, nh, NULL, nua_i_error,
625
		    900, "Cannot PRACK",
626
		    TAG_END());
627 628 629 630 631 632 633
  }

  su_home_deinit(home);

  return 0;
}

634
static int
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
process_response_to_prack(nua_handle_t *nh,
			  nta_outgoing_t *orq,
			  sip_t const *sip)
{
  struct nua_client_request *cr = nh->nh_cr;
  int status;
  char const *phrase = "OK", *reason = NULL, *recv = NULL;

  if (sip)
    status = sip->sip_status->st_status, phrase = sip->sip_status->st_phrase;
  else
    status = 408, phrase = sip_408_Request_timeout;

  SU_DEBUG_5(("nua: process_response_to_prack: %u %s\n", status, phrase));

#if 0
  if (nua_creq_check_restart(nh, cr, orq, sip, restart_prack))
    return 0;
#endif

  if (status < 200)
    return 0;
657

658 659
  if (status < 300) {
    if (session_process_response(nh, cr, orq, sip, &recv) < 0) {
660
      status = 900, phrase = "Malformed Session in Response";
661 662 663 664 665 666
      reason = "SIP;status=400;phrase=\"Malformed Session in Response\"";
    }
  }
  else
    nua_stack_process_response(nh, cr, orq, sip, TAG_END());

667 668 669
  if (recv)
    signal_call_state_change(nh, status, phrase,
			     nua_callstate_proceeding, recv, NULL);
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

  if (status < 300 && nh->nh_ss->ss_update_needed)
    nua_stack_update(nh->nh_nua, nh, nua_r_update, NULL);

  return 0;
}

static
char const reason_timeout[] = "SIP;cause=408;text=\"Session timeout\"";

void cancel_invite(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
{
  static tagi_t const timeout_tags[] = {
    { siptag_reason_str, (tag_value_t)reason_timeout },
    { NULL }
  };

687
  signal_call_state_change(nh, 487, "Call Canceled",
688 689 690 691 692
			   nua_callstate_init, NULL, NULL);

  nua_stack_cancel(nh->nh_nua, nh, nua_r_destroy, timeout_tags);
}

693
void
694 695
refresh_invite(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
{
696 697 698
  tagi_t tags[2] = 
    {{ SIPTAG_SUBJECT_STR("Session refresh") }, { TAG_END() }};

699
  if (now > 0 && NH_PGET(nh, update_refresh))
700
    nua_stack_update(nh->nh_nua, nh, nua_r_update, tags);
701
  else if (now > 0)
702
    nua_stack_invite(nh->nh_nua, nh, nua_r_invite, tags);
703 704
  else
    session_timeout(nh, du, SIP_TIME_MAX);
705 706
}

707
static void
708 709 710 711 712
session_timeout(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
{
  if (now > 1) {
    signal_call_state_change(nh, 408, "Session Timeout",
			     nua_callstate_terminating, NULL, NULL);
713 714 715
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason_timeout),
			  TAG_END());
716 717 718 719
  }
}

/** Restart invite (e.g., after 302 or 407) */
720
void
721 722 723 724 725 726 727 728 729 730 731
restart_invite(nua_handle_t *nh, tagi_t *tags)
{
  ua_invite2(nh->nh_nua, nh, nua_r_invite, 1, tags);
}

static int process_response_to_cancel(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip);

/* CANCEL */
int
732 733
nua_stack_cancel(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		 tagi_t const *tags)
734 735 736 737
{
  nua_session_state_t *ss = nh->nh_ss;
  nua_client_request_t *cri = ss->ss_crequest;
  nua_client_request_t *crc = nh->nh_cr;
738

739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
  if (nh && cri->cr_orq && cri->cr_usage &&
      cri->cr_usage->du_pending == cancel_invite) {
    nua_dialog_usage_t *du = cri->cr_usage;
    nta_outgoing_t *orq;

    du->du_pending = NULL;

    /* nh_referral_respond(nh, SIP_487_REQUEST_TERMINATED); */

    if (e)
      orq = nta_outgoing_tcancel(cri->cr_orq, process_response_to_cancel, nh,
				 TAG_NEXT(tags));
    else
      orq = nta_outgoing_tcancel(cri->cr_orq, NULL, NULL, TAG_NEXT(tags));

    if (orq == NULL)
755 756
      return nua_stack_event(nua, nh, NULL, e, 400, "Internal error",
			     TAG_END());
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

    if (e && crc->cr_orq == NULL)
      crc->cr_orq = orq, crc->cr_event = e;

    return 0;
  }

  return UA_EVENT2(e, 481, "No transaction to CANCEL");
}

static int process_response_to_cancel(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip)
{
  return nua_stack_process_response(nh, nh->nh_cr, orq, sip, TAG_END());
}

774 775 776
/* ---------------------------------------------------------------------- */
/* UAS side of INVITE */

777
static void respond_to_invite(nua_t *nua, nua_handle_t *nh,
778
			      int status, char const *phrase,
779 780
			      tagi_t const *tags);

781
static int
782 783
  process_invite1(nua_t *, nua_handle_t**, nta_incoming_t *, msg_t *, sip_t *),
  process_invite2(nua_t *, nua_handle_t *, nta_incoming_t *, sip_t *),
784
  process_prack(nua_handle_t *, nta_reliable_t *, nta_incoming_t *,
785 786 787 788 789
		sip_t const *),
  process_ack_or_cancel(nua_handle_t *, nta_incoming_t *, sip_t const *),
  process_ack(nua_handle_t *, nta_incoming_t *, sip_t const *),
  process_cancel(nua_handle_t *, nta_incoming_t *, sip_t const *),
  process_timeout(nua_handle_t *, nta_incoming_t *);
790

791
/** @internal Process incoming INVITE. */
792 793 794 795 796 797
int nua_stack_process_invite(nua_t *nua,
			     nua_handle_t *nh0,
			     nta_incoming_t *irq,
			     sip_t const *sip)
{
  nua_handle_t *nh = nh0;
798
  msg_t *msg = nta_incoming_getrequest(irq);
799 800 801 802 803 804 805 806 807 808 809 810 811 812
  int status;

  status = process_invite1(nua, &nh, irq, msg, (sip_t *)sip);

  if (status) {
    msg_destroy(msg);
    if (nh != nh0)
      nh_destroy(nua, nh);
    return status;
  }

  return process_invite2(nua, nh, irq, (sip_t *)sip);
}

813
/** @internal Preprocess incoming invite - sure we have a valid request. */
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
static
int process_invite1(nua_t *nua,
		    nua_handle_t **return_nh,
		    nta_incoming_t *irq,
		    msg_t *msg,
		    sip_t *sip)
{
  nua_handle_t *nh = *return_nh;
  nua_handle_t *dnh = nua->nua_dhandle, *nh0 = nh ? nh : dnh;
  nua_server_request_t *sr;
  int have_sdp;
  char const *sdp;
  size_t len;
  sip_user_agent_t const *user_agent = NH_PGET(nh0, user_agent);

829
#if HAVE_SOFIA_SMIME
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
  int sm_status;

  sm_status = sm_decode_message(nua->sm, msg, sip);
  switch(sm_status) {
  case SM_SMIME_DISABLED:
  case SM_ERROR:
    nta_incoming_treply(irq, 493, "Undecipherable", TAG_END());
    return 493;

  case SM_SUCCESS:
    break;
  default:
    break;
  }
#endif

  if (nh0->nh_soa) {
    /* Make sure caller uses application/sdp without compression */
    if (nta_check_session_content(irq, sip,
				  nua->nua_invite_accept,
				  SIPTAG_USER_AGENT(user_agent),
				  SIPTAG_ACCEPT_ENCODING_STR(""),
				  TAG_END()))
      return 415;

    /* Make sure caller accepts application/sdp */
856
    if (nta_check_accept(irq, sip,
857 858 859 860 861 862 863 864 865 866
			 nua->nua_invite_accept,
			 NULL,
			 SIPTAG_USER_AGENT(user_agent),
			 SIPTAG_ACCEPT_ENCODING_STR(""),
			 TAG_END()))
      return 406;
  }

  if (sip->sip_session_expires) {
    unsigned min_se = nh ? nh->nh_ss->ss_min_se : DNH_PGET(dnh, min_se);
867
    if (nta_check_session_expires(irq, sip,
868 869 870
				  min_se,
				  SIPTAG_USER_AGENT(user_agent),
				  TAG_END()))
871
      return 500; /* respond with 500 Internal Server Error  */
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  }

  if (!nh) {
    if (!DNH_PGET(dnh, invite_enable))
      return 403;

    if (!(nh = nua_stack_incoming_handle(nua, irq, sip, nh_has_invite, 1)))
      return 500;
  }

  have_sdp = session_get_description(msg, sip, &sdp, &len);

  if (nh->nh_ss->ss_srequest->sr_irq
      /* XXX || (have_sdp && nh->nh_sr->sr_offer_recv) XXX */) {
    /* Overlapping invites - RFC 3261 14.2 */
    sip_retry_after_t af[1];

    /* Random delay of 0..10 seconds */
    sip_retry_after_init(af)->af_delta = (unsigned)random() % 11U;
    af->af_comment = "Overlapping INVITE Request";

    nta_incoming_treply(irq, 500, af->af_comment,
			SIPTAG_RETRY_AFTER(af),
			TAG_END());
    return 500;
  }

  if (nh->nh_ss->ss_crequest->cr_orq ||
      (have_sdp && nh->nh_cr->cr_orq && nh->nh_cr->cr_offer_sent)) {
    /* Glare - RFC 3261 14.2 and RFC 3311 section 5.2 */
    nta_incoming_treply(irq, SIP_491_REQUEST_PENDING, TAG_END());
    return 491;
  }

  *return_nh = nh;

  sr = nh->nh_ss->ss_srequest; memset(sr, 0, sizeof *sr);

  if (nh->nh_soa) {
    soa_init_offer_answer(nh->nh_soa);

    if (have_sdp) {
      if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
	SU_DEBUG_5(("nua(%p): error parsing SDP in INVITE\n", nh));
	nta_incoming_treply(irq, 400, "Bad Session Description", TAG_END());
	return 400;
      }
      sr->sr_offer_recv = 1;
    }
  }

  /** Add a dialog usage */
924 925
  if (!nh->nh_ss->ss_usage)
    nh->nh_ss->ss_usage =
926 927 928 929 930 931 932 933
      nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
  if (!nh->nh_ss->ss_usage) {
    nta_incoming_treply(irq, SIP_500_INTERNAL_SERVER_ERROR, TAG_END());
    return 500;
  }

  sr->sr_msg = msg;
  sr->sr_irq = irq;
934

935 936 937
  return 0;
}

938
/** @internal Process incoming invite - initiate media, etc. */
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
static
int process_invite2(nua_t *nua,
		    nua_handle_t *nh,
		    nta_incoming_t *irq,
		    sip_t *sip)
{
  nua_session_state_t *ss = nh->nh_ss;
  nua_server_request_t *sr = ss->ss_srequest;

  ss->ss_100rel = NH_PGET(nh, early_media);
  ss->ss_precondition = sip_has_feature(sip->sip_require, "precondition");
  if (ss->ss_precondition)
    ss->ss_100rel = 1;

  /* Session Timer negotiation */
954
  init_session_timer(nh, sip);
955

956
  nua_dialog_uas_route(nh, nh->nh_ds, sip, 1);	/* Set route and tags */
957 958 959 960 961 962 963

  nta_incoming_bind(irq, process_ack_or_cancel, nh);

  assert(ss->ss_state >= nua_callstate_ready ||
	 ss->ss_state == nua_callstate_init);

  /* Magical value indicating autoanswer within respond_to_invite() */
964
#define AUTOANSWER ((void*)-1)
965 966 967

  if (NH_PGET(nh, auto_answer) ||
      /* Auto-answert to re-INVITE unless auto_answer is set to 0 */
968
      (ss->ss_state == nua_callstate_ready &&
969 970 971 972 973 974 975 976
       !NH_PISSET(nh, auto_answer))) {
    respond_to_invite(nua, nh, SIP_200_OK, AUTOANSWER);
    return 0;
  }

  ss->ss_srequest->sr_respond = respond_to_invite;

  if (NH_PGET(nh, auto_alert)) {
977
    if (ss->ss_100rel &&
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
	(sip_has_feature(nh->nh_ds->ds_remote_ua->nr_supported, "100rel") ||
	 sip_has_feature(nh->nh_ds->ds_remote_ua->nr_require, "100rel"))) {
      respond_to_invite(nua, nh, SIP_183_SESSION_PROGRESS, AUTOANSWER);
    }
    else {
      respond_to_invite(nua, nh, SIP_180_RINGING, AUTOANSWER);
    }
  }
  else {
    nta_incoming_treply(irq, SIP_100_TRYING, TAG_END());

    nua_stack_event(nh->nh_nua, nh, sr->sr_msg,
	     nua_i_invite, SIP_100_TRYING,
	     NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
	     TAG_END());
    sr->sr_msg = NULL;

995 996
    signal_call_state_change(nh, SIP_100_TRYING,
			     nua_callstate_received,
997 998 999 1000 1001 1002
			     sr->sr_offer_recv ? "offer" : 0, 0);
  }

  return 0;
}

1003
/** @internal Respond to an INVITE request.
1004 1005 1006 1007
 *
 * XXX - use tags to indicate when to use reliable responses.
 * XXX - change prototype.
 */
1008
static
1009
void respond_to_invite(nua_t *nua, nua_handle_t *nh,
1010
		       int status, char const *phrase,
1011 1012 1013 1014 1015 1016 1017
		       tagi_t const *tags)
{
  su_home_t home[1] = { SU_HOME_INIT(home) };
  msg_t *msg;
  sip_t *sip;
  int reliable;
  int original_status = status;
1018
  sip_warning_t *warning = NULL;
1019 1020 1021 1022 1023
  nua_dialog_state_t *ds = nh->nh_ds;
  nua_session_state_t *ss = nh->nh_ss;
  nua_server_request_t *sr = ss->ss_srequest;

  int autoanswer = 0, offer = 0, answer = 0;
1024
  
1025
  enter;
1026 1027 1028 1029

  if (ss->ss_srequest->sr_irq == NULL ||
      nta_incoming_status(ss->ss_srequest->sr_irq) >= 200) {
    nua_stack_event(nh->nh_nua, nh, NULL,
1030
	     nua_i_error, 900, "No INVITE request to response", TAG_END());
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    return;
  }

  if (tags == AUTOANSWER)
    autoanswer = 1, tags = NULL;

  assert(ss->ss_usage);

  if (nh->nh_soa)
    soa_set_params(nh->nh_soa, TAG_NEXT(tags));

1042
  reliable =
1043 1044 1045 1046
    (status >= 200)
    || (status > 100 &&
	ds->ds_remote_ua->nr_require &&
	sip_has_feature(ds->ds_remote_ua->nr_require, "100rel"))
1047 1048 1049 1050 1051 1052 1053
    || (status > 100 && !NH_PGET(nh, only183_100rel) && 
	NH_PGET(nh, early_media) && 
	ds->ds_remote_ua->nr_supported &&
	sip_has_feature(ds->ds_remote_ua->nr_supported, "100rel"))
    || (status == 183 &&
	ds->ds_remote_ua->nr_supported &&
	sip_has_feature(ds->ds_remote_ua->nr_supported, "100rel"))
1054 1055 1056 1057 1058 1059 1060 1061
    || (status == 183 &&
	ds->ds_remote_ua->nr_require &&
	sip_has_feature(ds->ds_remote_ua->nr_require, "precondition"))
    || (status > 100 &&
	ds->ds_remote_ua->nr_require &&
	sip_has_feature(ds->ds_remote_ua->nr_require, "precondition") &&
	sr->sr_offer_recv && !sr->sr_answer_sent);

1062 1063
  msg = nh_make_response(nua, nh, ss->ss_srequest->sr_irq,
			 status, phrase,
1064 1065 1066
			 TAG_IF(status < 300, NUTAG_ADD_CONTACT(1)),
			 SIPTAG_SUPPORTED(NH_PGET(nh, supported)),
			 TAG_NEXT(tags));
1067
  sip = sip_object(msg);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

  assert(sip);			/* XXX */

  if (!nh->nh_soa)
    /* Xyzzy */;
  else if (status >= 300) {
    soa_clear_remote_sdp(nh->nh_soa);
  }
  else if (status >= 200 || ss->ss_100rel) {
    if ((sr->sr_offer_recv && sr->sr_answer_sent) ||
	(sr->sr_offer_sent && !sr->sr_answer_recv))
      /* Nothing to do */;
    else if (sr->sr_offer_recv && !sr->sr_answer_sent) {
1081 1082 1083 1084
      if (soa_generate_answer(nh->nh_soa, NULL) < 0) {
	int wcode;
	char const *text;
	char const *host = "invalid.";
1085
	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
1086 1087 1088 1089 1090 1091 1092 1093 1094

	wcode = soa_get_warning(nh->nh_soa, &text);
	if (wcode) {
	  if (sip->sip_contact)
	    host = sip->sip_contact->m_url->url_host;
	  warning = sip_warning_format(home, "%u %s \"%s\"",
				       wcode, host, text);
	}
      }
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
      else {
	answer = 1;
	soa_activate(nh->nh_soa, NULL);
	/* signal that O/A answer sent (answer to invite) */
      }
    }
    else if (!sr->sr_offer_recv && !sr->sr_offer_sent) {
      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0)
	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
      else
	offer = 1;
    }

    if (offer || answer) {
1109
      if (session_include_description(nh->nh_soa, msg, sip) < 0)
1110
	SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
1111 1112 1113 1114
    }
  }

  if (ss->ss_refresher && 200 <= status && status < 300)
1115
    use_session_timer(nh, 1, msg, sip);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

#if HAVE_SOFIA_SMIME
  if (nua->sm->sm_enable && sdp) {
    int sm_status;

    sm_status = sm_encode_message(nua->sm, msg, sip, SM_ID_NULL);

    switch (sm_status) {
    case SM_SUCCESS:
      break;
    case SM_ERROR:
      status = 500, phrase = "S/MIME processing error";
      break;
    case SM_CERT_NOTFOUND:
    case SM_CERTFILE_NOTFOUND:
      status = 500, phrase = "S/MIME certificate error";
      break;
    }
  }
#endif

  if (reliable && status < 200) {
    nta_reliable_t *rel;
1139
    rel = nta_reliable_mreply(ss->ss_srequest->sr_irq,
1140 1141
			      process_prack, nh, msg);
    if (!rel)
1142
      SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
1143 1144 1145 1146 1147 1148 1149
  }

  if (reliable && status < 200)
    /* we are done */;
  else if (status != original_status) {    /* Error responding */
    assert(status >= 200);
    ss->ss_srequest->sr_respond = NULL;
1150
    nta_incoming_treply(ss->ss_srequest->sr_irq,
1151
			status, phrase,
1152
			SIPTAG_WARNING(warning),
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
			TAG_END());
    msg_destroy(msg), msg = NULL;
  }
  else {
    if (status >= 200)
      ss->ss_srequest->sr_respond = NULL;
    nta_incoming_mreply(ss->ss_srequest->sr_irq, msg);
  }

  if (autoanswer) {
    nua_stack_event(nh->nh_nua, nh, sr->sr_msg,
	     nua_i_invite, status, phrase,
	     NH_ACTIVE_MEDIA_TAGS(1, nh->nh_soa),
	     TAG_END());
    sr->sr_msg = NULL;
  }
  else if (status != original_status)
    nua_stack_event(nua, nh, NULL, nua_i_error, status, phrase, TAG_END());

  if (status >= 300)
    offer = 0, answer = 0;

  if (offer)
    sr->sr_offer_sent = 1;
  else if (answer)
    sr->sr_answer_sent = 1 + reliable;

  /* Update session state */
  assert(ss->ss_state != nua_callstate_calling);
  assert(ss->ss_state != nua_callstate_proceeding);

1184 1185 1186 1187
  signal_call_state_change(nh, status, phrase,
			   status >= 300
			   ? nua_callstate_init
			   : status >= 200
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
			   ? nua_callstate_completed
			   : nua_callstate_early,
			   autoanswer && sr->sr_offer_recv ? "offer" : 0,
			   offer ? "offer" : answer ? "answer" : 0);

  if (status == 180)
    ss->ss_alerting = 1;
  else if (status >= 200)
    ss->ss_alerting = 0;

  if (status >= 200) {
    ss->ss_usage->du_ready = 1;
  }

  if (status >= 300) {
    if (nh->nh_soa)
      soa_init_offer_answer(nh->nh_soa);
    nta_incoming_destroy(ss->ss_srequest->sr_irq);
    ss->ss_srequest->sr_irq = NULL;
    ss->ss_srequest->sr_respond = NULL;
  }

  su_home_deinit(home);

  if (ss->ss_state == nua_callstate_init)
    nsession_destroy(nh);
}


1217
/** @internal Process ACK or CANCEL or timeout (no ACK) for incoming INVITE */
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
static
int process_ack_or_cancel(nua_handle_t *nh,
			  nta_incoming_t *irq,
			  sip_t const *sip)
{
  int retval;
  nua_server_request_t *sr = nh->nh_ss->ss_srequest;

  enter;

  if (sip && sip->sip_request->rq_method == sip_method_ack)
    retval = process_ack(nh, irq, sip);
  else if (sip && sip->sip_request->rq_method == sip_method_cancel)
    retval = process_cancel(nh, irq, sip);
  else
    retval = process_timeout(nh, irq);

  assert(sr->sr_irq == irq);
  nta_incoming_destroy(sr->sr_irq);
  memset(sr, 0, sizeof *sr);

  return retval;
}

1242
/** @internal Process PRACK or (timeout from 100rel) */
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
static
int process_prack(nua_handle_t *nh,
		  nta_reliable_t *rel,
		  nta_incoming_t *irq,
		  sip_t const *sip)
{
  struct nua_session_state *ss = nh->nh_ss;
  nua_server_request_t *sr = ss->ss_srequest;
  int status = 200; char const *phrase = sip_200_OK;
  char const *recv = NULL, *sent = NULL;

  nta_reliable_destroy(rel);

  if (!sr->sr_irq) /* XXX  */
    return 481;

  if (sip)
    /* received PRACK */;
  else if (sr->sr_respond == NULL) { /* Final response interrupted 100rel */
    /* Ignore */
    return 200;
  }
1265
  else if (sip == NULL) {
1266 1267 1268 1269 1270
    SET_STATUS(504, "Reliable Response Timeout");

    respond_to_invite(nh->nh_nua, nh, status, phrase, NULL);

    nua_stack_event(nh->nh_nua, nh, NULL,
1271
		    nua_i_error, status, phrase, TAG_END());
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

    return status;
  }

  if (nh->nh_soa) {
    msg_t *msg = nta_incoming_getrequest(irq);
    char const *sdp;
    size_t len;

    if (session_get_description(msg, sip, &sdp, &len)) {
      su_home_t home[1] = { SU_HOME_INIT(home) };

      sip_content_disposition_t *cd = NULL;
      sip_content_type_t *ct = NULL;
      sip_payload_t *pl = NULL;

      if (soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0) {
	SU_DEBUG_5(("nua(%p): error parsing SDP in INVITE\n", nh));
	msg_destroy(msg);
	status = 400, phrase = "Bad Session Description";
      }

      /* Respond to PRACK */

      if (status >= 300)
	;
      else if (sr->sr_offer_sent) {
	recv = "answer";
	sr->sr_answer_recv = 1;
	if (soa_process_answer(nh->nh_soa, NULL) < 0)
	  status = soa_error_as_sip_response(nh->nh_soa, &phrase);
      }
      else {
	recv = "offer";
	if (soa_generate_answer(nh->nh_soa, NULL) < 0) {
	  status = soa_error_as_sip_response(nh->nh_soa, &phrase);
	}
	else {
1310
	  session_make_description(home, nh->nh_soa, &cd, &ct, &pl);
1311 1312 1313 1314 1315 1316 1317 1318 1319
	  sent = "answer";
	}
      }

      if (nta_incoming_treply(irq, status, phrase,
			      SIPTAG_CONTENT_DISPOSITION(cd),
			      SIPTAG_CONTENT_TYPE(ct),
			      SIPTAG_PAYLOAD(pl),
			      TAG_END()) < 0)
1320
	/* Respond with 500 if nta_incoming_treply() failed */
1321
	SET_STATUS1(SIP_500_INTERNAL_SERVER_ERROR);
1322 1323 1324 1325 1326 1327 1328 1329

      su_home_deinit(home);
    }

    msg_destroy(msg);
  }

  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
1330
		  nua_i_prack, status, phrase, TAG_END());
1331 1332 1333

  if (status < 300 && (recv || sent)) {
    soa_activate(nh->nh_soa, NULL);
1334
    signal_call_state_change(nh, status, phrase,
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
			     nua_callstate_early, recv, sent);
  }

  if (status < 300 &&
      NH_PGET(nh, auto_alert) && !ss->ss_alerting && !ss->ss_precondition)
    respond_to_invite(nh->nh_nua, nh, SIP_180_RINGING, NULL);

  return status;
}

int process_ack(nua_handle_t *nh,
		nta_incoming_t *irq,
		sip_t const *sip)
{
  struct nua_session_state *ss = nh->nh_ss;
  nua_server_request_t *sr = ss->ss_srequest;
  msg_t *msg = nta_incoming_getrequest_ackcancel(irq);
  char const *recv = NULL;

  if (nh->nh_soa && sr->sr_offer_sent && !sr->sr_answer_recv) {
    char const *sdp;
    size_t len;

    if (!session_get_description(msg, sip, &sdp, &len) ||
	!(recv = "answer") ||
	soa_set_remote_sdp(nh->nh_soa, NULL, sdp, len) < 0 ||
	soa_process_answer(nh->nh_soa, NULL) < 0 ||
	soa_activate(nh->nh_soa, NULL)) {
      int status; char const *phrase, *reason;

      status = soa_error_as_sip_response(nh->nh_soa, &phrase);
      reason = soa_error_as_sip_reason(nh->nh_soa);

1368
      nua_stack_event(nh->nh_nua, nh, msg,
1369
	       nua_i_ack, status, phrase, TAG_END());
1370
      nua_stack_event(nh->nh_nua, nh, NULL,
1371
	       nua_i_media_error, status, phrase, TAG_END());
1372 1373

      signal_call_state_change(nh, 488, "Offer-Answer Error",
1374
			       nua_callstate_terminating, recv, 0);
1375 1376 1377
      nua_stack_post_signal(nh, nua_r_bye,
			    SIPTAG_REASON_STR(reason),
			    TAG_END());
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406

      return 0;
    }
  }

  soa_clear_remote_sdp(nh->nh_soa);

  nua_stack_event(nh->nh_nua, nh, msg, nua_i_ack, SIP_200_OK, TAG_END());

  signal_call_state_change(nh, 200, "OK", nua_callstate_ready, recv, 0);

  set_session_timer(nh);

  return 0;
}

/* CANCEL  */
static
int process_cancel(nua_handle_t *nh,
		   nta_incoming_t *irq,
		   sip_t const *sip)
{
  struct nua_session_state *ss = nh->nh_ss;
  msg_t *msg = nta_incoming_getrequest_ackcancel(irq);

  nua_stack_event(nh->nh_nua, nh, msg, nua_i_cancel, SIP_200_OK, TAG_END());

  signal_call_state_change(nh, 0, "Received CANCEL", nua_callstate_init, 0, 0);

1407
  if (nh->nh_soa && ss->ss_state < nua_callstate_ready) {
1408
    soa_terminate(nh->nh_soa, NULL);
1409 1410
    nsession_destroy(nh);
  }
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429

  return 0;
}

/* Timeout (no ACK or PRACK received) */
static
int process_timeout(nua_handle_t *nh,
		    nta_incoming_t *irq)
{
  struct nua_session_state *ss = nh->nh_ss;

  nua_stack_event(nh->nh_nua, nh, 0, nua_i_error,
	   408, "Response timeout",
	   TAG_END());

  soa_terminate(nh->nh_soa, NULL);

  if (ss->ss_state == nua_callstate_ready) {
    /* send BYE if 200 OK (or 183 to re-INVITE) timeouts  */
1430
    signal_call_state_change(nh, 0, "Timeout",
1431
			     nua_callstate_terminating, 0, 0);
1432
    nua_stack_post_signal(nh, nua_r_bye,
1433 1434 1435 1436
		 SIPTAG_REASON_STR("SIP;cause=408;text=\"ACK Timeout\""),
		 TAG_END());
  }
  else {
1437
    nta_incoming_treply(irq, SIP_504_GATEWAY_TIME_OUT,
1438 1439 1440
			SIPTAG_REASON_STR("SIP;cause=504;"
					  "text=\"PRACK Timeout\""),
			TAG_END());
1441
    signal_call_state_change(nh, 0, "Timeout",
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
			     nua_callstate_init, 0, 0);
  }

  return 0;
}


/* ---------------------------------------------------------------------- */
/* Session timer */

/** Add timer featuretag and Session-Expires/Min-SE headers */
static int
1454
use_session_timer(nua_handle_t *nh, int uas, msg_t *msg, sip_t *sip)
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
{
  struct nua_session_state *ss = nh->nh_ss;

  sip_min_se_t min_se[1];
  sip_session_expires_t session_expires[1];

  static sip_param_t const x_params_uac[] = {"refresher=uac", NULL};
  static sip_param_t const x_params_uas[] = {"refresher=uas", NULL};

  /* Session-Expires timer */
  if ((NH_PGET(nh, refresher) == 0 &&
       NH_PGET(nh, session_timer) == 0) ||
      /* Is timer feature supported? */
      !sip_has_supported(NH_PGET(nh, supported), "timer"))
    return 0;
1470

1471 1472
  sip_min_se_init(min_se)->min_delta = ss->ss_min_se;
  sip_session_expires_init(session_expires)->x_delta = ss->ss_session_timer;
1473

1474 1475 1476 1477
  if (ss->ss_refresher == nua_remote_refresher)
    session_expires->x_params = uas ? x_params_uac : x_params_uas;
  else if (ss->ss_refresher == nua_local_refresher)
    session_expires->x_params = uas ? x_params_uas : x_params_uac;
1478 1479

  sip_add_tl(msg, sip,
1480 1481
	     TAG_IF(ss->ss_session_timer,
		    SIPTAG_SESSION_EXPIRES(session_expires)),
1482
	     TAG_IF(ss->ss_min_se != 0
1483
		    /* Min-SE: 0 is optional with initial INVITE */
1484 1485 1486
		    || ss->ss_state != nua_callstate_init,
		    SIPTAG_MIN_SE(min_se)),
	     TAG_IF(ss->ss_refresher == nua_remote_refresher,
1487 1488
		    SIPTAG_REQUIRE_STR("timer")),
	     TAG_END());
1489

1490 1491 1492
  return 1;
}

1493 1494
static int
init_session_timer(nua_handle_t *nh, sip_t const *sip)
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
{
  struct nua_session_state *ss = nh->nh_ss;

  int server;

  ss->ss_refresher = nua_no_refresher;

  /* Check if we support the timer feature */
  if (!sip->sip_session_expires ||
      !sip_has_supported(NH_PGET(nh, supported), "timer")) {
    return 0;
  }

  ss->ss_session_timer = sip->sip_session_expires->x_delta;

1510
  if (sip->sip_min_se != NULL
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
      && sip->sip_min_se->min_delta > ss->ss_min_se)
    ss->ss_min_se = sip->sip_min_se->min_delta;

  server = sip->sip_request != NULL;

  if (!str0casecmp("uac", sip->sip_session_expires->x_refresher))
    ss->ss_refresher = server ? nua_remote_refresher : nua_local_refresher;
  else if (!str0casecmp("uas", sip->sip_session_expires->x_refresher))
    ss->ss_refresher = server ? nua_local_refresher : nua_remote_refresher;
  else if (!server)
    return 0;			/* XXX */
  /* User preferences */
  else if (nua_local_refresher == NH_PGET(nh, refresher))
    ss->ss_refresher = nua_local_refresher;
  else
    ss->ss_refresher = nua_remote_refresher;

  return 0;
}

static void
set_session_timer(nua_handle_t *nh)
{
  struct nua_session_state *ss = nh->nh_ss;
  nua_dialog_usage_t *du = ss->ss_usage;

  assert(du);

  if (du == NULL)
    ;
  else if (ss->ss_refresher == nua_local_refresher) {
    nua_dialog_usage_set_refresh(du, ss->ss_session_timer);
    du->du_pending = refresh_invite; /* Set timer */
  }
  else if (ss->ss_refresher == nua_remote_refresher) {
    nua_dialog_usage_set_refresh(du, ss->ss_session_timer + 32);
    du->du_pending = session_timeout; /* Set timer */
  }
  else {
    du->du_refresh = 0;
    du->du_pending = NULL;
  }
}

static int
is_session_timer_set(nua_session_state_t *ss)
{
1558
  return ss->ss_usage &&
1559 1560 1561 1562 1563 1564 1565 1566
    (ss->ss_usage->du_pending == refresh_invite ||
     ss->ss_usage->du_pending == session_timeout);
}

/* ---------------------------------------------------------------------- */
/* Automatic notifications from a referral */

static int
1567
nh_referral_check(nua_handle_t *nh, tagi_t const *tags)
1568 1569 1570 1571 1572 1573
{
  sip_event_t const *event = NULL;
  int pause = 1;
  struct nua_referral *ref = nh->nh_referral;
  nua_handle_t *ref_handle = ref->ref_handle;

1574
  if (!ref_handle
1575
      &&
1576 1577
      tl_gets(tags,
	      NUTAG_NOTIFY_REFER_REF(ref_handle),
1578 1579
	      NUTAG_REFER_EVENT_REF(event),
	      NUTAG_REFER_PAUSE_REF(pause),
1580
	      TAG_END()) == 0
1581
      &&
1582
      tl_gets(nh->nh_tags,
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
	      NUTAG_NOTIFY_REFER_REF(ref_handle),
	      NUTAG_REFER_EVENT_REF(event),
	      NUTAG_REFER_PAUSE_REF(pause),
	      TAG_END()) == 0)
    return 0;

  if (!ref_handle)
    return 0;

  /* Remove nh_referral and nh_notevent */
  tl_tremove(nh->nh_tags,
1594 1595
	     NUTAG_NOTIFY_REFER(ref_handle),
	     TAG_IF(event, NUTAG_REFER_EVENT(event)),
1596
	     TAG_END());
1597

1598 1599
  if (event)
    ref->ref_event = sip_event_dup(nh->nh_home, event);
1600 1601

  if (!nh_validate(nh->nh_nua, ref_handle)) {
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    SU_DEBUG_3(("nua: invalid NOTIFY_REFER handle\n"));
    return -1;
  }
  else if (!ref->ref_event) {
    SU_DEBUG_3(("nua: NOTIFY event missing\n"));
    return -1;
  }

  if (ref_handle != ref->ref_handle) {
    if (ref->ref_handle)
      nua_handle_unref(ref->ref_handle);
    ref->ref_handle = nua_handle_ref(ref_handle);
  }

#if 0
  if (pause) {
    /* Pause media on REFER handle */
    nmedia_pause(nua, ref_handle->nh_nm, NULL);
  }
#endif

  return 0;
}


1627 1628
static void
nh_referral_respond(nua_handle_t *nh, int status, char const *phrase)
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642
{
  char payload[128];
  char const *substate;
  struct nua_referral *ref = nh->nh_referral;

  if (!nh_validate(nh->nh_nua, ref->ref_handle)) {
    if (ref) {
      if (ref->ref_handle)
	SU_DEBUG_1(("nh_handle_referral: stale referral handle %p\n",
		    ref->ref_handle));
      ref->ref_handle = NULL;
    }
    return;
  }
1643

1644 1645 1646 1647 1648 1649
  /* XXX - we should have a policy here whether to send 101..199 */

  assert(ref->ref_event);

  if (status >= 300)
    status = 503, phrase = sip_503_Service_unavailable;
1650

1651
  snprintf(payload, sizeof(payload), "SIP/2.0 %03u %s\r\n", status, phrase);
1652

1653 1654 1655 1656 1657 1658
  if (status < 200)
    substate = "active";
  else
    substate = "terminated ;reason=noresource";

  nua_stack_post_signal(ref->ref_handle,
1659 1660 1661 1662 1663 1664
			nua_r_notify,
			SIPTAG_EVENT(ref->ref_event),
			SIPTAG_SUBSCRIPTION_STATE_STR(substate),
			SIPTAG_CONTENT_TYPE_STR("message/sipfrag"),
			SIPTAG_PAYLOAD_STR(payload),
			TAG_END());
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

  if (status < 200)
    return;

  su_free(nh->nh_home, ref->ref_event), ref->ref_event = NULL;

  nua_handle_unref(ref->ref_handle), ref->ref_handle = NULL;
}


/** Zap the session associated with the handle */
static
void nsession_destroy(nua_handle_t *nh)
{
  struct nua_session_state *ss = nh->nh_ss;

  ss->ss_active = 0;
  ss->ss_state = nua_callstate_init;

  /* Remove usage */
  if (ss->ss_usage)
    nua_dialog_usage_remove(nh, nh->nh_ds, ss->ss_usage);
  ss->ss_usage = 0;

  nh->nh_has_invite = 0;

  if (nh->nh_soa)
    soa_destroy(nh->nh_soa), nh->nh_soa = NULL;

  ss->ss_srequest->sr_respond = NULL;

  SU_DEBUG_5(("nua: terminated session %p\n", nh));
}


/* ======================================================================== */
/* INFO */

static int process_response_to_info(nua_handle_t *nh,
				       nta_outgoing_t *orq,
				       sip_t const *sip);

int
nua_stack_info(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
{
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg;

  if (nh_is_special(nh)) {
1714
    return UA_EVENT2(e, 900, "Invalid handle for INFO");
1715 1716
  }
  else if (cr->cr_orq) {
1717
    return UA_EVENT2(e, 900, "Request already in progress");
1718 1719 1720 1721
  }

  nua_stack_init_handle(nua, nh, nh_has_nothing, NULL, TAG_NEXT(tags));

1722
  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
			 SIP_METHOD_INFO ,
			 NUTAG_ADD_CONTACT(1),
			 TAG_NEXT(tags));

  cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				    process_response_to_info, nh, NULL,
				    msg,
				    SIPTAG_END(), TAG_NEXT(tags));
  if (!cr->cr_orq) {
    msg_destroy(msg);
1733
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
  }

  return cr->cr_event = e;
}

void restart_info(nua_handle_t *nh, tagi_t *tags)
{
  nua_creq_restart(nh, nh->nh_cr, process_response_to_info, tags);
}

static int process_response_to_info(nua_handle_t *nh,
				    nta_outgoing_t *orq,
				    sip_t const *sip)
{
  if (nua_creq_check_restart(nh, nh->nh_cr, orq, sip, restart_info))
    return 0;
  return nua_stack_process_response(nh, nh->nh_cr, orq, sip, TAG_END());
}

int nua_stack_process_info(nua_t *nua,
			   nua_handle_t *nh,
			   nta_incoming_t *irq,
			   sip_t const *sip)
{
  nua_stack_event(nh->nh_nua, nh, nta_incoming_getrequest(irq),
	   nua_i_info, SIP_200_OK, TAG_END());

  return 200;		/* Respond automatically with 200 Ok */
}


/* ======================================================================== */
/* UPDATE */

static int process_response_to_update(nua_handle_t *nh,
				       nta_outgoing_t *orq,
				       sip_t const *sip);

int
nua_stack_update(nua_t *nua, nua_handle_t *nh, nua_event_t e, tagi_t const *tags)
{
  struct nua_session_state *ss = nh->nh_ss;
  struct nua_client_request *cr = nh->nh_cr;
  struct nua_client_request *cri = ss->ss_crequest;
  struct nua_server_request *sri = ss->ss_srequest;
  msg_t *msg;
  sip_t *sip;
  char const *offer_sent = 0;

  if (!nh_has_session(nh))
1784
    return UA_EVENT2(e, 900, "Invalid handle for UPDATE");
1785
  else if (cr->cr_orq)
1786
    return UA_EVENT2(e, 900, "Request already in progress");
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803

  nua_stack_init_handle(nua, nh, nh_has_nothing, NULL, TAG_NEXT(tags));

  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
			 SIP_METHOD_UPDATE,
			 NUTAG_USE_DIALOG(1),
			 NUTAG_ADD_CONTACT(1),
			 TAG_NEXT(tags));
  sip = sip_object(msg);

  if (sip) {
    if (nh->nh_soa && !sip->sip_payload &&
	!(cri->cr_offer_sent && !cri->cr_answer_recv) &&
	!(cri->cr_offer_recv && !cri->cr_answer_sent) &&
	!(sri->sr_offer_sent && !sri->sr_answer_recv) &&
	!(sri->sr_offer_recv && !sri->sr_answer_sent)) {
      soa_init_offer_answer(nh->nh_soa);
1804

1805
      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
1806
	  session_include_description(nh->nh_soa, msg, sip) < 0) {
1807 1808 1809 1810
	if (ss->ss_state < nua_callstate_ready) {
	  /* XXX */
	}
	msg_destroy(msg);
1811
	return UA_EVENT2(e, 900, "Local media failed");
1812 1813 1814 1815 1816