nua_session.c 114 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
 *
 * @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>
46
#include <sofia-sip/su_uniqueid.h>
47 48 49

#define NTA_LEG_MAGIC_T      struct nua_handle_s
#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
50
#define NTA_INCOMING_MAGIC_T struct nua_server_request
51 52 53 54 55 56 57 58 59
#define NTA_RELIABLE_MAGIC_T struct nua_handle_s

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

#ifndef SDP_H
typedef struct sdp_session_s sdp_session_t;
#endif

60
/* ---------------------------------------------------------------------- */
61

62 63 64 65 66 67 68 69 70 71 72 73 74
/** @enum nua_callstate

The states for SIP session established with INVITE.

Initially the call states follow the state of the INVITE transaction. If the
initial INVITE transaction fails, the call is terminated. The status codes
401 and 407 are an exception: if the client (on the left side in the diagram
below) receives them, it enters in #nua_callstate_authenticating state.

If a re-INVITE transaction fails, the result depends on the status code in
failure. The call can return to the ready state, be terminated immediately,
or be terminated gracefully. The proper action to take is determined with
sip_response_terminates_dialog().			   
75 76

@sa @ref nua_call_model, #nua_i_state, nua_invite(), #nua_i_invite
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
							   
@par Session State Diagram				   
							   
@code							   
  			 +----------+			   
  			 |          |---------------------+
  			 |   Init   |                     |
  			 |          |----------+          |
  			 +----------+          |          |
  			  |        |           |          |
                 --/INVITE|        |INVITE/100 |          |
                          V        V           |          |
     		+----------+      +----------+ |          |
       +--------|          |      |          | |          |
       |  18X +-| Calling  |      | Received | |INVITE/   |
       |   /- | |          |      |          | |  /18X    |
       |      V +----------+      +----------+ V          |
       |   +----------+ |           |     |  +----------+ |
       |---|          | |2XX     -/ |  -/ |  |          | |
       |   | Proceed- | | /-     2XX|  18X|  |  Early   | |INVITE/
       |   |   ing    | |           |     +->|          | |  /200
       |   +----------+ V           V        +----------+ |
       |     |  +----------+      +----------+   | -/     |
       |  2XX|  |          |      |          |<--+ 2XX    |
       |   /-|  | Complet- |      | Complete |<-----------+
       |     +->|   ing    |      |          |------+
       |        +----------+      +----------+      |
       |                  |        |      |         |
       |401,407/     -/ACK|        |ACK/- |timeout/ |
       | /ACK             V        V      | /BYE    |
       |                 +----------+     |         |
       |                 |          |     |         |
       |              +--|  Ready   |     |         |
       |              |  |          |     |         |
       |              |  +----------+     |         |
       |              |       |           |         |
       |         BYE/ |       |-/BYE      |         |BYE/
       V         /200 |       V           |         |/200
  +----------+        |  +----------+     |         |
  |          |        |  |          |     |         |
  |Authentic-|        |  | Terminat-|<----+         |
  |  ating   |        |  |   ing    |               |
  +----------+        |  +----------+               |
                      |       |                     |
                      |       |[23456]XX/-          |
                      |       V                     |
                      |  +----------+               |
                      |  |          |               |
                      +->|Terminated|<--------------+
                         |          |
                         +----------+
                              | 
                              V
                         +----------+
        		 |          |
                         |   Init   |
			 |          |
134 135
          		 +----------+
@endcode			      
136 137
*/			      
			      
138 139 140
/* ---------------------------------------------------------------------- */
/* Session event usage */

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
/** Session-related state */
typedef struct nua_session_usage
{
  /* enum nua_callstate */
  unsigned        ss_state:4;		/**< Session status (enum nua_callstate) */
  
  unsigned        ss_100rel:1;	        /**< Use 100rel, send 183 */
  unsigned        ss_alerting:1;	/**< 180 is sent/received */
  
  unsigned        ss_update_needed:2;	/**< Send an UPDATE (do O/A if > 1) */

  unsigned        ss_precondition:1;	/**< Precondition required */

  unsigned        ss_timer_set:1;       /**< We have active session timer. */
  unsigned        : 0;
  
  unsigned        ss_session_timer;	/**< Value of Session-Expires (delta) */
  unsigned        ss_min_se;		/**< Minimum session expires */
  enum nua_session_refresher ss_refresher; /**< none, local or remote */

  char const     *ss_ack_needed;	/**< If non-null, need to send an ACK
					 * (do O/A, if "offer" or "answer")
					 */

165
  nua_client_request_t ss_crequest[1];  /* Outgoing invite */
166
} nua_session_usage_t;
167 168

static char const *nua_session_usage_name(nua_dialog_usage_t const *du);
169
static int nua_session_usage_add(nua_handle_t *nh,
170 171
				 nua_dialog_state_t *ds,
				 nua_dialog_usage_t *du);
172
static void nua_session_usage_remove(nua_handle_t *nh,
173 174
				     nua_dialog_state_t *ds,
				     nua_dialog_usage_t *du);
175
static void nua_session_usage_refresh(nua_owner_t *,
176
				      nua_dialog_state_t *,
177 178 179
				      nua_dialog_usage_t *,
				      sip_time_t now);
static int nua_session_usage_shutdown(nua_owner_t *,
180 181
				      nua_dialog_state_t *,
				      nua_dialog_usage_t *);
182 183 184

static nua_usage_class const nua_session_usage[1] = {
  {
185
    sizeof (nua_session_usage_t),
186 187 188 189
    sizeof nua_session_usage,
    nua_session_usage_add,
    nua_session_usage_remove,
    nua_session_usage_name,
190 191 192
    NULL,
    nua_session_usage_refresh,
    nua_session_usage_shutdown
193 194 195 196 197 198 199
  }};

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

200 201
static
int nua_session_usage_add(nua_handle_t *nh,
202 203 204
			   nua_dialog_state_t *ds,
			   nua_dialog_usage_t *du)
{
205 206
  nua_session_usage_t *ss = nua_dialog_usage_private(du);

207 208 209
  if (ds->ds_has_session)
    return -1;
  ds->ds_has_session = 1;
210

211
  nh->nh_ds->ds_cr->cr_next = ss->ss_crequest;
212
 
213 214 215
  return 0;
}

