nua_register.c 53.7 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
/*
 * 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>
29
 * @author Martti Mela <Martti.Mela@nokia.com>
30 31 32 33 34 35
 *
 * @date Created: Wed Mar  8 11:48:49 EET 2006 ppessi
 */

#include "config.h"

36 37 38
/** @internal SU network changed detector argument pointer type */
#define SU_NETWORK_CHANGED_MAGIC_T struct nua_s

39
#include <sofia-sip/string0.h>
40
#include <sofia-sip/su_strlst.h>
41 42 43
#include <sofia-sip/su_uniqueid.h>
#include <sofia-sip/su_tagarg.h>

44
#include <sofia-sip/sip_protos.h>
45
#include <sofia-sip/sip_util.h>
46
#include <sofia-sip/sip_status.h>
47

48
#define NTA_UPDATE_MAGIC_T   struct nua_s
49

50
#include "nua_stack.h"
51

52
#include <sofia-sip/hostdomain.h>
53
#include <sofia-sip/nta_tport.h>
54
#include <sofia-sip/tport.h>
55
#include <sofia-sip/tport_tag.h>
56

57 58 59 60
#define OUTBOUND_OWNER_T struct nua_handle_s

#include "outbound.h"

61 62 63 64
#if HAVE_SIGCOMP
#include <sigcomp.h>
#endif

65 66 67 68 69 70 71
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <assert.h>

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

75
int nua_registration_from_via(nua_registration_t **list,
76
			      nua_handle_t *nh, 
77 78
			      sip_via_t const *via,
			      int public);
79

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

82
void nua_registration_remove(nua_registration_t *nr);
83

84 85
int nua_registration_set_aor(su_home_t *, nua_registration_t *nr,
			     sip_from_t const *aor);
86

87
int nua_registration_set_contact(nua_handle_t *,
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
				 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);
108 109 110
static void nua_register_usage_refresh(nua_handle_t *,
				       nua_dialog_state_t *,
				       nua_dialog_usage_t *,
111
				       sip_time_t);
112 113 114
static int nua_register_usage_shutdown(nua_handle_t *,
				       nua_dialog_state_t *,
				       nua_dialog_usage_t *);
115 116 117 118 119 120

/** 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 */
121
  sip_via_t *nr_via;		/**< Corresponding Via headers */
122 123 124 125 126 127 128 129 130 131 132 133

  /** 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.
   */
134
  unsigned nr_default:1, nr_secure:1, nr_public:1, nr_ip4:1, nr_ip6:1;
135

136 137
  /** Stack-generated contact */
  unsigned nr_by_stack:1, :0;
138

139 140
  sip_route_t *nr_route;	/**< Outgoing Service-Route */
  sip_path_t *nr_path;		/**< Incoming Path */
141

142 143
  tport_t *nr_tport;		/**< Transport to be used when registered */
  nua_dialog_state_t *nr_dialogs; /**< List of our dialogs */
144

145 146 147
#if HAVE_SIGCOMP
  struct sigcomp_compartment *nr_compartment;
#endif
148

149 150
  outbound_t *nr_ob;	/**< Outbound connection */
};
151

152 153 154 155 156 157 158 159
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,
160 161
    nua_register_usage_refresh,
    nua_register_usage_shutdown
162
  }};
163

164 165 166 167
static char const *nua_register_usage_name(nua_dialog_usage_t const *du)
{
  return "register";
}
168

169 170 171 172 173
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);
174

175 176
  if (ds->ds_has_register)
    return -1;			/* There can be only one usage */
177

178
  ds->ds_has_register = 1;
179

180
  nr->nr_public = 1;		/* */
181

182 183
  return 0;
}
184

185

186 187 188
static void nua_register_usage_remove(nua_handle_t *nh,
				      nua_dialog_state_t *ds,
				      nua_dialog_usage_t *du)
189
{
190
  nua_registration_t *nr = nua_dialog_usage_private(du);
191

192 193 194 195 196
  if (nr->nr_list)
    nua_registration_remove(nr);	/* Remove from list of registrations */

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

198
#if HAVE_SIGCOMP
199 200 201
  if (nr->nr_compartment)
    sigcomp_compartment_unref(nr->nr_compartment);
  nr->nr_compartment = NULL;
202
#endif
203 204 205 206 207 208 209 210 211 212 213 214 215 216

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

218 219 220
/* ======================================================================== */
/* REGISTER */

221
/* Interface towards outbound_t */
222 223 224 225 226 227 228 229
sip_contact_t *nua_handle_contact_by_via(nua_handle_t *nh,
					 su_home_t *home,
					 char const *extra_username,
					 sip_via_t const *v,
					 char const *transport,
					 char const *m_param,
					 ...);

230 231 232 233
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);
234

