nua_register.c 40.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 26 27 28 29 30 31 32 33 34 35
/*
 * 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_register.c
 * @brief REGISTER and registrations
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 *
 * @date Created: Wed Mar  8 11:48:49 EET 2006 ppessi
 */

#include "config.h"

#include <sofia-sip/string0.h>
36
#include <sofia-sip/su_strlst.h>
37 38 39
#include <sofia-sip/su_uniqueid.h>
#include <sofia-sip/su_tagarg.h>

40
#include <sofia-sip/sip_protos.h>
41
#include <sofia-sip/sip_util.h>
42
#include <sofia-sip/sip_status.h>
43 44 45

#define NTA_LEG_MAGIC_T      struct nua_handle_s
#define NTA_OUTGOING_MAGIC_T struct nua_handle_s
46
#define NTA_UPDATE_MAGIC_T   struct nua_s
47

48
#include "nua_stack.h"
49

50
#include <sofia-sip/nta_tport.h>
51
#include <sofia-sip/tport.h>
Pekka Pessi's avatar
Pekka Pessi committed
52
#include <sofia-sip/tport_tag.h>
53

54 55 56 57
#define OUTBOUND_OWNER_T struct nua_handle_s

#include "outbound.h"

58 59 60 61
#if HAVE_SIGCOMP
#include <sigcomp.h>
#endif

62 63 64 65 66 67 68
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <assert.h>

69 70 71 72
#if !defined(random) && defined(_WIN32)
#define random rand
#endif

73 74
/* ======================================================================== */
/* Registrations and contacts */
75

76 77 78 79
int nua_registration_from_via(nua_registration_t **list,
			      su_home_t *home,
			      sip_via_t const *via,
			      int public);
80

81
int nua_registration_add(nua_registration_t **list, nua_registration_t *nr);
82

83
void nua_registration_remove(nua_registration_t *nr);
84

85 86
int nua_registration_set_aor(su_home_t *, nua_registration_t *nr,
			     sip_from_t const *aor);
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
int nua_registration_set_contact(su_home_t *,
				 nua_registration_t *nr,
				 sip_contact_t const *m,
				 int terminating);

void nua_registration_set_ready(nua_registration_t *nr, int ready);

/* ====================================================================== */
/* REGISTER usage */

static char const *nua_register_usage_name(nua_dialog_usage_t const *du);

static int nua_register_usage_add(nua_handle_t *nh,
				  nua_dialog_state_t *ds,
				  nua_dialog_usage_t *du);
static void nua_register_usage_remove(nua_handle_t *nh,
				      nua_dialog_state_t *ds,
				      nua_dialog_usage_t *du);
static void nua_register_usage_peer_info(nua_dialog_usage_t *du,
					 nua_dialog_state_t const *ds,
					 sip_t const *sip);

/** REGISTER usage, aka nua_registration_t */
struct register_usage {
  nua_registration_t *nr_next, **nr_prev, **nr_list; /* Doubly linked list and its head */
  sip_from_t *nr_aor;		/**< AoR for this registration, NULL if none */
  sip_contact_t *nr_contact;	/**< Our Contact */

  /** Status of registration */
  unsigned nr_ready:1;
  /** Kind of registration.
   *
   * If nr_default is true, this is not a real registration but placeholder
   * for Contact header derived from a transport address.
   *
   * If nr_secure is true, this registration supports SIPS/TLS.
   *
   * If nr_public is true, transport should have public address.
   */
  unsigned nr_default:1, nr_secure:1, nr_public:1;
128

129 130
  /** Stack-generated contact */
  unsigned nr_by_stack:1, :0;
131

132 133
  sip_route_t *nr_route;	/**< Outgoing Service-Route */
  sip_path_t *nr_path;		/**< Incoming Path */
134

135 136
  tport_t *nr_tport;		/**< Transport to be used when registered */
  nua_dialog_state_t *nr_dialogs; /**< List of our dialogs */
137

138 139 140
#if HAVE_SIGCOMP
  struct sigcomp_compartment *nr_compartment;
#endif
141

142 143
  outbound_t *nr_ob;	/**< Outbound connection */
};
144

145 146 147 148 149 150 151 152 153
nua_usage_class const nua_register_usage[1] = {
  {
    sizeof (struct register_usage),
    (sizeof nua_register_usage),
    nua_register_usage_add,
    nua_register_usage_remove,
    nua_register_usage_name,
    nua_register_usage_peer_info,
  }};
154

155 156 157 158
static char const *nua_register_usage_name(nua_dialog_usage_t const *du)
{
  return "register";
}
159