216 217
static
void nua_session_usage_remove(nua_handle_t *nh,
218 219 220
			       nua_dialog_state_t *ds,
			       nua_dialog_usage_t *du)
{
221 222
  nua_session_usage_t *ss = nua_dialog_usage_private(du);

223
  ds->ds_has_session = 0;
224 225 226 227

  if (ss->ss_crequest)
    nua_creq_deinit(ss->ss_crequest, NULL);

228
  ds->ds_cr->cr_next = NULL;
229 230 231 232 233 234 235 236 237 238 239 240 241
}

static
nua_session_usage_t *nua_session_usage_get(nua_dialog_state_t const *ds)
{
  nua_dialog_usage_t *du;

  if (ds == ((nua_handle_t *)NULL)->nh_ds)
    return NULL;

  du = nua_dialog_usage_get(ds, nua_session_usage, NULL);

  return (nua_session_usage_t *)nua_dialog_usage_private(du);
242 243 244 245 246
}

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

247 248
static int nua_stack_invite2(nua_t *, nua_handle_t *, nua_event_t e,
			     int restarted, tagi_t const *tags);
249 250 251
static int process_response_to_invite(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip);
252
static void
253 254 255 256
  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);

257
static int process_100rel(nua_handle_t *nh,
258
			  nua_session_usage_t *ss,
259 260 261 262 263 264
			  nta_outgoing_t *orq,
			  sip_t const *sip);

int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		    tagi_t const *tags);

265 266 267 268
static int process_response_to_prack(nua_handle_t *nh,
				     nta_outgoing_t *orq,
				     sip_t const *sip);

269
static void nua_session_usage_destroy(nua_handle_t *, nua_session_usage_t *);
270

271 272 273 274
static void session_timer_preferences(nua_session_usage_t *ss,
				      unsigned expires,
				      unsigned min_se,
				      enum nua_session_refresher refresher);
275 276 277 278 279
static int session_timer_is_supported(nua_handle_t const *nh);
static int prefer_session_timer(nua_handle_t const *nh);

static int use_session_timer(nua_session_usage_t *ss, int uas, int always,
			     msg_t *msg, sip_t *);
280
static int init_session_timer(nua_session_usage_t *ss, sip_t const *, int refresher);
281 282 283 284 285
static void set_session_timer(nua_session_usage_t *ss);

static int
check_session_timer_restart(nua_handle_t *nh,
			    nua_session_usage_t *ss,
286
			    nua_client_request_t *cr,
287 288 289
			    nta_outgoing_t *orq,
			    sip_t const *sip,
			    nua_creq_restart_f *restart_function);
290

291 292 293
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);
294

295
static void signal_call_state_change(nua_handle_t *nh,
296
				     nua_session_usage_t *ss,
297 298 299 300 301 302
				     int status, char const *phrase,
				     enum nua_callstate next_state,
				     char const *oa_recv,
				     char const *oa_sent);

static
303
int session_get_description(sip_t const *sip,
304
			    char const **return_sdp,
305 306 307
			    size_t *return_len);

static
308
int session_include_description(soa_session_t *soa,
309
				int session,
310
				msg_t *msg,
311 312 313
				sip_t *sip);

static
314 315
int session_make_description(su_home_t *home,
			     soa_session_t *soa,
316
			     int session,
317 318 319 320 321 322
			     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,
323
			     nua_client_request_t *cr,
324 325 326 327
			     nta_outgoing_t *orq,
			     sip_t const *sip,
			     char const **return_received);

328 329 330 331 332
static
int respond_with_retry_after(nua_handle_t *nh, nta_incoming_t *irq,
			     int status, char const *phrase,
			     int min, int max);