235 236
static int nua_stack_outbound_status(nua_handle_t *,
				     outbound_t *ob,
237 238 239
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

240 241
static int nua_stack_outbound_failed(nua_handle_t *,
				     outbound_t *ob,
242 243 244
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

245
static int nua_stack_outbound_credentials(nua_handle_t *, auth_client_t **auc);
246

247 248
outbound_owner_vtable nua_stack_outbound_callbacks = {
    sizeof nua_stack_outbound_callbacks,
249
    nua_handle_contact_by_via,
250 251 252 253 254
    nua_stack_outbound_refresh,
    nua_stack_outbound_status,
    nua_stack_outbound_failed,
    nua_stack_outbound_failed,
    nua_stack_outbound_credentials
255 256
  };

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
/**@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:
273
 *     NUTAG_REGISTRAR(), NUTAG_INSTANCE(), NUTAG_OUTBOUND(),
274
 *     NUTAG_KEEPALIVE(), NUTAG_KEEPALIVE_STREAM(), NUTAG_M_USERNAME(),
275
 *     NUTAG_M_DISPLAY(), NUTAG_M_PARAMS(), NUTAG_M_FEATURES(), 
276 277 278
 *
 * @par Events:
 *     #nua_r_register, #nua_i_outbound
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
 * 
 * @par Generating Contact Header
 *
 * If the application did not specify the Contact header in the tags,
 * nua_register() will generate one. It will obtain the schema, IP address
 * for the host and port number for the Contact URI from the transport
 * socket. The diplay name is taken from NUTAG_M_DISPLAY(), URL username
 * part is taken from NUTAG_M_USERNAME(), URI parameters from
 * NUTAG_M_PARAMS(), and Contact header parameters from NUTAG_M_FEATURES(). 
 * If NUTAG_CALLEE_CAPS(1) is specified, additional Contact header
 * parameters are generated based on SDP capabilities and SIP @Allow header.
 * 
 * Note that @b nua may append a identifier of its own to the @Contact URI
 * username. Such nua-generated identifier trailer always starts with "="
 * (equal sign), rest of the nua-generated identifier may contain any
 * url-unreserved characters except "=".
 *
 * Likewise, nua may add transport parameters (such as "transport=tcp" or
 * "maddr") to the @Contact URI. It can add addtional header parameters, like
 * "+sip.instance" or "reg-id", too.
 *
 * For instance, if application uses tags like
 * @code
 *   nua_register(nh,
 *                NUTAG_M_DISPLAY("1"),
 *                NUTAG_M_USERNAME("line-1"),
 *                NUTAG_M_PARAMS("user=phone"),
 *                NUTAG_M_FEATURES("audio"),
 *                NUTAG_CALLEE_CAPS(0),
 *                TAG_END())
 * @endcode
 * @b nua can generate a Contact header like
 * @code
 * Contact: 1 <sip:line-1=SSQAIbjv@192.168.1.200;transport=tcp;user=phone>
 *   ;audio;reg-id=1
 *   ;+sip.instance=urn:uuid:97701ad9-39df-1229-1083-dbc0a85f029c
 * @endcode
 *
 * The incoming request from the proxy should contain the registered contact
 * URI as the request URI. The application can use the username prefix set
 * by NUTAG_M_USERNAME() and the non-transport parameters of the request URI
 * set by NUTAG_M_PARAMS() when determining to which registration the
 * incoming request belongs.
 * 
 * For example, a request line correspoding to the @Contact in above example
 * may look like:
 * @code
 * INVITE sip:line-1=SSQAIbjv@192.168.1.200;user=phone SIP/2.0
 * @endcode
 *
 * @sa NUTAG_M_DISPLAY(), NUTAG_M_USERNAME(), NUTAG_M_PARAMS(),
 * NUTAG_M_FEATURES(), NUTAG_CALLEE_CAPS().
331 332 333
 *
 * @par NAT, Firewall and Outbound Support
 *
334 335 336
 * Normally, @b nua will start start a protocol engine for outbound
 * connections used for NAT and firewall traversal and connectivity checks
 * when registering. 
337
 *
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
 * @note If the application provides @b nua with a
 * @Contact header of its own (or includes a SIPTAG_CONTACT(NULL) tag in
 * nua_register() tags), the outbound protocol engine is not started. It is
 * assumed that the application knows better what it is doing when it sets
 * the @Contact, or it is using experimental CPL upload as specified in 
 * <a href="http://www.ietf.org/internet-drafts/draft-lennox-sip-reg-payload-01.txt">
 * draft-lennox-sip-reg-payload-01.txt</a>.
 *
 * First, outbound engine will probe for NATs in between UA and registrar. 
 * It will send a REGISTER request as usual. Upon receiving the response it
 * checks for the presence of "received" and "rport" parameters in 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 actual source IP address in the Via header: if
 * that is different from the source IP address seen by the registrar, the
353 354 355 356 357 358 359
 * 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.
 *
360 361
 * The response to the initial REGISTER should also include option tags
 * indicating whether registrar supports various SIP extension options: @e
362 363 364 365 366 367 368 369 370 371 372 373 374 375
 * outbound, @e pref, @e path, @e gruu.
 *
 * 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 an instance identifier, application-provided
 * @ref NUTAG_INSTANCE() "unique string" identifying the user-agent instance
 * and a stack-generated numeric index identifying the transport-level
 * connection.
 *
 * If the @e outbound extension is supported, NUTAG_OUTBOUND() contains
 * option string "outbound" and the application has provided an instance
 * identifer to the stack with NUTAG_INSTANCE(), the nua_register() will try
 * to use outbound.
376 377 378 379 380 381 382 383 384
 *
 * 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.
 *
385 386 387 388 389
 * @todo Actually generate public addresses.
 *
 * You can disable this kind of NAT traversal by setting "no-natify" into
 * NUTAG_OUTBOUND() options string.
 * 
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
 * @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
411
 * application using #nua_i_outbound event, and start unregistration
412 413
 * procedure (unless that has been explicitly disabled).
 *
414 415 416
 * You can disable validation by inserting "no-validate" into
 * NUTAG_OUTBOUND() string.
 *
417 418 419 420
 * 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
421 422 423 424 425 426 427 428 429 430 431 432
 * keep-alive requests, however. The keepalive interval is determined by
 * NUTAG_KEEPALIVE() parameter. If the interval is 0, no keepalive messages
 * is sent.
 *
 * You can disable keepalive OPTIONS by inserting "no-options-keepalive"
 * into NUTAG_OUTBOUND() string. Currently there are no other keepalive
 * mechanisms available.
 *
 * 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.
 *
433 434 435 436 437 438 439 440 441
 * @sa #nua_r_register, nua_unregister(), #nua_r_unregister, 
 * #nua_i_register,
 * @RFC3261 section 10,
 * @Expires, @Contact, @CallID, @CSeq,
 * @Path, @RFC3327, @ServiceRoute, @RFC3608, @RFC3680,
 *     NUTAG_REGISTRAR(), NUTAG_INSTANCE(), NUTAG_OUTBOUND(),
 *     NUTAG_KEEPALIVE(), NUTAG_KEEPALIVE_STREAM(), 
 *     SIPTAG_CONTACT(), SIPTAG_CONTACT_STR(), NUTAG_M_USERNAME(),
 *     NUTAG_M_DISPLAY(), NUTAG_M_PARAMS(), NUTAG_M_FEATURES(), 
442 443
 */

444
/** @NUA_EVENT nua_r_register
445
 *
446
 * Response to an outgoing REGISTER.
447 448
 *
 * The REGISTER may be sent explicitly by nua_register() or implicitly by
449 450 451 452
 * NUA state machines. 
 * 
 * When REGISTER request has been restarted the @a status may be 100 even
 * while the real response status returned is different.
453
 *
454 455 456 457 458
 * @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
459
 * @param nh     operation handle associated with the registration
460
 * @param hmagic application context associated with the registration
461
 * @param sip    response message to REGISTER request or NULL upon an error
462 463
 *               (status code is in @a status and 
 *                descriptive message in @a phrase parameters)
464
 * @param tags   empty
465 466 467 468 469 470
 *
 * @sa nua_register(), nua_unregister(), #nua_r_unregister,
 * @Contact, @CallID, @CSeq, @RFC3261 section 10,
 * @Path, @RFC3327, @ServiceRoute, @RFC3608, @RFC3680
 * 
 * @END_NUA_EVENT
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
 */

/**@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
496 497 498 499 500 501 502 503 504
 *
 * @sa nua_register(), #nua_r_register, nua_handle_destroy(), nua_shutdown(),
 * #nua_i_register,
 * @Expires, @Contact, @CallID, @CSeq, @RFC3261 section 10,
 * @Path, @RFC3327, @ServiceRoute, @RFC3608, @RFC3680,
 *     NUTAG_REGISTRAR(), NUTAG_INSTANCE(), NUTAG_OUTBOUND(),
 *     NUTAG_KEEPALIVE(), NUTAG_KEEPALIVE_STREAM(), 
 *     SIPTAG_CONTACT(), SIPTAG_CONTACT_STR(), NUTAG_M_USERNAME(),
 *     NUTAG_M_DISPLAY(), NUTAG_M_PARAMS(), NUTAG_M_FEATURES(), 
505 506
 */

507
/** @NUA_EVENT nua_r_unregister
508 509 510
 *
 * Answer to outgoing un-REGISTER.
 *
511 512 513 514 515
 * @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
516
 * @param nh     operation handle associated with the registration
517
 * @param hmagic application context associated with the registration
518
 * @param sip    response message to REGISTER request or NULL upon an error
519 520
 *               (status code is in @a status and 
 *                descriptive message in @a phrase parameters)
521
 * @param tags   empty
522 523 524 525 526 527
 *
 * @sa nua_unregister(), nua_register(), #nua_r_register,
 * @Contact, @CallID, @CSeq, @RFC3261 section 10,
 * @Path, @RFC3327, @ServiceRoute, @RFC3608, @RFC3680
 * 
 * @END_NUA_EVENT
528 529
 */

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
static int nua_register_client_template(nua_client_request_t *cr,
					msg_t **return_msg,
					tagi_t const *tags);
static int nua_register_client_init(nua_client_request_t *cr,
				    msg_t *, sip_t *,
				    tagi_t const *tags);
static int nua_register_client_request(nua_client_request_t *cr,
				       msg_t *, sip_t *,
				       tagi_t const *tags);
static int nua_register_client_check_restart(nua_client_request_t *cr,
					     int status, char const *phrase,
					     sip_t const *sip);
static int nua_register_client_response(nua_client_request_t *cr,
					int status, char const *phrase,
					sip_t const *sip);

546
static nua_client_methods_t const nua_register_client_methods = {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  SIP_METHOD_REGISTER,
  0,
  {
    /* create_dialog */ 1,
    /* in_dialog */ 0,
    /* target refresh */ 0
  },
  nua_register_client_template,
  nua_register_client_init,
  nua_register_client_request,
  nua_register_client_check_restart,
  nua_register_client_response
};

/**@internal Send REGISTER. */
int nua_stack_register(nua_t *nua,
		       nua_handle_t *nh,
		       nua_event_t e,
		       tagi_t const *tags)
{
  return nua_client_create(nh, e, &nua_register_client_methods, tags);
}

static int nua_register_client_template(nua_client_request_t *cr,
					msg_t **return_msg,
					tagi_t const *tags)
573 574 575
{
  nua_dialog_usage_t *du;

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
  if (cr->cr_event == nua_r_register)
    return 0;

  /* Use a copy of REGISTER message as the template for un-REGISTER */
  du = nua_dialog_usage_get(cr->cr_owner->nh_ds, nua_register_usage, NULL);
  if (du && du->du_cr) {
    if (nua_client_set_target(cr, du->du_cr->cr_target) < 0)
      return -1;
    *return_msg = msg_copy(du->du_cr->cr_msg);
    return 1;
  }

  return 0;
}

static int nua_register_client_init(nua_client_request_t *cr,
				    msg_t *msg, sip_t *sip,
				    tagi_t const *tags)
{
  nua_handle_t *nh = cr->cr_owner;
  nua_dialog_usage_t *du;
  nua_registration_t *nr;
  sip_to_t const *aor = sip->sip_to;

  int unreg;
601

602 603 604 605 606 607 608 609 610
  /* Explicit empty (NULL) contact - used for CPL store/remove? */
  if (!sip->sip_contact && cr->cr_has_contact)
    /* Do not create any usage */
    return 0;

  unreg = cr->cr_event != nua_r_register ||
    (sip->sip_expires && sip->sip_expires->ex_delta == 0);
  if (unreg)
    nua_client_terminating(cr);
611

612
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_register_usage, NULL);
613 614 615 616
  if (du == NULL)
    return -1;
  nr = nua_dialog_usage_private(du);

617
  nua_registration_add(&nh->nh_nua->nua_registrations, nr);
618

619 620
  if (nua_client_bind(cr, du) < 0)
    return -1;
621

622 623 624 625
  if (aor == NULL)
    aor = sip->sip_from;
  if (aor == NULL)
    aor = nh->nh_nua->nua_from;
626

627 628
  if (nua_registration_set_aor(nh->nh_home, nr, aor) < 0)
    return -1;
629

630 631
  if (nua_registration_set_contact(nh, nr, sip->sip_contact, unreg) < 0)
    return -1;
632

633 634 635 636 637 638 639
  if (!nr->nr_ob && (NH_PGET(nh, outbound) || NH_PGET(nh, instance))) {
    nr->nr_ob = outbound_new(nh, &nua_stack_outbound_callbacks,
			     nh->nh_nua->nua_root,
			     nh->nh_nua->nua_nta,
			     NH_PGET(nh, instance));
    if (!nr->nr_ob)
      return nua_client_return(cr, 900, "Cannot create outbound", msg);
640
  }
641

642 643 644 645 646 647 648 649 650 651 652 653 654
  if (nr->nr_ob) {
    outbound_t *ob = nr->nr_ob;
    sip_contact_t *m;

    if (!unreg && sip->sip_contact) {
      for (m = sip->sip_contact; m; m = m->m_next)
	if (!m->m_expires || strtoul(m->m_expires, NULL, 10) != 0)
	  break;
      
      if (m == NULL)
	unreg = 1;	/* All contacts have expires=0 */
    }

655 656 657 658 659 660 661 662
    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);

663 664
    if (outbound_set_contact(ob, sip->sip_contact, nr->nr_via, unreg) < 0)
      return nua_client_return(cr, 900, "Cannot set outbound contact", msg);
665 666
  }

667
  return 0;
668 669
}