160 161 162 163 164
static int nua_register_usage_add(nua_handle_t *nh,
				  nua_dialog_state_t *ds,
				  nua_dialog_usage_t *du)
{
  nua_registration_t *nr = nua_dialog_usage_private(du);
165

166 167
  if (ds->ds_has_register)
    return -1;			/* There can be only one usage */
168

169
  ds->ds_has_register = 1;
170

171
  nr->nr_public = 1;		/* */
172

173 174
  return 0;
}
175

176

177 178 179
static void nua_register_usage_remove(nua_handle_t *nh,
				      nua_dialog_state_t *ds,
				      nua_dialog_usage_t *du)
180
{
181
  nua_registration_t *nr = nua_dialog_usage_private(du);
182

183 184 185 186 187
  if (nr->nr_list)
    nua_registration_remove(nr);	/* Remove from list of registrations */

  if (nr->nr_ob)
    outbound_unref(nr->nr_ob);
188

189
#if HAVE_SIGCOMP
190 191 192
  if (nr->nr_compartment)
    sigcomp_compartment_unref(nr->nr_compartment);
  nr->nr_compartment = NULL;
193
#endif
194 195 196 197 198 199 200 201 202 203 204 205 206 207

  ds->ds_has_register = 0;	/* There can be only one */
}


/** @internal Store information about registrar. */
static void nua_register_usage_peer_info(nua_dialog_usage_t *du,
					 nua_dialog_state_t const *ds,
					 sip_t const *sip)
{
  nua_registration_t *nr = nua_dialog_usage_private(du);
  if (nr->nr_ob)
    outbound_peer_info(nr->nr_ob, sip);
}
208

209 210 211
/* ======================================================================== */
/* REGISTER */

212 213
static void restart_register(nua_handle_t *nh, tagi_t *tags);
static void refresh_register(nua_handle_t *, nua_dialog_usage_t *, sip_time_t);
214 215 216 217 218

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

219 220
static void unregister_expires_contacts(msg_t *msg, sip_t *sip);

221 222 223 224 225
/* Interface towards outbound_t */
static int nua_stack_outbound_features(nua_handle_t *nh, outbound_t *ob);

static int nua_stack_outbound_refresh(nua_handle_t *,
				      outbound_t *ob);
226