333
/**@fn void nua_invite(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
334 335 336 337 338 339 340
 *
 * Place a call using SIP INVITE method. 
 *
 * Incomplete call can be hung-up with nua_cancel(). Complete or incomplete
 * calls can be hung-up with nua_bye().
 *
 * Optionally 
341
 * - uses early media if NUTAG_EARLY_MEDIA() tag is used with non zero-value
342 343 344 345 346 347 348 349 350 351 352 353
 * - media parameters can be set by SOA tags
 * - nua_invite() can be used to change status of an existing call: 
 *   - #SOATAG_HOLD tag can be used to list the media that will be put on hold,
 *     the value "*" sets all the media beloginging to the session on hold
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return 
 *    nothing
 *
 * @par Related Tags:
354 355 356
 *    NUTAG_URL() \n
 *    Tags of nua_set_hparams() \n
 *    NUTAG_INCLUDE_EXTRA_SDP() \n
357 358 359
 *    SOATAG_HOLD(), SOATAG_AF(), SOATAG_ADDRESS(),
 *    SOATAG_RTP_SELECT(), SOATAG_RTP_SORT(), SOATAG_RTP_MISMATCH(), 
 *    SOATAG_AUDIO_AUX(), \n
360
 *    SOATAG_USER_SDP() or SOATAG_USER_SDP_STR() \n
361
 *    See use of tags in <sip_tag.h> below
362 363 364
 *
 * @par Events:
 *    #nua_r_invite \n
365
 *    #nua_i_state (#nua_i_active, #nua_i_terminated) \n
366 367 368 369 370 371 372 373
 *    #nua_i_media_error \n
 *    #nua_i_fork \n
 *
 * @par Populating SIP Request Message with Tagged Arguments
 * The tagged arguments can be used to pass values for any SIP headers to
 * the stack. When the INVITE message (or any other SIP message) is created,
 * the tagged values saved with nua_handle() are used first, next the tagged
 * values given with the operation (nua_invite()) are added.
374 375
 *
 * @par
376 377 378 379 380 381 382
 * When multiple tags for the same header are specified, the behaviour
 * depends on the header type. If only a single header field can be included
 * in a SIP message, the latest non-NULL value is used, e.g., @Subject. 
 * However, if the SIP header can consist of multiple lines or header fields
 * separated by comma, e.g., @Accept, all the tagged
 * values are concatenated.
 * 
383
 * @par
384 385 386
 * However, if a tag value is #SIP_NONE (-1 casted as a void pointer), the
 * values from previous tags are ignored.
 *
387
 * @par
388 389 390 391
 * Next, values previously set with nua_set_params() or nua_set_hparams()
 * are used: @Allow, @Supported, @Organization, and @UserAgent headers are
 * added to the request if they are not already set.
 *
392
 * @par
393 394
 * Now, the target URI for the request needs to be determined.
 *
395
 * @par
396 397 398 399 400 401 402 403 404 405
 * For initial INVITE requests, values from tags are used. If NUTAG_URL() is
 * given, it is used as target URI. Otherwise, if SIPTAG_TO() is given, it
 * is used as target URI. If neither is given, the complete request line
 * already specified using SIPTAG_REQUEST() or SIPTAG_REQUEST_STR() is used. 
 * If none of the tags above are given, an internal error is returned to the
 * application. At this point, the target URI is stored in the request line,
 * together with method name ("INVITE") and protocol version ("SIP/2.0"). 
 * The initial dialog information is also created: @CallID, @CSeq headers
 * are generated, if they do not exist, and tag is added to @From header.
 *
406
 * @par
407 408 409 410 411 412 413
 * For in-dialog INVITE (re-INVITE), the request URI is taken from the
 * @Contact header received from the remote party during the dialog
 * establishment. Also, the @CallID and @CSeq headers and @From and @To tags
 * are generated based on the dialog information and added to the request. 
 * If the dialog has a route (set by @RecordRoute headers), it is added to
 * the request, too.
 *
414
 * @par
415 416 417
 * @MaxForwards header (with default value set by NTATAG_MAX_FORWARDS()) is
 * also added now, if it does not exist.
 * 
418
 * @par
419 420 421 422 423 424 425 426
 * Next, the stack generates a @Contact header for the request (Unless the
 * application already gave a @Contact header or it does not want to use
 * @Contact and indicates that by including SIPTAG_CONTACT(NULL) or
 * SIPTAG_CONTACT(SIP_NONE) in the tagged parameters.) If the application
 * has registered the URI in @From header, the @Contact header used with
 * registration is used. Otherwise, the @Contact header is generated from the
 * local IP address and port number.
 *
427
 * @par
428 429 430
 * For the initial INVITE requests, @ServiceRoute set received from
 * the registrar is also added to the request message.
 *
431
 * @par
432 433
 * The INVITE request message created by nua_invite() operation is saved as
 * a template for automatic re-INVITE requests sent by the session timer
434 435 436 437 438
 * ("timer") feature (see NUTAG_SESSION_TIMER() for more details). Please
 * note that the template message is not used when ACK, PRACK, UPDATE or
 * INFO requests are created (however, these requests will include
 * dialog-specific headers like @To, @From, and @CallID as well as
 * preference headers @Allow, @Supported, @UserAgent, @Organization).
439 440 441 442 443 444 445
 *
 * @par SDP Handling
 * The initial nua_invite() creates a @ref soa_session_t "soa media session"
 * unless NUTAG_MEDIA_ENABLE(0) has been given. The SDP description of the
 * @ref soa_session_t "soa media session" is included in the INVITE request
 * as message body. 
 *
446
 * @par
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
 * The SDP in a 1XX or 2XX response message is interpreted as an answer,
 * given to the @ref soa_session_t "soa media session" object for
 * processing.
 *
 * @bug If the INVITE request already contains a message body, SDP is not
 * added. Also, if the response contains a multipart body, it is not parsed.
 *
 * @par Authentication
 * The INVITE request may need authentication. Each proxy or server
 * requiring authentication can respond with 401 or 407 response. The
 * nua_authenticate() operation stores authentication information (username
 * and password) to the handle, and stack tries to authenticate all the rest
 * of the requests (e.g., PRACK, ACK, UPDATE, re-INVITE, BYE) using same
 * username and password.
 *
462 463
 * @sa @ref nua_call_model, #nua_r_invite, #nua_i_state, \n
 *     nua_handle_has_active_call() \n
464 465 466 467 468 469 470 471
 *     nua_handle_has_call_on_hold()\n
 *     nua_handle_has_invite() \n
 *     nua_authenticate() \n
 *     nua_prack() \n
 *     nua_update() \n
 *     nua_info() \n 
 *     nua_cancel() \n
 *     nua_bye() \n
472
 *     #nua_i_invite, nua_respond()
473 474
 */

475 476 477
/* Tags not implemented
 *    NUTAG_REFER_PAUSE() \n
 */
478 479 480
int
nua_stack_invite(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		 tagi_t const *tags)
481 482 483
{
  char const *what;

484 485
  if (nh_is_special(nh) || 
      nua_stack_set_handle_special(nh, nh_has_invite, nua_i_error))
486
    what = "Invalid handle for INVITE";
487
  else if (nh_referral_check(nh, tags) < 0) {
488 489
    what = "Invalid referral";
  }
490
  else if (nua_stack_init_handle(nua, nh, TAG_NEXT(tags)) < 0) {
491 492 493
    what = "Handle initialization failed";
  }
  else
494
    return nua_stack_invite2(nua, nh, e, 0, tags);
495

496
  UA_EVENT2(e, 900, what);
497

498
  signal_call_state_change(nh, NULL, 900, what, nua_callstate_init, 0, 0);
499 500 501 502 503

  return e;
}

static int
504 505 506
nua_stack_invite2(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		  int restarted,
		  tagi_t const *tags)