670 671 672 673
static
int nua_register_client_request(nua_client_request_t *cr,
				msg_t *msg, sip_t *sip,
				tagi_t const *tags)
674
{
675
  nua_handle_t *nh = cr->cr_owner;
676
  nua_dialog_usage_t *du = cr->cr_usage;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  nua_registration_t *nr;
  sip_contact_t *m = NULL, *contacts = sip->sip_contact, *previous = NULL;
  int unreg;

  (void)nh;

  /* Explicit empty (NULL) contact - used for CPL store/remove? */
  if (!contacts && cr->cr_has_contact)
    return nua_base_client_request(cr, msg, sip, tags);

  if ((du && du->du_shutdown) ||
      (sip->sip_expires && sip->sip_expires->ex_delta == 0))
    nua_client_terminating(cr);

  if (contacts) {
    if (!cr->cr_terminating) {
      for (m = contacts; m; m = m->m_next)
	if (!m->m_expires || strtoul(m->m_expires, NULL, 10) != 0)
	  break;
      /* All contacts have expires=0 */
      if (m == NULL)
	nua_client_terminating(cr);
    }
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    if (cr->cr_terminating) {
      /* Remove the expire parameters from contacts */
      for (m = sip->sip_contact; m; m = m->m_next) {
	if (m->m_url->url_type == url_any) {
	  /* If there is a '*' in contact list, remove everything else */
	  while (m != sip->sip_contact)
	    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_contact);
	  while (m->m_next)
	    sip_header_remove(msg, sip, (sip_header_t *)m->m_next);
	  contacts = m;
	  break;
	}
	msg_header_remove_param(m->m_common, "expires");
      }
    }
  }
