nua_session.c 104 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 275 276 277 278 279 280 281
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 *);
static int  init_session_timer(nua_session_usage_t *ss, sip_t const *, int refresher);
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,
282
			    nua_client_request_t *cr,
283 284 285
			    nta_outgoing_t *orq,
			    sip_t const *sip,
			    nua_creq_restart_f *restart_function);
286

287 288 289
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);
290

291
static void signal_call_state_change(nua_handle_t *nh,
292
				     nua_session_usage_t *ss,
293 294 295 296 297 298
				     int status, char const *phrase,
				     enum nua_callstate next_state,
				     char const *oa_recv,
				     char const *oa_sent);

static
299
int session_get_description(sip_t const *sip,
300
			    char const **return_sdp,
301 302 303
			    size_t *return_len);

static
304
int session_include_description(soa_session_t *soa,
305
				int session,
306
				msg_t *msg,
307 308 309
				sip_t *sip);

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

324 325 326 327 328
static
int respond_with_retry_after(nua_handle_t *nh, nta_incoming_t *irq,
			     int status, char const *phrase,
			     int min, int max);

329
/**@fn void nua_invite(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
330 331 332 333 334 335 336
 *
 * 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 
337
 * - uses early media if NUTAG_EARLY_MEDIA() tag is used with non zero-value
338 339 340 341 342 343 344 345 346 347 348 349
 * - 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:
350 351 352
 *    NUTAG_URL() \n
 *    Tags of nua_set_hparams() \n
 *    NUTAG_INCLUDE_EXTRA_SDP() \n
353 354 355
 *    SOATAG_HOLD(), SOATAG_AF(), SOATAG_ADDRESS(),
 *    SOATAG_RTP_SELECT(), SOATAG_RTP_SORT(), SOATAG_RTP_MISMATCH(), 
 *    SOATAG_AUDIO_AUX(), \n
356
 *    SOATAG_USER_SDP() or SOATAG_USER_SDP_STR() \n
357
 *    See use of tags in <sip_tag.h> below
358 359 360
 *
 * @par Events:
 *    #nua_r_invite \n
361
 *    #nua_i_state (#nua_i_active, #nua_i_terminated) \n
362 363 364 365 366 367 368 369
 *    #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.
370 371
 *
 * @par
372 373 374 375 376 377 378
 * 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.
 * 
379
 * @par
380 381 382
 * However, if a tag value is #SIP_NONE (-1 casted as a void pointer), the
 * values from previous tags are ignored.
 *
383
 * @par
384 385 386 387
 * 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.
 *
388
 * @par
389 390
 * Now, the target URI for the request needs to be determined.
 *
391
 * @par
392 393 394 395 396 397 398 399 400 401
 * 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.
 *
402
 * @par
403 404 405 406 407 408 409
 * 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.
 *
410
 * @par
411 412 413
 * @MaxForwards header (with default value set by NTATAG_MAX_FORWARDS()) is
 * also added now, if it does not exist.
 * 
414
 * @par
415 416 417 418 419 420 421 422
 * 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.
 *
423
 * @par
424 425 426
 * For the initial INVITE requests, @ServiceRoute set received from
 * the registrar is also added to the request message.
 *
427
 * @par
428 429 430 431 432 433 434 435 436 437 438 439 440
 * The INVITE request message created by nua_invite() operation is saved as
 * a template for automatic re-INVITE requests sent by the session timer
 * ("timer") feature. 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).
 *
 * @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. 
 *
441
 * @par
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
 * 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.
 *
 * \sa @ref nua_call_model \n
 *     nua_nua_handle_has_active_call() \n
 *     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
 *     nua_respond()
 */

470 471 472
/* Tags not implemented
 *    NUTAG_REFER_PAUSE() \n
 */
473 474 475
int
nua_stack_invite(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		 tagi_t const *tags)
476 477 478
{
  char const *what;

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

491
  UA_EVENT2(e, 900, what);
492

493
  signal_call_state_change(nh, NULL, 900, what, nua_callstate_init, 0, 0);
494 495 496 497 498

  return e;
}

static int
499 500 501
nua_stack_invite2(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		  int restarted,
		  tagi_t const *tags)