507 508
{
  nua_dialog_usage_t *du;
509
  nua_session_usage_t *ss;
510
  nua_client_request_t *cr;
511 512 513
  int offer_sent = 0;

  msg_t *msg = NULL;
514
  sip_t *sip = NULL;
515 516 517 518

  char const *what;

  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
519 520
  ss = nua_dialog_usage_private(du);
  cr = ss->ss_crequest;
521
  what = nua_internal_error;		/* Internal error */
522

523 524
  if (du == NULL)
    goto failure;
525

526 527 528
  if (cr->cr_orq) {
    what = "INVITE request already in progress";
    goto failure;
529 530
  }

531 532 533
  if (ss->ss_state == nua_callstate_terminated)
    ss->ss_state = nua_callstate_init;

534 535 536 537 538 539 540 541 542 543 544 545 546
  if (!restarted) {
    session_timer_preferences(ss, 
			      NH_PGET(nh, session_timer),
			      NH_PGET(nh, min_se),
			      NH_PGET(nh, refresher));
  }

  if (restarted && !cr->cr_msg) {
    if (du->du_msg)
      cr->cr_msg = msg_dup(du->du_msg);
    else
      restarted = 0;
  }
547 548 549 550 551 552

  msg = nua_creq_msg(nua, nh, cr, restarted,
		     SIP_METHOD_INVITE,
		     NUTAG_USE_DIALOG(1),
		     NUTAG_ADD_CONTACT(1),
		     TAG_NEXT(tags));
553 554
  sip = sip_object(msg);

555 556
  if (!sip) {
    what = "Cannot Initialize Request";
557
    goto failure;
558
  }
559 560 561 562 563 564

  if (!restarted) {
    msg_destroy(du->du_msg), du->du_msg = msg_dup(msg);
  }

  if (nh->nh_soa) {
565 566 567 568 569 570 571 572 573 574
    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;
  }

575
  if (offer_sent >= 0) {
576
    sip_time_t invite_timeout = NH_PGET(nh, invite_timeout);
577
    if (invite_timeout == 0)
578
      invite_timeout = UINT_MAX;
579 580 581
    /* Cancel if we don't get response within timeout*/
    nua_dialog_usage_set_expires(du, invite_timeout);
    nua_dialog_usage_set_refresh(du, 0);
582 583

    /* Add session timer headers */
584 585
    if (session_timer_is_supported(nh))
      use_session_timer(ss, 0, prefer_session_timer(nh), msg, sip);
586 587 588 589 590 591 592 593

    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 &&
594
	session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
595 596
      what = "Internal media error"; goto failure;
    }
597

598
    if (nh->nh_soa &&
599
	NH_PGET(nh, media_features) && !nua_dialog_is_established(nh->nh_ds) &&
600 601 602 603 604 605
	!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));
606

607 608 609 610 611 612
      if (ac->cp_params) {
	msg_header_replace_param(msg_home(msg), ac->cp_common, "explicit");
	sip_add_dup(msg, sip, (sip_header_t *)ac);
      }
    }

613 614 615 616
    if (nh->nh_auth) {
      if (auc_authorize(&nh->nh_auth, msg, sip) < 0) {
	what = "Internal authentication error"; goto failure;
      }
617
    }
618

619 620 621 622 623 624 625 626 627
      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;
628
      du->du_refresh = 0;
629
      signal_call_state_change(nh, ss, 0, "INVITE sent",
630 631 632 633 634 635
			       nua_callstate_calling, 0,
			       offer_sent ? "offer" : 0);
      return cr->cr_event = e;
    }
  }

636 637
 failure:

638
  msg_destroy(msg);
639
  if (du && !du->du_ready)
640
    nua_dialog_usage_remove(nh, nh->nh_ds, du), ss = NULL;
641

642
  UA_EVENT2(e, 900, what);
643
  signal_call_state_change(nh, ss, 900, what, nua_callstate_init, 0, 0);
644 645 646 647

  return e;
}

648
/** @NUA_EVENT nua_r_invite
649 650 651 652 653 654
 *
 * Answer to outgoing INVITE.
 *
 * The INVITE may be sent explicitly by nua_invite() or
 * implicitly by NUA state machine.
 *
655 656 657 658 659
 * @param status response status code
 *               (if the request is retried, @a status is 100, the @a
 *               sip->sip_status->st_status contain the real status code
 *               from the response message, e.g., 302, 401, or 407)
 * @param phrase a short textual description of @a status code
660
 * @param nh     operation handle associated with the call
661 662 663 664
 * @param hmagic application context associated with the call
 * @param sip    response message to INVITE or NULL upon an error
 *               (status code is in @a status and 
 *                descriptive message in @a phrase parameters)
665
 * @param tags   empty
666 667 668 669 670
 *
 * @sa nua_invite(), @ref nua_call_model, #nua_i_state, #nua_i_invite, 
 * nua_ack(), NUTAG_AUTOACK()
 * 
 * @END_NUA_EVENT
671 672
 */

673 674 675 676 677
static int process_response_to_invite(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip)
{
  nua_t *nua = nh->nh_nua;
678 679 680
  nua_client_request_t *cr;
  nua_dialog_usage_t *du;
  nua_session_usage_t *ss;
681 682 683 684 685 686
  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;

687
  cr = nua_client_request_by_orq(nh->nh_ds->ds_cr, orq);
688 689 690 691
  du = cr ? cr->cr_usage : NULL;
  ss = nua_dialog_usage_private(du);
  
  assert(cr && du && ss);
692

693 694 695 696 697 698 699 700
  if (ss->ss_state == nua_callstate_terminating && 200 <= status) {
    /*
     * If the call is being terminated but re-INVITE was responded with 2XX
     * re-send the BYE, otherwise terminate the call.
     */
    gracefully = status < 300, terminated = !gracefully;
  }
  else if (status >= 300) {
701 702 703
    if (sip->sip_retry_after)
      gracefully = 0;

704
    terminated = sip_response_terminates_dialog(status, sip_method_invite,
705 706 707
						&gracefully);

    if (!terminated) {
708
      if (check_session_timer_restart(nh, ss, cr, orq, sip, restart_invite))
709 710
	return 0;

711
      if (ss->ss_state < nua_callstate_ready)
712 713 714 715 716 717
	terminated = 1;
    }
  }
  else if (status >= 200) {
    du->du_ready = 1;
    cr->cr_usage = NULL;
718

719 720
    /* XXX - check remote tag, handle forks */
    /* Set route, contact, nh_ds->ds_remote_tag */
721
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
722
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
723

724 725
    init_session_timer(ss, sip, NH_PGET(nh, refresher));
    set_session_timer(ss);
726 727 728 729 730

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

731
      if (NH_PGET(nh, auto_ack) ||
732
	  /* Auto-ACK response to re-INVITE unless auto_ack is set to 0 */
733
	  (ss->ss_state == nua_callstate_ready &&
734 735 736
	   !NH_PISSET(nh, auto_ack)))
	nua_stack_ack(nua, nh, nua_r_ack, NULL);
      else
737
	signal_call_state_change(nh, ss, status, phrase,
738 739 740 741 742
				 nua_callstate_completing, received, 0);
      nh_referral_respond(nh, SIP_200_OK);
      return 0;
    }

743
    status = 500, phrase = "Malformed Session in Response";
744 745 746 747 748 749 750 751

    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);