717

718
  unreg = cr->cr_terminating;
719

720 721
  if (du) {
    nr = nua_dialog_usage_private(du);
722

723 724 725 726
    if (nr->nr_ob) {
      outbound_stop_keepalive(nr->nr_ob);
      outbound_start_registering(nr->nr_ob);
    }
727

728 729 730 731 732
    if (nr->nr_by_stack) {
      m = nr->nr_contact;
      outbound_get_contacts(nr->nr_ob, &m, &previous);
    }
  }
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747
  return nua_base_client_trequest(cr, msg, sip,
				  /* m is stack-generated contact */
				  SIPTAG_CONTACT(m),
				  /* 
				   * previous is outdated stack-generated contact
				   * which is now unregistered
				   */
				  SIPTAG_CONTACT(previous),
				  TAG_IF(unreg, SIPTAG_EXPIRES_STR("0")),
#if 0
				  TAG_IF(unreg, NTATAG_SIGCOMP_CLOSE(1)),
				  TAG_IF(!unreg, NTATAG_COMP("sigcomp")),
#endif
				  TAG_NEXT(tags));
748
}
749

750 751 752
static int nua_register_client_check_restart(nua_client_request_t *cr,
					     int status, char const *phrase,
					     sip_t const *sip)
753
{
754 755 756 757 758 759 760
  nua_registration_t *nr = nua_dialog_usage_private(cr->cr_usage);
  unsigned short retry_count = cr->cr_retry_count;
  int restart = 0, retry;

  if (nr && nr->nr_ob) {
    msg_t *_reqmsg = nta_outgoing_getrequest(cr->cr_orq);
    sip_t *req = sip_object(_reqmsg); msg_destroy(_reqmsg);
761

762 763
    retry = outbound_register_response(nr->nr_ob, cr->cr_terminating,
				       req, sip);
764

765 766 767 768 769 770 771
    restart = retry >= ob_reregister_now;
    
    if (retry == ob_reregister)
      /* outbound restarts REGISTER later */;

    if (retry < 0)
      /* XXX - report an error? */;
772
  }
773

774 775 776
  /* Check for status-specific reasons to retry */
  if (nua_base_client_check_restart(cr, status, phrase, sip))
    return 1;
777

778 779 780 781 782
  /* Restart only if nua_base_client_check_restart() did not try to restart */
  if (restart && retry_count == cr->cr_retry_count)
    return nua_client_restart(cr, status, phrase);
  
  return 0;
783 784
}