502 503
{
  nua_dialog_usage_t *du;
504
  nua_session_usage_t *ss;
505
  nua_client_request_t *cr;
506 507 508
  int offer_sent = 0;

  msg_t *msg = NULL;
509
  sip_t *sip = NULL;
510 511 512 513

  char const *what;

  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_session_usage, NULL);
514 515
  ss = nua_dialog_usage_private(du);
  cr = ss->ss_crequest;
516
  what = nua_internal_error;		/* Internal error */
517

518 519
  if (du == NULL)
    goto failure;
520

521 522 523
  if (cr->cr_orq) {
    what = "INVITE request already in progress";
    goto failure;
524 525
  }

526 527 528 529 530 531 532 533 534 535 536
  if (ss->ss_state == nua_callstate_terminated)
    ss->ss_state = nua_callstate_init;

  if (restarted && !cr->cr_msg)
    cr->cr_msg = msg_dup(du->du_msg);

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

539 540 541 542 543 544 545 546 547 548 549
  if (!sip)
    goto failure;

  if (!restarted) {
    msg_destroy(du->du_msg), du->du_msg = msg_dup(msg);
    ss->ss_min_se = NH_PGET(nh, min_se);
    ss->ss_session_timer = NH_PGET(nh, session_timer);
    ss->ss_refresher = NH_PGET(nh, refresher);
  }

  if (nh->nh_soa) {
550 551 552 553 554 555 556 557 558 559
    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;
  }

560
  if (offer_sent >= 0) {
561
    sip_time_t invite_timeout = NH_PGET(nh, invite_timeout);
562
    if (invite_timeout == 0)
563
      invite_timeout = UINT_MAX;
564 565 566
    /* Cancel if we don't get response within timeout*/
    nua_dialog_usage_set_expires(du, invite_timeout);
    nua_dialog_usage_set_refresh(du, 0);
567 568

    /* Add session timer headers */
569 570
    if (session_timer_is_supported(nh))
      use_session_timer(ss, 0, prefer_session_timer(nh), msg, sip);
571 572 573 574 575 576 577 578

    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 &&
579
	session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
580 581
      what = "Internal media error"; goto failure;
    }
582

583
    if (nh->nh_soa &&
584
	NH_PGET(nh, media_features) && !nua_dialog_is_established(nh->nh_ds) &&
585 586 587 588 589 590
	!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));
591

592 593 594 595 596 597
      if (ac->cp_params) {
	msg_header_replace_param(msg_home(msg), ac->cp_common, "explicit");
	sip_add_dup(msg, sip, (sip_header_t *)ac);
      }
    }

598 599 600 601
    if (nh->nh_auth) {
      if (auc_authorize(&nh->nh_auth, msg, sip) < 0) {
	what = "Internal authentication error"; goto failure;
      }
602
    }
603

604 605 606 607 608 609 610 611 612
      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;
Pekka Pessi's avatar
Pekka Pessi committed
613
      du->du_refresh = 0;
614
      signal_call_state_change(nh, ss, 0, "INVITE sent",
615 616 617 618 619 620
			       nua_callstate_calling, 0,
			       offer_sent ? "offer" : 0);
      return cr->cr_event = e;
    }
  }

621 622
 failure:

623
  msg_destroy(msg);
624
  if (du && !du->du_ready)
625
    nua_dialog_usage_remove(nh, nh->nh_ds, du), ss = NULL;
626

627
  UA_EVENT2(e, 900, what);
628
  signal_call_state_change(nh, ss, 900, what, nua_callstate_init, 0, 0);
629 630 631 632

  return e;
}

633 634 635 636 637 638 639 640 641 642 643 644 645 646
/** @var nua_event_e::nua_r_invite
 *
 * Answer to outgoing INVITE.
 *
 * The INVITE may be sent explicitly by nua_invite() or
 * implicitly by NUA state machine.
 *
 * @param nh     operation handle associated with the call
 * @param hmagic operation magic associated with the call
 * @param sip    response to INFO or NULL upon an error
 *               (error code and message are in status an phrase parameters)
 * @param tags   empty
 */