752
    return process_100rel(nh, ss, orq, sip); /* signal_call_state_change */
753 754 755 756 757
  }
  else {
    /* Provisional response */
    nh_referral_respond(nh, status, phrase);
    session_process_response(nh, cr, orq, sip, &received);
758
    signal_call_state_change(nh, ss, status, phrase,
759 760 761 762 763 764 765 766 767 768
			     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)
769
    signal_call_state_change(nh, ss, status, phrase,
770 771 772 773 774 775 776 777 778
			     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) {
779
    char *reason =
780 781
      su_sprintf(NULL, "SIP;cause=%u;text=\"%s\"", 
		 status > 699 ? 500 : status, phrase);
782

783
    signal_call_state_change(nh, ss, status, phrase,
784 785
			     nua_callstate_terminating, 0, 0);

786 787 788
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
789 790 791 792 793 794 795

    su_free(NULL, reason);
  }

  return 0;
}

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
/**@fn void nua_ack(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
 *
 * Acknowledge a succesful response to INVITE request.
 *
 * Acknowledge a successful response (200..299) to INVITE request with the
 * SIP ACK request message. This function is need only if NUTAG_AUTOACK()
 * parameter has been cleared.
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return 
 *    nothing
 *
 * @par Related Tags:
 *    Tags in <sip_tag.h>
 *
 * @par Events:
 *    #nua_i_media_error \n
815
 *    #nua_i_state  (#nua_i_active, #nua_i_terminated) 
816 817
 *
 * @sa NUTAG_AUTOACK(), @ref nua_call_model, #nua_i_state
818 819
 */

820 821
int nua_stack_ack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		  tagi_t const *tags)
822
{
823 824
  nua_session_usage_t *ss;
  nua_client_request_t *cr;
825 826 827 828 829
  nta_outgoing_t *ack = NULL;
  msg_t *msg;
  sip_t *sip;
  int status = 200;
  char const *phrase = "OK", *reason = NULL, *sent = NULL;
830 831 832 833
  char const *received;

  ss = nua_session_usage_get(nh->nh_ds);
  cr = ss->ss_crequest;
834

835 836 837
  received = ss ? ss->ss_ack_needed : NULL;

  if (!received)
838
    return UA_EVENT2(nua_i_error, 900, "No response to ACK");
839 840 841 842 843 844

  ss->ss_ack_needed = 0;

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

845
  if (tags)
846
    nua_stack_set_params(nua, nh, nua_i_error, tags);
847

848
  msg = nua_creq_msg(nua, nh, cr, 0,
849 850 851
		     SIP_METHOD_ACK,
		     /* NUTAG_COPY(0), */
		     TAG_NEXT(tags));
852 853 854 855 856 857 858 859
  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 ||
860
	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
861
	reason = soa_error_as_sip_reason(nh->nh_soa);
862
	status = 900, phrase = "Internal media error";
863 864 865 866 867 868 869 870 871 872 873
	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";
      }
    }

874
    if (!reason &&
875 876 877
	/* ss->ss_offer_sent && !ss->ss_answer_recv */
	!soa_is_complete(nh->nh_soa)) {
      /* No SDP answer in 2XX response -> terminate call */
878 879
      status = 988, phrase = "Incomplete offer/answer";
      reason = "SIP;cause=488;text=\"Incomplete offer/answer\"";
880 881 882
    }
  }

883 884 885 886 887 888 889 890 891 892
  if (sip) {
    msg_t *imsg = nta_outgoing_getrequest(cr->cr_orq);
    sip_t const *isip = sip_object(imsg);
    if (isip->sip_proxy_authorization)
      sip_add_dup(msg, sip, (void *)isip->sip_proxy_authorization);
    if (isip->sip_authorization)
      sip_add_dup(msg, sip, (void *)isip->sip_authorization);
    msg_destroy(imsg);
  }

893
  if (sip)
894
    ack = nta_outgoing_mcreate(nua->nua_nta, NULL, NULL, NULL, msg,
895 896 897 898
			       SIPTAG_END(), TAG_NEXT(tags));

  if (!ack) {
    if (!reason) {
899
      status = 900, phrase = "Cannot send ACK";
900 901 902 903 904 905 906 907 908
      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) {
909
    signal_call_state_change(nh, ss, status, phrase, nua_callstate_ready,
910 911 912
			     received, sent);
  }
  else {
913
    signal_call_state_change(nh, ss, status, phrase, nua_callstate_terminating,
914 915 916 917
			     0, 0);
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
918 919 920 921 922
  }

  return 0;
}

923