785 786 787
static int nua_register_client_response(nua_client_request_t *cr,
					int status, char const *phrase,
					sip_t const *sip)
788
{
789 790
  nua_handle_t *nh = cr->cr_owner;
  nua_dialog_usage_t *du = cr->cr_usage;
791
  nua_registration_t *nr = nua_dialog_usage_private(du);
792
  int ready;
793

794
  ready = du && !cr->cr_terminated && status < 300;
795

796 797 798
  if (ready) {
    sip_time_t mindelta = 0;
    sip_time_t now = sip_now(), delta, reqdelta, mdelta;
799

800
    sip_contact_t const *m, *sent;
801

802 803 804 805 806
    msg_t *_reqmsg = nta_outgoing_getrequest(cr->cr_orq);
    sip_t *req = sip_object(_reqmsg);

    msg_destroy(_reqmsg);

807
    assert(nr); assert(sip); assert(req);
808

809 810 811 812 813 814 815 816
#if HAVE_SIGCOMP
    {
      struct sigcomp_compartment *cc;
      cc = nta_outgoing_compartment(cr->cr_orq);
      sigcomp_compartment_unref(nr->nr_compartment);
      nr->nr_compartment = cc;
    }
#endif
817

818 819 820 821 822
    /* XXX - if store/remove, remove 
       Content-Disposition
       Content-Type
       body
    */
823

824 825
    /** Search for lowest delta of SIP contacts we tried to register */
    mindelta = SIP_TIME_MAX;
826

827
    reqdelta = req->sip_expires ? req->sip_expires->ex_delta : 0;
828

829 830 831 832
    for (m = sip->sip_contact; m; m = m->m_next) {
      if (m->m_url->url_type != url_sip && 
	  m->m_url->url_type != url_sips)
	continue;
833

834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
      for (sent = req->sip_contact; sent; sent = sent->m_next) {
	if (url_cmp(m->m_url, sent->m_url))
	  continue;

	if (sent->m_expires)
	  mdelta = strtoul(sent->m_expires, NULL, 10);
	else
	  mdelta = reqdelta;

	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;
853
      }
854
    }
855

856 857 858 859
    if (mindelta == SIP_TIME_MAX)
      mindelta = 3600;

    nua_dialog_usage_set_expires(du, mindelta);
860

861
  /*  RFC 3608 Section 6.1 Procedures at the UA
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

   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.
877

878
  */
879 880
    su_free(nh->nh_home, nr->nr_route);
    nr->nr_route = sip_route_dup(nh->nh_home, sip->sip_service_route);
881

882 883 884 885
    {
      /* RFC 3327 */
      /* Store last URI in Path header */
      sip_path_t *path = sip->sip_path;
886

887 888
      while (path && path->r_next)
	path = path->r_next;
889

890 891 892 893 894
      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);
      }
895 896
    }

897
    if (sip->sip_to->a_url->url_type == url_sips)
898
      nr->nr_secure = 1;
899

900
    if (nr->nr_ob) {
901
      outbound_gruuize(nr->nr_ob, sip);
902
      outbound_start_keepalive(nr->nr_ob, cr->cr_orq);
903
    }
904 905 906 907 908 909 910 911 912 913 914 915

    nua_registration_set_ready(nr, 1);
  }
  else if (du) {
    nua_dialog_usage_set_expires(du, 0);

    su_free(nh->nh_home, nr->nr_route);
    nr->nr_route = NULL;

    outbound_stop_keepalive(nr->nr_ob);

    nua_registration_set_ready(nr, 0);
916 917 918
  }


919 920 921 922 923 924 925 926
  return nua_base_client_response(cr, status, phrase, sip, NULL);
}

static void nua_register_usage_refresh(nua_handle_t *nh,
				       nua_dialog_state_t *ds,
				       nua_dialog_usage_t *du,
				       sip_time_t now)
{
927
  nua_t *nua = nh->nh_nua;
928 929 930 931 932 933 934 935 936
  nua_client_request_t *cr = du->du_cr;

  if (cr) {
    if (nua_client_is_queued(cr) /* Already registering. */
	|| nua_client_resend_request(cr, 0, NULL) >= 0)
      return;
  }

  /* Report that we have de-registered */
937
  nua_stack_event(nua, nh, NULL, nua_r_register, NUA_INTERNAL_ERROR, NULL);
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
  nua_dialog_usage_remove(nh, ds, du);
}