647 648 649 650 651
static int process_response_to_invite(nua_handle_t *nh,
				      nta_outgoing_t *orq,
				      sip_t const *sip)
{
  nua_t *nua = nh->nh_nua;
652 653 654
  nua_client_request_t *cr;
  nua_dialog_usage_t *du;
  nua_session_usage_t *ss;
655 656 657 658 659 660
  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;

661
  cr = nua_client_request_by_orq(nh->nh_ds->ds_cr, orq);
662 663 664 665
  du = cr ? cr->cr_usage : NULL;
  ss = nua_dialog_usage_private(du);
  
  assert(cr && du && ss);
666

667 668 669 670 671 672 673 674
  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) {
675 676 677
    if (sip->sip_retry_after)
      gracefully = 0;

678
    terminated = sip_response_terminates_dialog(status, sip_method_invite,
679 680 681
						&gracefully);

    if (!terminated) {
682
      if (check_session_timer_restart(nh, ss, cr, orq, sip, restart_invite))
683 684
	return 0;

685
      if (ss->ss_state < nua_callstate_ready)
686 687 688 689 690 691
	terminated = 1;
    }
  }
  else if (status >= 200) {
    du->du_ready = 1;
    cr->cr_usage = NULL;
692

693 694
    /* XXX - check remote tag, handle forks */
    /* Set route, contact, nh_ds->ds_remote_tag */
695
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
696
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
697

698 699
    init_session_timer(ss, sip, NH_PGET(nh, refresher));
    set_session_timer(ss);
700 701 702 703 704

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

705
      if (NH_PGET(nh, auto_ack) ||
706
	  /* Auto-ACK response to re-INVITE unless auto_ack is set to 0 */
707
	  (ss->ss_state == nua_callstate_ready &&
708 709 710
	   !NH_PISSET(nh, auto_ack)))
	nua_stack_ack(nua, nh, nua_r_ack, NULL);
      else
711
	signal_call_state_change(nh, ss, status, phrase,
712 713 714 715 716
				 nua_callstate_completing, received, 0);
      nh_referral_respond(nh, SIP_200_OK);
      return 0;
    }

717
    status = 500, phrase = "Malformed Session in Response";
718 719 720 721 722 723 724 725

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

726
    return process_100rel(nh, ss, orq, sip); /* signal_call_state_change */
727 728 729 730 731
  }
  else {
    /* Provisional response */
    nh_referral_respond(nh, status, phrase);
    session_process_response(nh, cr, orq, sip, &received);
732
    signal_call_state_change(nh, ss, status, phrase,
733 734 735 736 737 738 739 740 741 742
			     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)
743
    signal_call_state_change(nh, ss, status, phrase,
744 745 746 747 748 749 750 751 752
			     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) {
753
    char *reason =
754 755
      su_sprintf(NULL, "SIP;cause=%u;text=\"%s\"", 
		 status > 699 ? 500 : status, phrase);
756

757
    signal_call_state_change(nh, ss, status, phrase,
758 759
			     nua_callstate_terminating, 0, 0);

760 761 762
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
763 764 765 766 767 768 769

    su_free(NULL, reason);
  }

  return 0;
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
/**@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
789
 *    #nua_i_state  (#nua_i_active, #nua_i_terminated) 
790 791
 */

792 793
int nua_stack_ack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		  tagi_t const *tags)
794
{
795 796
  nua_session_usage_t *ss;
  nua_client_request_t *cr;
797 798 799 800 801
  nta_outgoing_t *ack = NULL;
  msg_t *msg;
  sip_t *sip;
  int status = 200;
  char const *phrase = "OK", *reason = NULL, *sent = NULL;
802 803 804 805
  char const *received;

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

807 808 809
  received = ss ? ss->ss_ack_needed : NULL;

  if (!received)
810
    return UA_EVENT2(nua_i_error, 900, "No response to ACK");
811 812 813 814 815 816

  ss->ss_ack_needed = 0;

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

817
  if (tags)
818
    nua_stack_set_params(nua, nh, nua_i_error, tags);
819

820
  msg = nua_creq_msg(nua, nh, cr, 0,
821 822 823
		     SIP_METHOD_ACK,
		     /* NUTAG_COPY(0), */
		     TAG_NEXT(tags));
824 825 826 827 828 829 830 831
  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 ||
832
	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
833
	reason = soa_error_as_sip_reason(nh->nh_soa);
834
	status = 900, phrase = "Internal media error";
835 836 837 838 839 840 841 842 843 844 845
	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";
      }
    }