924
/* Process reliable provisional response */
925
static int
926
process_100rel(nua_handle_t *nh,
927
	       nua_session_usage_t *ss,
928 929 930
	       nta_outgoing_t *orq,
	       sip_t const *sip)
{
931 932
  nua_client_request_t *cr_invite = ss->ss_crequest;
  nua_client_request_t *cr_prack = nh->nh_ds->ds_cr;
933 934 935 936
  
  sip_rseq_t *rseq;
  char const *recv = NULL;
  int status; char const *phrase;
937 938

  if (cr_prack->cr_orq) {
939
    /* XXX - better luck next time */
940
    SU_DEBUG_3(("nua(%p): cannot send PRACK because %s is pending\n", nh,
941
		nta_outgoing_method_name(cr_prack->cr_orq)));
942
    return 0; /* Wait until this response is re-transmitted */
943 944 945
  }

  if (!nua_dialog_is_established(nh->nh_ds)) {
946
    /* Establish early dialog */
947 948
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
949 950
    
    /* Tag the INVITE request */
951
    cr_invite->cr_orq =
952 953 954 955 956
      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;
  }
957 958 959 960 961
  
  assert(sip);

  status = sip->sip_status->st_status, phrase = sip->sip_status->st_phrase;
  rseq = sip->sip_rseq;
962

963 964
  if (!rseq) {
    SU_DEBUG_5(("nua(%p): 100rel missing RSeq\n", nh));
965
  }
966 967 968 969 970 971
  else if (rseq->rs_response <= nta_outgoing_rseq(orq)) {
    SU_DEBUG_5(("nua(%p): 100rel bad RSeq %u (got %u)\n", nh, 
		(unsigned)rseq->rs_response,
		nta_outgoing_rseq(orq)));
    /* XXX - send nua_r_invite event or not? */
    return 0;
972
  }
973 974 975
  else if (nta_outgoing_setrseq(orq, rseq->rs_response) < 0) {
    SU_DEBUG_1(("nua(%p): cannot set RSeq %u\n", nh, 
		(unsigned)rseq->rs_response));
976
  }
977 978 979 980 981
  else if (session_process_response(nh, cr_invite, orq, sip, &recv) < 0) {
    assert(nh->nh_soa);
    status = soa_error_as_sip_response(nh->nh_soa, &phrase);
    nua_stack_event(nh->nh_nua, nh, NULL,
		    nua_i_media_error, status, phrase, TAG_END());
982
  }
983
  /* Here we could let application PRACK and just send state event */
984
  else {
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    sip_rack_t rack[1];
    tagi_t tags[] = {
      { TAG_SKIP(nua_stack_prack) }, /* this is autoprack */
      { NUTAG_STATUS(status), },
      { NUTAG_PHRASE(phrase), },
      { NUTAG_PHRASE(recv), },
      { SIPTAG_RACK(rack) }, 
      { TAG_END() }
    };

    sip_rack_init(rack);

    rack->ra_response    = sip->sip_rseq->rs_response;
    rack->ra_cseq        = sip->sip_cseq->cs_seq;
    rack->ra_method      = sip->sip_cseq->cs_method;
    rack->ra_method_name = sip->sip_cseq->cs_method_name;

    nua_stack_prack(nh->nh_nua, nh, nua_r_prack, tags);

    return 0;
1005 1006
  }

1007 1008 1009
  /* XXX - CANCEL INVITE or BYE this session? */
  /* Because we don't do forking very well we just cancel INVITE */
  nua_stack_cancel(nh->nh_nua, nh, nua_r_cancel, NULL);
1010 1011 1012 1013

  return 0;
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
/**@fn void nua_prack(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
 * Send a PRACK request. 
 *
 * PRACK is used to acknowledge receipt of 100rel responses. See @RFC3262.
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return 
 *    nothing
 *
 * @par Related Tags:
 *    Tags in <sofia-sip/soa_tag.h>, <sofia-sip/sip_tag.h>.
 *
 * @par Events:
 *    #nua_r_prack
 */

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
/** @NUA_EVENT nua_r_prack
 *
 * Response to an outgoing @b PRACK request. PRACK request is used to
 * acknowledge reliable preliminary responses and it is usually sent
 * automatically by the nua stack.
 *
 * @param status response status code
 *               (if the request is retried, @a status is 100, the @a
 *               sip->sip_status->st_status contain the real status code
 *               from the response message, e.g., 302, 401, or 407)
 * @param phrase a short textual description of @a status code
 * @param nh     operation handle associated with the call
 * @param hmagic application context associated with the call
 * @param sip    response to @b PRACK or NULL upon an error
 *               (status code is in @a status and 
 *                descriptive message in @a phrase parameters)
 * @param tags   empty
 *
 * @sa nua_prack(), #nua_i_prack, @RFC3262
 *
 * @END_NUA_EVENT
 */


1056 1057 1058
int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		    tagi_t const *tags)
{
1059 1060
  nua_session_usage_t *ss;
  nua_client_request_t *cr;
1061 1062 1063 1064
  msg_t *msg;
  sip_t *sip;
  int offer_sent_in_prack = 0, answer_sent_in_prack = 0;

1065 1066 1067
  int status = 0; char const *phrase = "PRACK sent";
  char const *recv = NULL, *sent = NULL;

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
  int autoprack =		/* XXX - should have common indication */
    tags && tags->t_tag == tag_skip && 
    tags->t_value == (tag_value_t)nua_stack_prack;

  if (autoprack) {
    status = (int)tags[1].t_value; 
    phrase = (char const *)tags[2].t_value;
    recv = (char const *)tags[3].t_value;
    tags += 4;
  }

1079 1080 1081
  ss = nua_session_usage_get(nh->nh_ds);

  if (!ss || !ss->ss_crequest || !nta_outgoing_rseq(ss->ss_crequest->cr_orq))
1082
    return UA_EVENT2(e, 900, "Nothing to PRACK");
1083
  else if (nh->nh_ds->ds_cr->cr_orq)
1084 1085
    return UA_EVENT2(e, 900, "Request already in progress");

1086
  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
1087

1088
  cr = nh->nh_ds->ds_cr;
1089

1090 1091 1092 1093 1094 1095 1096 1097 1098
  msg = nua_creq_msg(nua, nh, cr, cr->cr_retry_count,
		     SIP_METHOD_PRACK,
		     NUTAG_USE_DIALOG(1),
		     NUTAG_ADD_CONTACT(1),
		     TAG_NEXT(tags));

  sip = sip_object(msg);

  if (sip) {
1099
    nua_client_request_t *cri = ss->ss_crequest;
1100 1101 1102 1103 1104 1105 1106
    if (nh->nh_soa == NULL)
      /* It is up to application to handle SDP */;
    else if (sip->sip_payload)
      /* XXX - we should just do MIME in session_include_description() */;
    else if (cri->cr_offer_recv && !cri->cr_answer_sent) {

      if (soa_generate_answer(nh->nh_soa, NULL) < 0 ||
1107
	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
	SU_DEBUG_3(("nua(%p): PRACK answer: %d %s\n", nh, status, phrase));
	nua_stack_event(nh->nh_nua, nh, NULL,
			nua_i_media_error, status, phrase, TAG_END());

	goto error;
      }
      else {
	answer_sent_in_prack = 1, sent = "answer";
	soa_activate(nh->nh_soa, NULL);
      }
    }
    /* When 100rel response status was 183 fake support for preconditions */
    else if (autoprack && status == 183 && ss->ss_precondition) {

      if (soa_generate_offer(nh->nh_soa, 0, NULL) < 0 ||
1125
	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

	status = soa_error_as_sip_response(nh->nh_soa, &phrase);
	SU_DEBUG_3(("nua(%p): PRACK offer: %d %s\n", nh, status, phrase));
	nua_stack_event(nh->nh_nua, nh, NULL,
			nua_i_media_error, status, phrase, TAG_END());
	goto error;
      }
      else {
	offer_sent_in_prack = 1, sent = "offer";
      }
    }

    if (nh->nh_auth) {
      if (auc_authorize(&nh->nh_auth, msg, sip) < 0)
	/* xyzzy */;
    }

    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				      process_response_to_prack, nh, NULL,
				      msg,
				      SIPTAG_END(), TAG_NEXT(tags));
    if (cr->cr_orq) {
1148
      cr->cr_usage = nua_dialog_usage_public(ss);
1149 1150 1151 1152 1153 1154 1155 1156
      cr->cr_event = nua_r_prack;

      if (answer_sent_in_prack)
	cri->cr_answer_sent = 1;
      else if (offer_sent_in_prack)
	cr->cr_offer_sent = 1;

      if (autoprack) 
1157
	signal_call_state_change(nh, ss, status, phrase,
1158 1159
				 nua_callstate_proceeding, recv, sent);
      else
1160
	signal_call_state_change(nh, ss, 0, "PRACK sent",
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
				 nua_callstate_proceeding, NULL, sent);
	

      return cr->cr_event = e;
    }
  }

 error:
  msg_destroy(msg);
  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
}