/** @interal Shut down REGISTER usage.
 *
 * @retval >0  shutdown done
 * @retval 0   shutdown in progress
 * @retval <0  try again later
 */
static int nua_register_usage_shutdown(nua_handle_t *nh,
				     nua_dialog_state_t *ds,
				     nua_dialog_usage_t *du)
{
  nua_client_request_t *cr = du->du_cr;

  if (cr) {
    if (nua_client_is_queued(cr)) /* Already registering. */
      return -1;
    cr->cr_event = nua_r_unregister;
    if (nua_client_resend_request(cr, 1, NULL) >= 0)
      return 0;
  }

  nua_dialog_usage_remove(nh, ds, du);
  return 200;
963
}
964

965
/* ---------------------------------------------------------------------- */
966
/* nua_registration_t interface */
967

968 969 970 971
#if HAVE_SOFIA_STUN
#include <sofia-sip/stun.h>
#endif

972
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
973 974 975 976 977
static int nua_registration_add_contact_and_route(nua_registration_t *nr,
						  msg_t *msg,
						  sip_t *sip,
						  int add_contact,
						  int add_service_route);
978

979
int
980 981 982 983 984 985 986
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,
987 988 989 990
          NUTAG_URL_REF(contact1),
          NUTAG_SIPS_URL_REF(contact2),
          NUTAG_CERTIFICATE_DIR_REF(certificate_dir),
          TAG_END());
991

992 993 994
  if (!contact1 && contact2)
    contact1 = contact2, contact2 = NULL;

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
  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";