227 228
static int nua_stack_outbound_status(nua_handle_t *,
				     outbound_t *ob,
229 230 231
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

232 233
static int nua_stack_outbound_failed(nua_handle_t *,
				     outbound_t *ob,
234 235 236
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

237
static int nua_stack_outbound_credentials(nua_handle_t *, auth_client_t **auc);
238

239 240 241 242 243 244 245
outbound_owner_vtable nua_stack_outbound_callbacks = {
    sizeof nua_stack_outbound_callbacks,
    nua_stack_outbound_refresh,
    nua_stack_outbound_status,
    nua_stack_outbound_failed,
    nua_stack_outbound_failed,
    nua_stack_outbound_credentials
246 247
  };

Pekka Pessi's avatar
Pekka Pessi committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
/**@fn void nua_register(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
 * 
 * Send SIP REGISTER request to the registrar. 
 *
 * Request status will be delivered to the application using #nua_r_register
 * event. When successful the registration will be updated periodically.
 *
 * The handle used for registration cannot be used for any other purposes.
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return
 *     nothing
 *
 * @par Related tags:
 *     NUTAG_REGISTRAR(), NUTAG_KEEPALIVE(), NUTAG_KEEPALIVE_STREAM(),
 *     NUTAG_OUTBOUND()
 *
 * @par Events:
 *     #nua_r_register, #nua_i_outbound
 *
 * @par NAT, Firewall and Outbound Support
 *
 * If the application did not include the Contact header in the tags,
 * nua_register() will generate one and start a protocol engine for outbound
 * connections used for NAT and firewall traversal and connectivity checks.
 * 
276
 * First, nua_register() will probe for NATs in between UA and
Pekka Pessi's avatar
Pekka Pessi committed
277
 * registrar. It will send a REGISTER request as usual. Upon receiving the
278
 * response it checks for the presence of valid "received" and "rport" parameters in
Pekka Pessi's avatar
Pekka Pessi committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 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 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
 * the Via header returned by registrar. The presence of NAT is determined
 * from the "received" parameter in a Via header. When a REGISTER request
 * was sent, the stack inserted the source IP address in the Via header: if
 * that is different from the source IP address seen by the registrar, the
 * registrar inserts the source IP address it sees into the "received"
 * parameter.
 *
 * Please note that an ALG (application-level gateway) modifying the Via
 * headers in outbound requests and again in incoming responses will make
 * the above-described NAT check to fail.
 *
 * The response to the initial REGISTER should also include feature tags
 * indicating whether registrar supports various SIP extensions: @e
 * outbound, @e pref, @e path, @e gruu. If the @e outbound extension is
 * supported, and it is not explicitly disabled by application, the
 * nua_register() will use it. Basically, @e outbound means that instead of
 * registering its contact URI with a particular address-of-record URI, the
 * user-agent registers a transport-level connection. Such a connection is
 * identified on the Contact header field with a @ref NUTAG_INSTANCE()
 * "unique string" identifying the user-agent instance and a numeric index
 * identifying the transport-level connection.
 *
 * If @e outbound is not supported, nua_register() has to generate a URI
 * that can be used to reach it from outside. It will check for public
 * transport addresses detected by underlying stack with, e.g., STUN, UPnP
 * or SOCKS. If there are public addresses, nua_register() will use them. If
 * there is no public address, it will try to generate a Contact URI from
 * the "received" and "rport" parameters found in the Via header of the
 * response message.
 *
 * @par GRUU and Service-Route
 *
 * After a successful response to the REGISTER request has been received,
 * nua_register() will update the information about the registration based
 * on it. If there is a "gruu" parameter included in the response,
 * nua_register() will save it and use the gruu URI in the Contact header
 * fields of dialog-establishing messages, such as INVITE or SUBSCRIBE. 
 * Also, if the registrar has included a Service-Route header in the
 * response, and the service route feature has not been disabled using
 * NUTAG_SERVICE_ROUTE_ENABLE(), the route URIs from the Service-Route
 * header will be used for initial non-REGISTER requests.
 *
 * The #nua_r_register message will include the contact header and route
 * used in with the registration.
 *
 * @par Registration Keep-Alive
 *
 * After the registration has successfully completed the nua_register() will
 * validate the registration and initiate the keepalive mechanism, too. The
 * user-agent validates the registration by sending a OPTIONS requests to
 * itself. If there is an error, nua_register() will indicate that to the
 * application using nua_i_outbound event, and start unregistration
 * procedure (unless that has been explicitly disabled).
 *
 * The keepalive mechanism depends on the network features detected earlier. 
 * If @a outbound extension is used, the STUN keepalives will be used. 
 * Otherwise, NUA stack will repeatedly send OPTIONS requests to itself. In
 * order to save bandwidth, it will include Max-Forwards: 0 in the
 * keep-alive requests, however. The keepalive interval is determined by two
 * parameters: NUTAG_KEEPALIVE() and NUTAG_KEEPALIVE_STREAM(). If the
 * interval is 0, no keepalive messages is sent. The value of
 * NUTAG_KEEPALIVE_STREAM(), if specified, is used to indicate the desired
 * transport-layer keepalive interval for stream-based transports like TLS
 * and TCP.
 */

/** @var nua_event_e::nua_r_register
 *
 * Answer to outgoing REGISTER.
 *
 * The REGISTER may be sent explicitly by nua_register() or implicitly by
 * NUA state machines. The @a status may be 100 even if the real response
 * status returned is different if the REGISTER request has been restarted.
 *
 * @param nh     operation handle associated with the call
 * @param hmagic operation magic associated with the call
 * @param status registration status
 * @param sip    response to REGISTER request or NULL upon an error
 *               (error code and message are in status an phrase parameters)
 * @param tags   empty
 */

/** @var nua_event_e::nua_i_outbound
 *
 * Answer to outgoing REGISTER.
 *
 * The REGISTER may be sent explicitly by nua_register() 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 REGISTER request or NULL upon an error
 *               (error code and message are in status an phrase parameters)
 * @param tags   empty
 */

/**@fn void nua_unregister(nua_handle_t *nh, tag_type_t tag, tag_value_t value, ...);
 * Unregister. 
 *
 * Send a REGISTER request with expiration time 0. This removes the 
 * registration from the registrar. If the handle was earlier used 
 * with nua_register() the periodic updates will be terminated. 
 *
 * If a SIPTAG_CONTACT_STR() with argument "*" is used, all the
 * registrations will be removed from the registrar otherwise only the
 * contact address belonging to the NUA stack is removed.
 *
 * @param nh              Pointer to operation handle
 * @param tag, value, ... List of tagged parameters
 *
 * @return
 *     nothing
 *
 * @par Related tags:
 *     NUTAG_REGISTRAR() \n
 *     Tags in <sip_tag.h> except SIPTAG_EXPIRES() or SIPTAG_EXPIRES_STR()
 *
 * @par Events:
 *     #nua_r_unregister
 */

/** @var nua_event_e::nua_r_unregister
 *
 * Answer to outgoing un-REGISTER.
 *
 * @param nh     operation handle associated with the call
 * @param hmagic operation magic associated with the call
 * @param sip    response to REGISTER request or NULL upon an error
 *               (error code and message are in status and phrase parameters)
 * @param tags   empty
 */


412
int
413 414
nua_stack_register(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		   tagi_t const *tags)
415 416
{
  nua_dialog_usage_t *du;
417 418
  nua_registration_t *nr = NULL;
  outbound_t *ob = NULL;
419 420 421
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg = NULL;
  sip_t *sip;
422
  int terminating = e != nua_r_register;
423 424

  if (nh->nh_special && nh->nh_special != nua_r_register)
425
    return UA_EVENT2(e, 900, "Invalid handle for REGISTER");
426
  if (cr->cr_orq)
427
    return UA_EVENT2(e, 900, "Request already in progress");
428

429
  nua_stack_init_handle(nua, nh, nh_has_register, "", TAG_NEXT(tags));
430
  nh->nh_special = nua_r_register;
431

432
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_register_usage, NULL);
433
  if (!du)
434
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
435 436 437 438
  nr = nua_dialog_usage_private(du); assert(nr);
  nua_registration_add(&nh->nh_nua->nua_registrations, nr);
  if (!terminating && du->du_terminating)
    return UA_EVENT2(e, 900, "Unregister in progress");
439

440 441 442 443
  if (cr->cr_msg)
    msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
  /* Use original message as template when unregistering */
  if (terminating)		
444
    cr->cr_msg = msg_ref_create(du->du_msg);
445

446
  msg = nua_creq_msg(nua, nh, cr, cr->cr_msg != NULL,
447
		     SIP_METHOD_REGISTER,
448
		     TAG_IF(!terminating, NUTAG_USE_DIALOG(1)),
449 450
		     TAG_NEXT(tags));
  sip = sip_object(msg);
451 452
  if (!msg || !sip)
    goto error;
453

454 455 456 457
  if (!nr->nr_aor) {
    if (nua_registration_set_aor(nh->nh_home, nr, sip->sip_to) < 0)
      goto error;
  }
458

459
  du->du_terminating = terminating;
460

461 462
  if (du->du_msg == NULL)
    du->du_msg = msg_ref_create(cr->cr_msg); /* Save original message */
463

464 465 466
  if (terminating)
    /* Add Expires: 0 and remove the expire parameters from contacts */
    unregister_expires_contacts(msg, sip);
467

468 469 470 471 472 473 474 475 476 477 478 479
  if (nua_registration_set_contact(nh->nh_home, nr, sip->sip_contact, terminating) < 0)
    goto error;
  
  ob = nr->nr_ob;
  
  if (!ob && (NH_PGET(nh, outbound) || NH_PGET(nh, instance))) {
    nr->nr_ob = ob = outbound_new(nh, &nua_stack_outbound_callbacks,
				  nh->nh_nua->nua_root,
				  nh->nh_nua->nua_nta,
				  NH_PGET(nh, instance));
    if (!ob)
      goto error;
480
  }
481

482 483 484 485 486 487 488 489 490 491 492 493
  if (ob) {
    outbound_set_options(ob,
			 NH_PGET(nh, outbound),
			 NH_PGET(nh, keepalive),
			 NH_PISSET(nh, keepalive_stream)
			 ? NH_PGET(nh, keepalive_stream)
			 : NH_PGET(nh, keepalive));
    nua_stack_outbound_features(nh, ob);
    outbound_stop_keepalive(ob);

    if (outbound_set_contact(ob, sip->sip_contact, nr->nr_contact, terminating) < 0)
      goto error;
494 495
  }

496 497 498 499 500 501 502 503 504 505 506 507 508 509
  /* This calls nta_outgoing_mcreate() but adds a few tags */
  cr->cr_orq =
    outbound_register_request(ob, terminating,
			      nr->nr_by_stack ? nr->nr_contact : NULL,
			      nua->nua_nta,
			      process_response_to_register, nh, NULL,
			      msg,
			      SIPTAG_END(), 
			      TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
			      TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
			      TAG_NEXT(tags));

  if (!cr->cr_orq)
    goto error;
510

511
  cr->cr_usage = du;
512
  return cr->cr_event = e;
513 514 515 516 517 518

 error:
  msg_destroy(msg);
  msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
  nua_dialog_usage_remove(nh, nh->nh_ds, du);    
  return UA_EVENT1(e, NUA_INTERNAL_ERROR);
519 520 521 522 523 524 525
}

static void
restart_register(nua_handle_t *nh, tagi_t *tags)
{
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg;
526
  nua_dialog_usage_t *du = cr->cr_usage;
527 528
  nua_registration_t *nr = nua_dialog_usage_private(du);
  int terminating = du && du->du_terminating;
529 530 531 532 533 534 535

  cr->cr_restart = NULL;

  if (!cr->cr_msg)
    return;

  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1,
536 537 538 539
		     SIP_METHOD_UNKNOWN,
		     TAG_NEXT(tags));

  if (!msg)
540
    return;			/* XXX - Uh-oh */
541

542
  if (terminating)
543
    unregister_expires_contacts(msg, sip_object(msg));
544

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
  /* This calls nta_outgoing_mcreate() but adds a few tags */
  cr->cr_orq =
    outbound_register_request(nr->nr_ob, terminating,
			      nr->nr_by_stack ? nr->nr_contact : NULL,
			      nh->nh_nua->nua_nta,
			      process_response_to_register, nh, NULL,
			      msg,
			      SIPTAG_END(), 
			      TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
			      TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
			      TAG_NEXT(tags));

  if (!cr->cr_orq)
    msg_destroy(msg);
}
560