void restart_prack(nua_handle_t *nh, tagi_t *tags)
{
1175
  nua_creq_restart(nh, nh->nh_ds->ds_cr, process_response_to_prack, tags);
1176 1177 1178
}


1179
static int
1180 1181 1182 1183
process_response_to_prack(nua_handle_t *nh,
			  nta_outgoing_t *orq,
			  sip_t const *sip)
{
1184
  nua_client_request_t *cr = nh->nh_ds->ds_cr;
1185
  nua_session_usage_t *ss = nua_dialog_usage_private(cr->cr_usage);
1186 1187 1188
  int status;
  char const *phrase = "OK", *reason = NULL, *recv = NULL;

1189 1190
  assert(cr->cr_usage && cr->cr_usage->du_class == nua_session_usage);

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  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 (nua_creq_check_restart(nh, cr, orq, sip, restart_prack))
    return 0;

  if (status < 200)
    return 0;
1203

1204 1205
  cr->cr_usage = NULL;

1206 1207
  if (status < 300) {
    if (session_process_response(nh, cr, orq, sip, &recv) < 0) {
1208
      status = 900, phrase = "Malformed Session in Response";
1209 1210 1211 1212 1213 1214
      reason = "SIP;status=400;phrase=\"Malformed Session in Response\"";
    }
  }
  else
    nua_stack_process_response(nh, cr, orq, sip, TAG_END());

1215
  if (recv)
1216
    signal_call_state_change(nh, ss, status, phrase,
1217
			     nua_callstate_proceeding, recv, NULL);
1218

1219
  if (status < 300 && ss->ss_update_needed)
1220 1221 1222 1223 1224
    nua_stack_update(nh->nh_nua, nh, nua_r_update, NULL);

  return 0;
}

1225 1226
/** Refresh session usage */
static void nua_session_usage_refresh(nua_handle_t *nh,
1227
				      nua_dialog_state_t *ds,
1228 1229
				      nua_dialog_usage_t *du,
				      sip_time_t now)
1230
{
1231 1232 1233
  tagi_t const timer_tags[2] = {
    { SIPTAG_SUBJECT_STR("Session refresh") }, 
    { TAG_END() }
1234
  };
1235 1236 1237 1238
  tagi_t const refresh_tags[2] = {
    { SIPTAG_SUBJECT_STR("Dialog refresh") }, 
    { TAG_END() }
  };
1239 1240

  nua_session_usage_t const *ss = nua_dialog_usage_private(du);
1241
  nua_client_request_t const *cri = ss->ss_crequest, *cro = ds->ds_cr;
1242
  nua_server_request_t const *sr;
1243

1244
  for (sr = ds->ds_sr; sr; sr = sr->sr_next)
1245
    if (sr->sr_usage == du && 
1246 1247
	(sr->sr_method == sip_method_invite || 
	 sr->sr_method == sip_method_update))
1248 1249 1250 1251
      break;

  /* INVITE or UPDATE in progress or being authenticated */
  if ((cri && cri->cr_orq) || sr)	
1252
    return;
1253
  if (ss->ss_state >= nua_callstate_terminating)
1254
    return;
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
  if (!ss->ss_refresher) {
    if (now >= du->du_expires)
      session_timeout(nh, du, now);
    else
      /* Refreshing contact & route set */
      nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, refresh_tags);
  }
  else if (NH_PGET(nh, update_refresh)) {
    if (!cro->cr_orq)
      nua_stack_update(nh->nh_nua, nh, nua_r_update, timer_tags);
    else
      nua_dialog_usage_refresh_range(du, 5, 15);
  }
  else {
1270
    nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, timer_tags);
1271
  }
1272 1273
}

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

1277
static void
1278 1279 1280
session_timeout(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
{
  if (now > 1) {
1281 1282 1283
    nua_session_usage_t *ss = nua_dialog_usage_private(du);

    signal_call_state_change(nh, ss, 408, "Session Timeout",
1284
			     nua_callstate_terminating, NULL, NULL);
1285

1286 1287 1288
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason_timeout),
			  TAG_END());
1289 1290 1291
  }
}

1292 1293
/** Terminate usage/dialog/handle/agent gracefully */
static int nua_session_usage_shutdown(nua_handle_t *nh,
1294
				      nua_dialog_state_t *ds,
1295
				      nua_dialog_usage_t *du)