1007
  if (!contact1 /* && !contact2 */) {
1008
    if (nta_agent_add_tport(nua->nua_nta, NULL,
1009 1010 1011
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0 &&
1012
        nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
1013 1014 1015
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
1016
      return -1;
1017
#if HAVE_SOFIA_STUN
1018 1019 1020 1021 1022 1023 1024 1025
    if (stun_is_requested(TAG_NEXT(nua->nua_args)) &&
	nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:0.0.0.0:*"),
			    TPTAG_IDENT("stun"),
			    TPTAG_PUBLIC(tport_type_stun), /* use stun */
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0) {
      SU_DEBUG_0(("nua: error initializing STUN transport\n"));
    }
1026
#endif
1027
  }
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  else {
    if (nta_agent_add_tport(nua->nua_nta, contact1,
			    TPTAG_IDENT(name1),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;

    if (contact2 &&
	nta_agent_add_tport(nua->nua_nta, contact2,
			    TPTAG_IDENT(name2),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0) 
      return -1;
1041 1042
  }

1043

1044 1045 1046 1047 1048 1049
  if (nua_stack_init_registrations(nua) < 0)
    return -1;

  return 0;
}

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
#if 0
  /* Store network detector param value */
  if (agent->sa_nw_updates == 0)
    agent->sa_nw_updates = nw_updates;
 	      NTATAG_DETECT_NETWORK_UPDATES_REF(nw_updates),
  unsigned nw_updates = 0;
  unsigned nw_updates = 0;

  su_network_changed_t *sa_nw_changed;

#endif

static
void nua_network_changed_cb(nua_t *nua, su_root_t *root)
{

  uint32_t nw_updates = NUA_NW_DETECT_TRY_FULL;

  switch (nw_updates) {
  case NUA_NW_DETECT_ONLY_INFO:
1070
    nua_stack_event(nua, NULL, NULL, nua_i_network_changed, SIP_200_OK, NULL);
1071 1072 1073 1074 1075 1076 1077
    break;
    
  case NUA_NW_DETECT_TRY_FULL:

    /* 1) Shutdown all tports */
    nta_agent_close_tports(nua->nua_nta);

1078
    /* 2) Create new tports */
1079 1080 1081
    if (nua_stack_init_transport(nua, nua->nua_args) < 0)
      /* We are hosed */
      nua_stack_event(nua, NULL, NULL, nua_i_network_changed,
1082
		      900, "Internal Error", NULL);
1083 1084
    else
      nua_stack_event(nua, NULL, NULL, nua_i_network_changed,
1085
		      SIP_200_OK, NULL);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

    break;
    
  default:
    break;
  }

  return;
}

int nua_stack_launch_network_change_detector(nua_t *nua)
{
  su_network_changed_t *snc = NULL;

  snc = su_root_add_network_changed(nua->nua_home,
				    nua->nua_api_root,
				    nua_network_changed_cb,
				    nua);
  
  if (!snc)
    return -1;

  nua->nua_nw_changed = snc;

  return 0;
}


1114 1115
int
nua_stack_init_registrations(nua_t *nua)
1116 1117
{
  /* Create initial identities: peer-to-peer, public, sips */
1118 1119
  nua_registration_t **nr_list = &nua->nua_registrations, **nr_next;
  nua_handle_t **nh_list;
1120
  nua_handle_t *dnh = nua->nua_dhandle;
1121
  sip_via_t const *v;
1122

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  /* Remove existing, local address based registrations and count the
     rest */
  while (nr_list && *nr_list) {
    nr_next = &(*nr_list)->nr_next;
    if ((*nr_list)->nr_default == 1) {
      nua_registration_remove(*nr_list);
      /* memset(*nr_list, 170, sizeof(**nr_list)); */
      /* XXX - free, too */
    }
    nr_list = nr_next;
  }
  nr_list = &nua->nua_registrations;

1136 1137
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
1138
    nua_registration_from_via(nr_list, dnh, v, 1);
1139
  }
1140

1141 1142
  v = nta_agent_via(nua->nua_nta);
  if (v) {
1143
    nua_registration_from_via(nr_list, dnh, v, 0);
1144
  }
1145 1146
  else {
    sip_via_t v[2];
1147

1148 1149 1150 1151 1152 1153
    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.";
1154

1155
    nua_registration_from_via(nr_list, dnh, v, 0);
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
  }

  /* Go through all the registrations and set to refresh almost
     immediately */
  nh_list = &nua->nua_handles;
  for (; *nh_list; nh_list = &(*nh_list)->nh_next) {
    nua_dialog_state_t *ds;
    nua_dialog_usage_t *du;

    ds = (*nh_list)->nh_ds;
    du = ds->ds_usage;

    if (ds->ds_has_register == 1 && du->du_class->usage_refresh) {
1169
      nua_dialog_usage_refresh(*nh_list, ds, du, 1);
1170
    }
1171 1172
  }

1173
  nta_agent_bind_tport_update(nua->nua_nta, nua, nua_stack_tport_update);
1174

1175 1176 1177
  return 0;
}

1178
int nua_registration_from_via(nua_registration_t **list,
1179
			      nua_handle_t *nh,
1180 1181
			      sip_via_t const *via,
			      int public)
1182
{
1183
  su_home_t *home = nh->nh_home;
1184 1185 1186
  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)];
1187
  int nr_items = 0;
1188

1189
  vias = sip_via_copy(su_home_auto(autohome, sizeof autohome), via);
1190

1191
  for (; *list; list = &(*list)->nr_next)
1192
    ++nr_items;
1193

1194
  next = list;
1195

1196 1197 1198
  for (vv = &vias; (v = *vv);) {
    char const *protocol;
    sip_contact_t *contact;
1199
    sip_via_t v2[2];
1200

1201
    *vv = v->v_next, v->v_next = NULL, pair = NULL;
1202

1203 1204 1205 1206 1207 1208
    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;
1209

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
    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;
      }
1221

1222 1223 1224 1225
      if (*prev) {
        pair = *prev; *prev = pair->v_next; pair->v_next = NULL;
      }
    }
1226

1227 1228 1229
    /* if more than one candidate, ignore local entries */
    if (v && (*vv || nr_items > 0) && 
	host_is_local(v->v_host)) {
1230 1231
      SU_DEBUG_9(("nua_register: ignoring contact candidate %s:%s.\n", 
		  v->v_host, v->v_port ? v->v_port : ""));
1232 1233 1234
      continue;
    }
     
1235 1236 1237
    nr = su_zalloc(home, sizeof *nr);
    if (!nr)
      break;
1238

1239
    v2[0] = *v;
1240

1241 1242
    if (pair)
      /* Don't use protocol if we have both udp and tcp */
1243
      protocol = NULL, v2[0].v_next = &v2[1], v2[1] = *pair;
1244
    else
1245
      protocol = via->v_protocol, v2[0].v_next = NULL;
1246

1247
    v2[1].v_next = NULL;
1248

1249 1250 1251 1252 1253 1254 1255 1256
#if 1
    contact = nua_handle_contact_by_via(nh, home, NULL, v2, protocol, NULL);
#else
    contact = sip_contact_create_from_via_with_transport(home, v2, NULL, protocol);
#endif
    v = sip_via_dup(home, v2);

    if (!contact || !v) {
1257 1258 1259
      su_free(home, nr);
      break;
    }
1260

1261 1262 1263
    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;
1264
    nr->nr_via = v;
1265 1266
    nr->nr_ip4 = host_is_ip4_address(contact->m_url->url_host);
    nr->nr_ip6 = !nr->nr_ip4 && host_is_ip6_reference(contact->m_url->url_host);
1267

1268 1269 1270
    SU_DEBUG_9(("nua_register: Adding contact URL '%s' to list.\n", contact->m_url->url_host));

    ++nr_items;
1271 1272
    nr->nr_next = *next, nr->nr_prev = next; *next = nr, next = &nr->nr_next;
    nr->nr_list = list;
1273 1274
  }

1275 1276
  su_home_deinit(autohome);

1277 1278 1279
  return 0;
}

1280
static
1281
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
1282
{
1283 1284 1285 1286
#if 0
  nua_registration_t *default_oc;
  nua_registration_t const *defaults = nua->nua_registrations;
  sip_via_t *via = nta_agent_via(nta);
1287

1288
  default_oc = outbound_by_aor(defaults, NULL, 1);
1289

1290 1291
  if (default_oc) {
    assert(default_oc->nr_via);
1292

1293 1294 1295
    outbound_contacts_from_via(default_oc,
				       via,
				       via->v_next);
1296

1297 1298 1299 1300 1301
    /* refresh_register(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now); */
  }
#endif
  return;
}
1302

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
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;

1315 1316 1317
  int ip4 = remote_uri && host_is_ip4_address(remote_uri->url_host);
  int ip6 = remote_uri && host_is_ip6_reference(remote_uri->url_host);

1318 1319 1320 1321 1322 1323 1324
  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;
1325 1326 1327 1328
      if (nr->nr_ip4 && ip6)
	continue;
      if (nr->nr_ip6 && ip4)
	continue;
1329 1330 1331 1332 1333 1334
      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;
1335
    }
1336 1337 1338 1339 1340
    if (public)
      return (nua_registration_t *)public;
    if (any)
      return (nua_registration_t *)any;
    return NULL;
1341 1342
  }

1343 1344
  if (!sips_aor && aor)
    alt_aor = memcpy(_alt_aor, aor, sizeof _alt_aor);