846
    if (!reason &&
847 848 849
	/* ss->ss_offer_sent && !ss->ss_answer_recv */
	!soa_is_complete(nh->nh_soa)) {
      /* No SDP answer in 2XX response -> terminate call */
850 851
      status = 988, phrase = "Incomplete offer/answer";
      reason = "SIP;cause=488;text=\"Incomplete offer/answer\"";
852 853 854
    }
  }

855 856 857 858 859 860 861 862 863 864
  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);
  }

865
  if (sip)
866
    ack = nta_outgoing_mcreate(nua->nua_nta, NULL, NULL, NULL, msg,
867 868 869 870
			       SIPTAG_END(), TAG_NEXT(tags));

  if (!ack) {
    if (!reason) {
871
      status = 900, phrase = "Cannot send ACK";
872 873 874 875 876 877 878 879 880
      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) {
881
    signal_call_state_change(nh, ss, status, phrase, nua_callstate_ready,
882 883 884
			     received, sent);
  }
  else {
885
    signal_call_state_change(nh, ss, status, phrase, nua_callstate_terminating,
886 887 888 889
			     0, 0);
    nua_stack_post_signal(nh, nua_r_bye,
			  SIPTAG_REASON_STR(reason),
			  TAG_END());
890 891 892 893 894
  }

  return 0;
}

895

896
/* Process reliable provisional response */
897
static int
898
process_100rel(nua_handle_t *nh,
899
	       nua_session_usage_t *ss,
900 901 902
	       nta_outgoing_t *orq,
	       sip_t const *sip)
{
903 904
  nua_client_request_t *cr_invite = ss->ss_crequest;
  nua_client_request_t *cr_prack = nh->nh_ds->ds_cr;
905 906 907 908
  
  sip_rseq_t *rseq;
  char const *recv = NULL;
  int status; char const *phrase;
909 910

  if (cr_prack->cr_orq) {
911
    /* XXX - better luck next time */
912
    SU_DEBUG_3(("nua(%p): cannot send PRACK because %s is pending\n", nh,
913
		nta_outgoing_method_name(cr_prack->cr_orq)));
914
    return 0; /* Wait until this response is re-transmitted */
915 916 917
  }

  if (!nua_dialog_is_established(nh->nh_ds)) {
918
    /* Establish early dialog */
919 920
    nua_dialog_uac_route(nh, nh->nh_ds, sip, 1);
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
921 922
    
    /* Tag the INVITE request */
923
    cr_invite->cr_orq =
924 925 926 927 928
      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;
  }
929 930 931 932 933
  
  assert(sip);

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

935 936
  if (!rseq) {
    SU_DEBUG_5(("nua(%p): 100rel missing RSeq\n", nh));
937
  }
938 939 940 941 942 943
  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;
944
  }
945 946 947
  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));
948
  }
949 950 951 952 953
  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());
954
  }
955
  /* Here we could let application PRACK and just send state event */
956
  else {
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    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;
977 978
  }

979 980 981
  /* 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);
982 983 984 985

  return 0;
}

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
/**@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
 */

1004 1005 1006
int nua_stack_prack(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		    tagi_t const *tags)
{
1007 1008
  nua_session_usage_t *ss;
  nua_client_request_t *cr;
1009 1010 1011 1012
  msg_t *msg;
  sip_t *sip;
  int offer_sent_in_prack = 0, answer_sent_in_prack = 0;

1013 1014 1015
  int status = 0; char const *phrase = "PRACK sent";
  char const *recv = NULL, *sent = NULL;

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
  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;
  }

1027 1028 1029
  ss = nua_session_usage_get(nh->nh_ds);

  if (!ss || !ss->ss_crequest || !nta_outgoing_rseq(ss->ss_crequest->cr_orq))
1030
    return UA_EVENT2(e, 900, "Nothing to PRACK");
1031
  else if (nh->nh_ds->ds_cr->cr_orq)
1032 1033
    return UA_EVENT2(e, 900, "Request already in progress");

1034
  nua_stack_init_handle(nua, nh, TAG_NEXT(tags));
1035

1036
  cr = nh->nh_ds->ds_cr;
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046
  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) {
1047
    nua_client_request_t *cri = ss->ss_crequest;
1048 1049 1050 1051 1052 1053 1054
    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 ||
1055
	  session_include_description(nh->nh_soa, 1, msg, sip) < 0) {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

	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