1296
{
1297
  nua_session_usage_t *ss = nua_dialog_usage_private(du);
1298
  nua_client_request_t *cr;
1299
  nua_server_request_t *sr, *sr_next;
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
  int status;

  /* Zap client-side invite transaction */
  if (ss->ss_crequest->cr_orq) {
    cr = ss->ss_crequest;
    status = nta_outgoing_status(cr->cr_orq);

    if (status < 200) 
      nta_outgoing_tcancel(cr->cr_orq, NULL, NULL, TAG_END());

    if (ss->ss_ack_needed) {
      msg_t *ack = nua_creq_msg(nh->nh_nua, nh, cr, 0,
				SIP_METHOD_ACK,
				TAG_END());
      nta_outgoing_mcreate(nh->nh_nua->nua_nta, NULL, NULL, NULL, 
			   ack, TAG_END());
    }

    nua_creq_deinit(cr, NULL);
  }

1321 1322
  /* Zap server-side transactions */
  for (sr = ds->ds_sr; sr; sr = sr_next) {
1323 1324 1325 1326 1327 1328 1329 1330 1331
    sr_next = sr->sr_next;
    if (sr->sr_usage == du) {
      assert(sr->sr_usage == du);
      sr->sr_usage = NULL;
      if (sr->sr_respond) 
	nua_server_respond(sr, SIP_480_TEMPORARILY_UNAVAILABLE, TAG_END());
      else
	nua_server_request_destroy(sr);
    }
1332 1333
  }

1334 1335
  assert(ss == nua_session_usage_get(nh->nh_ds));

1336 1337 1338 1339 1340 1341 1342
  switch (ss->ss_state) {
  case nua_callstate_completing:
  case nua_callstate_ready:
  case nua_callstate_completed:
    {
      msg_t *bye;

1343
      cr = ds->ds_cr;
1344
      nua_creq_deinit(cr, NULL);
1345
      bye = nua_creq_msg(nh->nh_nua, nh, ds->ds_cr, 0, 
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
			 SIP_METHOD_BYE,
			 TAG_END());
      cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta,
					NULL, NULL, NULL,
					bye,
					TAG_END());
      if (cr->cr_orq)		/* Wait for BYE to complete? */
	nua_creq_deinit(cr, NULL);
    }
  }

1357
  nua_dialog_usage_remove(nh, ds, du);
1358 1359 1360 1361

  return 0;
}

1362
/** Restart invite (e.g., after 302 or 407) */
1363
void
1364 1365
restart_invite(nua_handle_t *nh, tagi_t *tags)
{
1366
  nua_stack_invite2(nh->nh_nua, nh, nua_r_invite, 1, tags);
1367 1368 1369 1370 1371 1372
}

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

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
/**@fn void nua_cancel(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
 *
 * Cancel an INVITE operation 
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return 
 *    nothing
 *
 * @par Related Tags:
 *    Tags in <sip_tag.h>
 *
 * @par Events:
1387
 *    #nua_r_cancel, #nua_i_state  (#nua_i_active, #nua_i_terminated)
1388 1389 1390 1391
 *
 * @sa @ref nua_call_model, nua_invite(), #nua_i_cancel
 */

1392
int
1393 1394
nua_stack_cancel(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		 tagi_t const *tags)
1395
{
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
  nua_session_usage_t *ss;
  nua_client_request_t *cri, *crc;

  ss = nua_session_usage_get(nh->nh_ds);

  if (!nh || !ss || !ss->ss_crequest->cr_usage ||
      nta_outgoing_status(ss->ss_crequest->cr_orq) >= 200) {
    return UA_EVENT2(e, 481, "No transaction to CANCEL");
  }

  cri = ss->ss_crequest;
1407
  crc = nh->nh_ds->ds_cr;
1408

1409
  if (tags)
1410
    nua_stack_set_params(nua, nh, nua_i_error, tags);
1411

1412
  if (nh && cri->cr_orq && cri->cr_usage) {
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
    nta_outgoing_t *orq;

    /* 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)
1424 1425
      return nua_stack_event(nua, nh, NULL, e, 400, "Internal error",
			     TAG_END());
1426 1427 1428 1429 1430

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

1431
  return 0;
1432 1433
}

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
/** @NUA_EVENT nua_r_cancel
 *
 * Answer to outgoing CANCEL.
 *
 * The CANCEL may be sent explicitly by nua_cancel() or implicitly by NUA
 * state machine.
 *
 * @param status response status code 
 * @param phrase a short textual description of @a status code
 * @param nh     operation handle associated with the call
 * @param hmagic application context associated with the call
 * @param sip    response to CANCEL request or NULL upon an error
 *               (status code is in @a status and 
 *                descriptive message in @a phrase parameters)
 * @param tags   empty
 *
 * @sa nua_cancel(), @ref nua_uac_call_model, #nua_r_invite, nua_invite(),
 * #nua_i_state
 *
 * @END_NUA_EVENT
 */



1458 1459 1460 1461
static int process_response_to_cancel(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip)
{
1462
  return nua_stack_process_response(nh, nh->nh_ds->ds_cr, orq, sip, TAG_END());
1463 1464
}

1465 1466 1467
/* ---------------------------------------------------------------------- */
/* UAS side of INVITE */

1468
static int respond_to_invite(nua_server_request_t *sr, tagi_t const *tags);
1469

1470
static int
1471
  preprocess_invite(nua_t *, nua_handle_t *, nua_server_request_t **, sip_t *),
1472 1473 1474 1475
  session_check_request(nua_t *nua,
			nua_handle_t *nh,
			nta_incoming_t *irq,
			sip_t const *sip),
1476
  process_invite(nua_t *, nua_handle_t *, nua_server_request_t *, sip_t *),
1477
  process_prack(nua_handle_t *, nta_reliable_t *, nta_incoming_t *,
1478 1479 1480 1481 1482 1483 1484 1485
		sip_t const *);

static int
  process_ack_or_cancel(nua_server_request_t *, nta_incoming_t *, 
			sip_t const *),
  process_ack(nua_server_request_t *, nta_incoming_t *, sip_t const *),
  process_cancel(nua_server_request_t *, nta_incoming_t *, sip_t const *),
  process_timeout(nua_server_request_t *, nta_incoming_t *);
1486

1487
/** @NUA_EVENT nua_i_invite
1488
 *
1489
 * Indication of incoming call or re-INVITE request. 
1490
 *
1491 1492
 * @param status statuscode of response sent automatically by stack
 * @param phrase a short textual description of @a status code
1493 1494
 * @param nh     operation handle associated with this call
 *               (maybe created for this call)
1495
 * @param hmagic application context associated with this call
1496 1497 <