1345

1346
  for (nr = list; nr; nr = nr->nr_next) {
1347
    if (!nr->nr_ready || !nr->nr_contact)
1348 1349 1350 1351 1352 1353 1354
      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;
    }
1355 1356 1357 1358 1359
    else {
      if (!sipswise && ((sips_aor || sips_uri) ? 
			nr->nr_secure : !nr->nr_secure))
	sipswise = nr;
    }
1360 1361 1362 1363
    if (!public && nr->nr_public)
      public = nr;
    if (!any)
      any = nr;
1364 1365
  }

1366 1367 1368 1369
  if (namewise)
    return (nua_registration_t *)namewise;
  if (sipswise)
    return (nua_registration_t *)sipswise;
1370

1371 1372 1373 1374 1375 1376 1377 1378
  /* XXX - 
     should we do some policing whether sips_aor or sips_uri can be used
     with sip contact?
  */
  if (public)
    return (nua_registration_t *)public;
  if (any)
    return (nua_registration_t *)any;
1379

1380
  return NULL;
1381 1382
}

1383

1384
nua_registration_t *
1385
nua_registration_for_request(nua_registration_t const *list, sip_t const *sip)
1386
{
1387 1388
  sip_from_t const *aor;
  url_t *uri;
1389

1390 1391
  aor = sip->sip_from;
  uri = sip->sip_request->rq_url;
1392

1393 1394 1395 1396 1397 1398 1399 1400 1401
  return nua_registration_by_aor(list, aor, uri, 0);
}

nua_registration_t *
nua_registration_for_response(nua_registration_t const *list, 
			      sip_t const *sip,
			      sip_record_route_t const *record_route,
			      sip_contact_t const *remote_contact)
{
1402
  nua_registration_t *nr;
1403 1404 1405 1406
  sip_to_t const *aor = NULL;
  url_t const *uri = NULL;

  if (sip)
1407
    aor = sip->sip_to;
1408 1409 1410 1411 1412 1413 1414 1415 1416
  
  if (record_route)
    uri = record_route->r_url;
  else if (sip && sip->sip_record_route)
    uri = sip->sip_record_route->r_url;
  else if (remote_contact)
    uri = remote_contact->m_url;
  else if (sip && sip->sip_from)
    uri = sip->sip_from->a_url;
1417

1418 1419 1420
  nr = nua_registration_by_aor(list, aor, uri, 0);

  return nr;
1421
}
1422

1423

1424 1425
/** Return Contact usable in dialogs */
sip_contact_t const *nua_registration_contact(nua_registration_t const *nr)
1426
{
1427 1428 1429 1430
  if (nr->nr_by_stack && nr->nr_ob) {
    sip_contact_t const *m = outbound_dialog_contact(nr->nr_ob);
    if (m)
      return m;
1431 1432
  }

1433
  return nr->nr_contact;
1434 1435
}

1436 1437
/** Return initial route. */
sip_route_t const *nua_registration_route(nua_registration_t const *nr)
1438
{
1439
  return nr ? nr->nr_route : NULL;
1440 1441
}

1442
sip_contact_t const *nua_stack_get_contact(nua_registration_t const *nr)
1443
{
1444 1445
  nr = nua_registration_by_aor(nr, NULL, NULL, 1);
  return nr ? nr->nr_contact : NULL;
1446 1447
}

1448 1449 1450 1451 1452 1453
/** Add a Contact (and Route) header to request */
int nua_registration_add_contact_to_request(nua_handle_t *nh,
					    msg_t *msg,
					    sip_t *sip,
					    int add_contact,
					    int add_service_route)
1454
{
1455
  nua_registration_t *nr = NULL;
1456

1457
  if (!add_contact && !add_service_route)
1458 1459
    return 0;

1460
  if (nh == NULL || msg == NULL)
1461 1462
    return -1;

1463 1464 1465
  if (sip == NULL)
    sip = sip_object(msg);

1466
  if (nr == NULL)
1467 1468 1469
    nr = nua_registration_for_request(nh->nh_nua->nua_registrations, sip);

  return nua_registration_add_contact_and_route(nr, msg, sip, 
1470 1471
						add_contact, 
						add_service_route);
1472
}
1473

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
/** Add a Contact header to response.
 *
 * @param nh
 * @param msg response message
 * @param sip response headers
 * @param record_route record-route from request
 * @param remote_contact Contact from request
 */
int nua_registration_add_contact_to_response(nua_handle_t *nh,
					     msg_t *msg,
					     sip_t *sip,
					     sip_record_route_t const *record_route,
					     sip_contact_t const *remote_contact)
{
  nua_registration_t *nr = NULL;

  if (sip == NULL)
    sip = sip_object(msg);

  if (nh == NULL || msg == NULL || sip == NULL)
    return -1;

  if (nr == NULL)
    nr = nua_registration_for_response(nh->nh_nua->nua_registrations, sip,
				       record_route, remote_contact);

  return nua_registration_add_contact_and_route(nr, msg, sip, 1, 0);
}

/** Add a Contact (and Route) header to request */
static 
int nua_registration_add_contact_and_route(nua_registration_t *nr,
					   msg_t *msg,
					   sip_t *sip,
					   int add_contact,
					   int add_service_route)
{
1511 1512
  if (nr == NULL)
    return -1;
1513

1514 1515 1516 1517
  if (add_contact) {
    sip_contact_t const *m = nua_registration_contact(nr);
    if (!m || msg_header_add_dup(msg, (msg_pub_t *)sip, (void const *)m) < 0)
      return -1;
1518 1519
  }