561 562 563 564 565 566 567 568 569 570
void
refresh_register(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now)
{
  nua_t *nua = nh->nh_nua;
  nua_client_request_t *cr = nh->nh_cr;
  nua_registration_t *nr = nua_dialog_usage_private(du);
  nua_event_t e;
  msg_t *msg;
  sip_t *sip;
  int terminating;
571

572 573 574 575 576
  if (cr->cr_msg) {
    /* Delay of 5 .. 15 seconds */
    nua_dialog_usage_set_refresh(du, 5 + (unsigned)random() % 11U);
    du->du_pending = refresh_register;
    return;
577
  }
578 579 580

  if (now > 0)
    e = nua_r_register;
581
  else
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    e = nua_r_destroy, du->du_terminating = 1;

  terminating = du->du_terminating;

  outbound_stop_keepalive(nr->nr_ob);

  cr->cr_msg = msg_ref_create(du->du_msg);
  msg = nua_creq_msg(nua, nh, cr, 1,
		     SIP_METHOD_REGISTER,
		     NUTAG_USE_DIALOG(1),
		     TAG_END());
  sip = sip_object(msg);
  if (!msg || !sip)
    goto error;

  if (terminating)
    unregister_expires_contacts(msg, sip);

  cr->cr_orq =
    outbound_register_request(nr->nr_ob, terminating,
			      nr->nr_by_stack ? nr->nr_contact : NULL,
			      nh->nh_nua->nua_nta,
			      process_response_to_register, nh, NULL,
			      msg,
			      SIPTAG_END(), 
			      TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
			      TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
			      TAG_END());
  if (!cr->cr_orq)
    goto error;

  cr->cr_usage = du;
  cr->cr_event = e;
  return;

 error:
  if (terminating)
    nua_dialog_usage_remove(nh, nh->nh_ds, du);
  msg_destroy(msg);
  msg_destroy(cr->cr_msg);
  UA_EVENT2(e, NUA_INTERNAL_ERROR, TAG_END());
  return;
624 625
}

626

627 628 629 630 631 632 633
static
int process_response_to_register(nua_handle_t *nh,
				 nta_outgoing_t *orq,
				 sip_t const *sip)
{
  struct nua_client_request *cr = nh->nh_cr;
  nua_dialog_usage_t *du = cr->cr_usage;
634 635
  nua_registration_t *nr = nua_dialog_usage_private(du);
  int status, ready, reregister, terminating;
636
  char const *phrase;
637 638
  msg_t *_reqmsg = nta_outgoing_getrequest(orq);
  sip_t *req = sip_object(_reqmsg); msg_destroy(_reqmsg);
639 640

  assert(sip);
641
  assert(du && du->du_class == nua_register_usage);
642 643 644 645 646 647
  status = sip->sip_status->st_status;
  phrase = sip->sip_status->st_phrase;

  if (status < 200 || !du)
    return nua_stack_process_response(nh, cr, orq, sip, TAG_END());

648 649
  terminating = du->du_terminating;
  if (!terminating)
650
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
651

652 653 654 655 656 657
  reregister = outbound_register_response(nr->nr_ob, terminating, req, sip);
  if (reregister < 0)
    SET_STATUS1(NUA_INTERNAL_ERROR);
  else if (reregister >= ob_reregister) {
    /* Save msg otherwise nua_creq_check_restart() will zap it */
    msg_t *msg = msg_ref_create(cr->cr_msg);
658

659 660 661 662
    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register)) {
      msg_destroy(msg);
      return 0;
    }
663

664 665
    assert(cr->cr_msg == NULL);
    cr->cr_msg = msg;
666

667 668 669 670 671 672 673 674 675 676
    if (reregister >= ob_reregister_now) {
      /* We can try to reregister immediately */
      nua_creq_restart_with(nh, cr, orq, 100, "Updated Contact",
			    restart_register,
			    TAG_END());
    }
    else {
      /* Outbound will invoke refresh_register() later */
      nua_creq_save_restart(nh, cr, orq, 100, "Updated Contact",
			    restart_register);
677
    }
678
    return 0;
679
  }
680

681
  if (status >= 300)
682 683
    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register))
      return 0;
684

685 686
  ready = !terminating && status < 300;
  du->du_ready = ready;
687

688 689 690 691 692 693
  if (status < 300) {
    sip_time_t mindelta = 0;

    if (!du->du_terminating) {
      sip_time_t now = sip_now(), delta, reqdelta;
      sip_contact_t const *m, *sent;
694

695
      /** Search for lowest delta of SIP contacts we tried to register */
696
      mindelta = SIP_TIME_MAX;
697

698
      reqdelta = req->sip_expires ? req->sip_expires->ex_delta : 0;
699

700
      for (m = sip->sip_contact; m; m = m->m_next) {
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
        if (m->m_url->url_type != url_sip && 
            m->m_url->url_type != url_sips)
          continue;
        for (sent = req->sip_contact; sent; sent = sent->m_next)
          if (url_cmp(m->m_url, sent->m_url) == 0) {
            sip_time_t mdelta = reqdelta;

            if (sent->m_expires)
              mdelta = strtoul(sent->m_expires, NULL, 10);
            if (mdelta == 0)
              mdelta = 3600;

            delta = sip_contact_expires(m, sip->sip_expires, sip->sip_date,
       				 mdelta, now);
            if (delta > 0 && delta < mindelta)
              mindelta = delta;
            if (url_cmp_all(m->m_url, sent->m_url) == 0)
              break;
          }
720 721
      }

722
      if (mindelta == SIP_TIME_MAX)
723 724
        mindelta = 3600;
    }
725

726 727
    nua_dialog_usage_set_refresh(du, mindelta);
    if (mindelta)
728
      du->du_pending = refresh_register;
729
  }
730 731

#if HAVE_SIGCOMP
732 733 734 735 736
  if (ready) {
    struct sigcomp_compartment *cc;
    cc = nta_outgoing_compartment(orq);
    sigcomp_compartment_unref(nr->nr_compartment);
    nr->nr_compartment = cc;
737
  }
738
#endif
739

740
  /*  RFC 3608 Section 6.1 Procedures at the UA
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

   The UA performs a registration as usual.  The REGISTER response may
   contain a Service-Route header field.  If so, the UA MAY store the
   value of the Service-Route header field in an association with the
   address-of-record for which the REGISTER transaction had registered a
   contact.  If the UA supports multiple addresses-of-record, it may be
   able to store multiple service routes, one per address-of-record.  If
   the UA refreshes the registration, the stored value of the Service-
   Route is updated according to the Service-Route header field of the
   latest 200 class response.  If there is no Service-Route header field
   in the response, the UA clears any service route for that address-
   of-record previously stored by the UA.  If the re-registration
   request is refused or if an existing registration expires and the UA
   chooses not to re-register, the UA SHOULD discard any stored service
   route for that address-of-record.
756

757
  */
758 759 760
  if (ready) {
    su_free(nh->nh_home, nr->nr_route);
    nr->nr_route = sip_route_dup(nh->nh_home, sip->sip_service_route);
761 762
  }
  else {
763 764
    su_free(nh->nh_home, nr->nr_route);
    nr->nr_route = NULL;
765
  }
766

767 768 769
  if (ready) {
    /* RFC 3327 */
    /* Store last URI in Path header */
770 771
    sip_path_t *path = sip->sip_path;

772
    while (path && path->r_next)
773 774
      path = path->r_next;

775 776 777 778
    if (!nr->nr_path || !path ||
        url_cmp_all(nr->nr_path->r_url, path->r_url)) {
      su_free(nh->nh_home, nr->nr_path);
      nr->nr_path = sip_path_dup(nh->nh_home, path);
779 780 781
    }
  }

782
  if (ready)
783
    if (sip->sip_to->a_url->url_type == url_sips)
784
      nr->nr_secure = 1;
785

786 787 788 789
  if (nr->nr_ob) {
    if (ready) {
      outbound_gruuize(nr->nr_ob, sip);
      outbound_start_keepalive(nr->nr_ob, orq);
790
    }
791 792
    else
      outbound_stop_keepalive(nr->nr_ob);
793 794
  }

795
  nua_registration_set_ready(nr, ready);
796

797
  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
798
}
799

800
/* ---------------------------------------------------------------------- */
801
/* nua_registration_t interface */
802

803 804 805 806
#if HAVE_SOFIA_STUN
#include <sofia-sip/stun.h>
#endif

807
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
808

809
int
Pekka Pessi's avatar
Pekka Pessi committed
810 811 812 813 814 815 816
nua_stack_init_transport(nua_t *nua, tagi_t const *tags)
{
  url_string_t const *contact1 = NULL, *contact2 = NULL;
  char const *name1 = "sip", *name2 = "sip";
  char const *certificate_dir = NULL;

  tl_gets(tags,
817 818 819 820
          NUTAG_URL_REF(contact1),
          NUTAG_SIPS_URL_REF(contact2),
          NUTAG_CERTIFICATE_DIR_REF(certificate_dir),
          TAG_END());
Pekka Pessi's avatar
Pekka Pessi committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

  if (contact1 &&
      (url_is_string(contact1) 
       ? strncasecmp(contact1->us_str, "sips:", 5) == 0
       : contact1->us_url->url_type == url_sips))
    name1 = "sips";

  if (contact2 && 
      (url_is_string(contact2) 
       ? strncasecmp(contact2->us_str, "sips:", 5) == 0
       : contact2->us_url->url_type == url_sips))
    name2 = "sips";

  if (!contact1 && !contact2) {
    if (nta_agent_add_tport(nua->nua_nta, NULL,
836 837 838 839 840 841 842
       		     TPTAG_IDENT("sip"),
       		     TPTAG_CERTIFICATE(certificate_dir),
       		     TAG_NEXT(nua->nua_args)) < 0 &&
        nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
       		     TPTAG_IDENT("sip"),
       		     TPTAG_CERTIFICATE(certificate_dir),
       		     TAG_NEXT(nua->nua_args)) < 0)
Pekka Pessi's avatar
Pekka Pessi committed
843 844
      return -1;

845 846 847
#if HAVE_SOFIA_STUN
    if (stun_is_requested(TAG_NEXT(nua->nua_args)))
      if (nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
848 849 850 851 852 853
       		       TPTAG_IDENT("stun"),
       		       TPTAG_PUBLIC(tport_type_stun), /* use stun */
       		       TPTAG_CERTIFICATE(certificate_dir),
       		       TAG_NEXT(nua->nua_args)) < 0) {
        SU_DEBUG_5(("nua: error initializing STUN transport\n"));
        return -1;
854 855 856
      }
#endif

Pekka Pessi's avatar
Pekka Pessi committed
857 858
  }
  else if ((!contact1 ||
859 860 861 862 863 864 865 866 867
            nta_agent_add_tport(nua->nua_nta, contact1,
       			 TPTAG_IDENT(name1),
       			 TPTAG_CERTIFICATE(certificate_dir),
       			 TAG_NEXT(nua->nua_args)) < 0) &&
           (!contact2 ||
            nta_agent_add_tport(nua->nua_nta, contact2,
       			 TPTAG_IDENT(name2),
       			 TPTAG_CERTIFICATE(certificate_dir),
       			 TAG_NEXT(nua->nua_args)) < 0)) {
Pekka Pessi's avatar
Pekka Pessi committed
868 869 870 871 872 873 874 875 876 877 878
    return -1;
  }

  if (nua_stack_init_registrations(nua) < 0)
    return -1;

  return 0;
}

int
nua_stack_init_registrations(nua_t *nua)
879 880
{
  /* Create initial identities: peer-to-peer, public, sips */
881 882
  nua_registration_t **list = &nua->nua_registrations;
  su_home_t *home = nua->nua_dhandle->nh_home;
883
  sip_via_t const *v;
884

885 886
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
887
    nua_registration_from_via(list, home, v, 1);
888
  }
889

890 891
  v = nta_agent_via(nua->nua_nta);
  if (v) {
892
    nua_registration_from_via(list, home, v, 0);
893
  }
894 895
  else {
    sip_via_t v[2];
896

897 898 899 900 901 902
    sip_via_init(v)->v_next = v + 1;
    v[0].v_protocol = sip_transport_udp;
    v[0].v_host = "addr.is.invalid.";
    sip_via_init(v + 1);
    v[1].v_protocol = sip_transport_tcp;
    v[1].v_host = "addr.is.invalid.";
903

904
    nua_registration_from_via(list, home, v, 0);
905 906
  }

907
  nta_agent_bind_tport_update(nua->nua_nta, nua, nua_stack_tport_update);
908

909 910 911
  return 0;
}

912 913 914 915
int nua_registration_from_via(nua_registration_t **list,
			      su_home_t *home,
			      sip_via_t const *via,
			      int public)
916
{
917 918 919
  sip_via_t *v, *pair, /* v2[2], */ *vias, **vv, **prev;
  nua_registration_t *nr = NULL, **next;
  su_home_t autohome[SU_HOME_AUTO_SIZE(1024)];
920

921
  vias = sip_via_copy(su_home_auto(autohome, sizeof autohome), via);
922

923 924
  for (; *list; list = &(*list)->nr_next)
    ;
925

926
  next = list;
927

928 929 930
  for (vv = &vias; (v = *vv);) {
    char const *protocol;
    sip_contact_t *contact;
931

932
    *vv = v->v_next, v->v_next = NULL, pair = NULL;
933

934 935 936 937 938 939
    if (v->v_protocol == sip_transport_tcp)
      protocol = sip_transport_udp;
    else if (v->v_protocol == sip_transport_udp)
      protocol = sip_transport_tcp;
    else
      protocol = NULL;
940

941 942 943 944 945 946 947 948 949 950 951
    if (protocol) {
      /* Try to pair vias if we have both udp and tcp */
      for (prev = vv; *prev; prev = &(*prev)->v_next) {
        if (strcasecmp(protocol, (*prev)->v_protocol))
          continue;
        if (strcasecmp(v->v_host, (*prev)->v_host))
          continue;
        if (str0cmp(v->v_port, (*prev)->v_port))
          continue;
        break;
      }
952

953 954 955 956
      if (*prev) {
        pair = *prev; *prev = pair->v_next; pair->v_next = NULL;
      }
    }
957

958 959 960
    nr = su_zalloc(home, sizeof *nr);
    if (!nr)
      break;
961

962
    /* v2[0] = *v; */
963

964 965 966 967 968
    if (pair)
      /* Don't use protocol if we have both udp and tcp */
      protocol = NULL /*, v2[0].v_next = &v2[1], v2[1] = *pair */;
    else
      protocol = via->v_protocol /*, v2[0].v_next = NULL */;
969

970 971
    contact = sip_contact_create_from_via_with_transport(home, v, NULL, protocol);
    /* v = sip_via_dup(home, v2); */
972

973 974 975 976
    if (!contact) {
      su_free(home, nr);
      break;
    }
977

978 979 980 981 982 983 984
    nr->nr_ready = 1, nr->nr_default = 1, nr->nr_public = public;
    nr->nr_secure = contact->m_url->url_type == url_sips;
    nr->nr_contact = contact;
    /* nr->nr_via = v; */

    nr->nr_next = *next, nr->nr_prev = next; *next = nr, next = &nr->nr_next;
    nr->nr_list = list;
985 986
  }

987 988
  su_home_deinit(autohome);

989 990 991
  return 0;
}

992
static
993
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
994
{
995 996 997 998
#if 0
  nua_registration_t *default_oc;
  nua_registration_t const *defaults = nua->nua_registrations;
  sip_via_t *via = nta_agent_via(nta);
999

1000
  default_oc = outbound_by_aor(defaults, NULL, 1);
1001

1002 1003
  if (default_oc) {
    assert(default_oc->nr_via);
1004

1005 1006 1007
    outbound_contacts_from_via(default_oc,
				       via,
				       via->v_next);
1008

1009 1010 1011 1012 1013
    /* refresh_register(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now); */
  }
#endif
  return;
}
1014

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
nua_registration_t *nua_registration_by_aor(nua_registration_t const *list,
					    sip_from_t const *aor,
					    url_t const *remote_uri,
					    int only_default)
{
  sip_from_t *alt_aor = NULL, _alt_aor[1];
  int sips_aor = aor && aor->a_url->url_type == url_sips;
  int sips_uri = remote_uri && remote_uri->url_type == url_sips;

  nua_registration_t const *nr, *public = NULL, *any = NULL;
  nua_registration_t const *namewise = NULL, *sipswise = NULL;

  if (only_default || aor == NULL) {
    /* Ignore AoR, select only by remote_uri */
    for (nr = list; nr; nr = nr->nr_next) {
      if (!nr->nr_ready)
	continue;
      if (only_default && !nr->nr_default)
	continue;
      if (sips_uri ? nr->nr_secure : !nr->nr_secure) 
	return (nua_registration_t *)nr;
      if (!public && nr->nr_public)
	public = nr;
      if (!any)
	any = nr;
1040
    }
1041 1042 1043 1044 1045
    if (public)
      return (nua_registration_t *)public;
    if (any)
      return (nua_registration_t *)any;
    return NULL;
1046 1047
  }

1048 1049
  if (!sips_aor && aor)
    alt_aor = memcpy(_alt_aor, aor, sizeof _alt_aor);
1050

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  for (nr = list; nr; nr = nr->nr_next) {
    if (!nr->nr_ready)
      continue;
    if (nr->nr_aor) {
      if (aor && url_cmp(nr->nr_aor->a_url, aor->a_url) == 0)
	return (nua_registration_t *)nr;
      if (!namewise && alt_aor && url_cmp(nr->nr_aor->a_url, aor->a_url) == 0)
	namewise = nr;
    }
    if (!sipswise && (sips_aor || sips_uri) ? nr->nr_secure : !nr->nr_secure) 
      sipswise = nr;
    if (!public && nr->nr_public)
      public = nr;
    if (!any)
      any = nr;
1066 1067
  }

1068 1069 1070 1071
  if (namewise)
    return (nua_registration_t *)namewise;
  if (sipswise)
    return (nua_registration_t *)sipswise;
1072

1073 1074 1075 1076 1077 1078 1079