nua_register.c 55.5 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 40 41
#include <sofia-sip/sha1.h>
#include <sofia-sip/su_uniqueid.h>
#include <sofia-sip/token64.h>
#include <sofia-sip/su_tagarg.h>

42 43
#include <sofia-sip/bnf.h>

44
#include <sofia-sip/sip_protos.h>
45
#include <sofia-sip/sip_util.h>
46
#include <sofia-sip/sip_status.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_UPDATE_MAGIC_T   struct nua_s
51

52
#include "nua_stack.h"
53
#include <sofia-sip/nta_tport.h>
Pekka Pessi's avatar
Pekka Pessi committed
54
#include <sofia-sip/tport_tag.h>
55 56 57 58 59

#if HAVE_SIGCOMP
#include <sigcomp.h>
#endif

60 61 62 63 64 65 66
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <assert.h>

67 68 69 70
#if !defined(random) && defined(_WIN32)
#define random rand
#endif

71 72 73 74 75 76 77 78 79 80 81
/* ====================================================================== */
/* Outbound connection */

typedef struct outbound_connect outbound_connect;
typedef struct outbound_owner_vtable outbound_owner_vtable;

int outbound_connect_init(outbound_connect *ru,
			  outbound_owner_vtable const *owner_methods,
			  su_root_t *root,
			  nta_agent_t *agent,
			  char const *options);
82

83
int outbound_connect_set_options(outbound_connect *oc, char const *options);
84

85
int outbound_connect_set_features(outbound_connect *ru, char *features);
86

87
int outbound_connect_check_for_nat(struct outbound_connect *ru,
88 89 90
				 nta_outgoing_t *orq,
				 sip_t const *sip);

91
int outbound_connect_contacts_from_via(outbound_connect *ru,
92 93 94
				     sip_via_t const *via,
				     sip_via_t const *pair);

95
int outbound_connect_set_contact(struct outbound_connect *ru,
96 97
			       sip_contact_t *m);

98
int outbound_connects_from_via(struct outbound_connect **list,
99 100 101 102
			     nua_owner_t *owner,
			     sip_via_t const *via,
			     int public);

103
int outbound_connect_set_contact_by_aor(struct outbound_connect *ru,
104
				      url_t const *aor,
105
				      outbound_connect const *defaults);
106

107
outbound_connect *outbound_connect_by_aor(outbound_connect const *usages,
108 109 110
				      url_t const *aor,
				      int only_default);

111 112
int outbound_connect_gruuize(struct outbound_connect *oc, sip_t const *sip);

113
void outbound_connect_start_keepalive(struct outbound_connect *ru,
114 115
				    unsigned interval,
				    nta_outgoing_t *register_trans);
116

117
void outbound_connect_stop_keepalive(struct outbound_connect *ru);
118

119
int outbound_connect_check_accept(sip_accept_t const *accept);
120

121 122 123
int outbound_connect_process_options(struct outbound_connect *usages,
				     nta_incoming_t *irq,
				     sip_t const *sip);
124

125
sip_contact_t const *outbound_connect_contact(outbound_connect const *ru);
126

127 128
char const * const outbound_connect_content_type;
nua_usage_class const *nua_outbound_connect;
129

130
struct outbound_owner_vtable
131
{
132 133
  int oo_size;
  int (*oo_status)(nua_owner_t *, outbound_connect *ru,
134 135
		   int status, char const *phrase,
		   tag_type_t tag, tag_value_t value, ...);
136 137 138 139 140 141
  int (*oo_probe_error)(nua_owner_t *, outbound_connect *ru,
			int status, char const *phrase,
			tag_type_t tag, tag_value_t value, ...);
  int (*oo_keepalive_error)(nua_owner_t *, outbound_connect *ru,
			    int status, char const *phrase,
			    tag_type_t tag, tag_value_t value, ...);
142
};
143

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
struct outbound_connect {
  struct outbound_connect *oc_next, **oc_prev; /* Doubly linked list */
  outbound_owner_vtable
  const *oc_oo;			/**< Callbacks */
  nua_owner_t *oc_owner;	/**< Backpointer */
  su_root_t *oc_root;		/**< Root for timers and stuff */
  nta_agent_t *oc_nta;		/**< SIP transactions */

  char oc_cookie[32];		/**< Our magic cookie */

  int32_t oc_reg_id;		/**< Flow-id */

  struct outbound_prefs {
    unsigned gruuize:1;		/**< Establish a GRUU */
    unsigned outbound:1;	/**< Try to use outbound */
    unsigned natify:1;		/**< Try to detect NAT */
    unsigned validate:1;	/**< Validate registration with OPTIONS */
    /* How to detect NAT binding or connect to outbound: */
    unsigned use_connect:1;	/**< Use HTTP connect */
    unsigned use_rport:1;	/**< Use received/rport */
    unsigned use_socks:1;	/**< Detect and use SOCKS V5 */
    unsigned use_upnp:1;	/**< Detect and use UPnP */
    unsigned use_stun:1;	/**< Detect and try to use STUN */
    unsigned :0;
  } oc_prefs;

  struct outbound_info {
    /* 0 do not support, 1 - perhaps supports, 2 supports, 4 requires */
    unsigned gruu:2, outbound:2, pref:2;
  } oc_info;

  unsigned oc_default:1, oc_secure:1, oc_public:1;
  unsigned oc_by_application:1;
  unsigned oc_add_contact:1;
178

179
  /* The registration state machine. */
Pekka Pessi's avatar
Pekka Pessi committed
180
  /** Initial REGISTER containing oc_rcontact has been sent */
181
  unsigned oc_registering:1;
Pekka Pessi's avatar
Pekka Pessi committed
182
  /** 2XX response to REGISTER containg oc_rcontact has been received */
183
  unsigned oc_registered:1;
Pekka Pessi's avatar
Pekka Pessi committed
184 185
  /**The registration has been validated:
   * We have successfully sent OPTIONS to ourselves.
186
   */
187
  unsigned oc_validated:1;
Pekka Pessi's avatar
Pekka Pessi committed
188
  /** The registration has been validated once.
189 190 191
   *   We have successfully sent OPTIONS to ourselves, so do not give
   *   up if OPTIONS probe fails.
   */
192
  unsigned oc_once_validated:1;
193

194
  unsigned :0;
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  tport_t *oc_tport;		/**< Transport used when registered */
  char const *oc_features;	/**< Feature parameters for rcontact */
  sip_via_t *oc_via;		/**< Our Via (or Via pair) */
  sip_contact_t *oc_rcontact;	/**< Our contact */
  sip_contact_t *oc_dcontact;	/**< Contact for dialogs */
  sip_contact_t *oc_previous;	/**< Stale contact */
  sip_contact_t *oc_gruu;	/**< Contact added to requests */
  sip_route_t *oc_route;	/**< Outgoing Service-Route */
  sip_path_t *oc_path;		/**< Incoming Path */
  sip_contact_t *oc_obp;	/**< Contacts from outbound proxy */

  char *oc_nat_detected;	/**< Our public address */
  char *oc_nat_port;		/**< Our public port number */

  void *oc_stun;		/**< Stun context */
  void *oc_upnp;		/**< UPnP context  */

  char *oc_sipstun;		/**< Stun server usable for keep-alives */
  unsigned oc_keepalive;	/**< Interval. */
  su_timer_t *oc_kalt;		/**< Keep-alive timer */
  msg_t *oc_kalmsg;		/**< Keep-alive OPTIONS message */
  nta_outgoing_t *oc_kalo;	/**< Keep-alive OPTIONS transaction */
218

219
#if HAVE_SIGCOMP
220
  struct sigcomp_compartment *oc_compartment;
221 222
#endif
};
223

224 225 226
/* ======================================================================== */
/* REGISTER */

227 228
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);
229 230 231 232 233

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

234 235
static void unregister_expires_contacts(msg_t *msg, sip_t *sip);

236
static char *nua_stack_register_features(nua_handle_t *nh);
237

238
static int nua_stack_register_status(nua_handle_t *, outbound_connect *oc,
239 240 241
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

242
static int nua_stack_register_failed(nua_handle_t *, outbound_connect *oc,
243 244 245
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

246
outbound_owner_vtable nua_stack_register_callbacks = {
247 248 249 250 251 252
    sizeof nua_stack_register_callbacks,
    nua_stack_register_status,
    nua_stack_register_failed,
    nua_stack_register_failed,
  };

Pekka Pessi's avatar
Pekka Pessi committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 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 412 413 414 415 416
/**@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.
 * 
 * First, nua_register() will first probe for NATs in between UA and
 * registrar. It will send a REGISTER request as usual. Upon receiving the
 * response check 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 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
 */


417
int
418 419
nua_stack_register(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		   tagi_t const *tags)
420 421
{
  nua_dialog_usage_t *du;
422
  struct outbound_connect *oc = NULL;
423 424 425
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg = NULL;
  sip_t *sip;
426
  int terminating = e != nua_r_register;
427 428

  if (nh->nh_special && nh->nh_special != nua_r_register)
429
    return UA_EVENT2(e, 900, "Invalid handle for REGISTER");
430
  if (cr->cr_orq)
431
    return UA_EVENT2(e, 900, "Request already in progress");
432

433
  nua_stack_init_handle(nua, nh, nh_has_register, "", TAG_NEXT(tags));
434
  nh->nh_special = nua_r_register;
435

436
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_outbound_connect, NULL);
437
  if (!du)
438
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
439 440 441 442 443
  oc = nua_dialog_usage_private(du); assert(oc);

  outbound_connect_init(oc, &nua_stack_register_callbacks,
			nh->nh_nua->nua_root, nh->nh_nua->nua_nta,
			NH_PGET(nh, outbound));
444

445
  outbound_connect_set_features(oc, nua_stack_register_features(nh));
446

447
  outbound_connect_stop_keepalive(oc);
448

449 450
  if (du->du_msg)
    cr->cr_msg = msg_ref_create(du->du_msg);
451

452
  msg = nua_creq_msg(nua, nh, cr, cr->cr_msg != NULL,
453
		     SIP_METHOD_REGISTER,
454
		     TAG_IF(!terminating, NUTAG_USE_DIALOG(1)),
455 456 457
		     TAG_NEXT(tags));
  sip = sip_object(msg);

458 459
  if (sip) {
    du->du_terminating = terminating;
460

461 462 463 464
    if (du->du_msg)
      msg_destroy(du->du_msg);
    du->du_msg = msg_ref_create(cr->cr_msg);

465
    if (sip->sip_contact)
466
      outbound_connect_set_contact(oc, sip->sip_contact);
467

468 469 470
    if (!oc->oc_rcontact) {
      outbound_connect_set_contact_by_aor(oc, sip->sip_to->a_url,
					  nh->nh_nua->nua_registrations);
471
      /* Try first time without contact if we are not natifying */
472
      oc->oc_add_contact = !oc->oc_prefs.natify;
473
      oc->oc_add_contact = 1;	/* Try always with contact */
474 475 476 477 478 479 480
    }

    if (terminating)
      /* Add Expires: 0 and remove expire parameter from contacts */
      unregister_expires_contacts(msg, sip);

    cr->cr_orq =
481 482 483
      nta_outgoing_mcreate(nua->nua_nta,
			   process_response_to_register, nh, NULL,
			   msg,
484 485 486 487
			   TAG_IF(oc->oc_add_contact,
				  SIPTAG_CONTACT(oc->oc_rcontact)),
			   TAG_IF(oc->oc_add_contact,
				  SIPTAG_CONTACT(oc->oc_previous)),
488 489 490
			   SIPTAG_END(),
			   TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
			   TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
491
			   TAG_NEXT(tags));
492 493

    if (cr->cr_orq)
494
      oc->oc_registering = 1;
495
  }
496 497 498 499

  if (!cr->cr_orq) {
    msg_destroy(msg);
    msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
500
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
501 502 503 504 505 506 507 508 509 510 511 512
  }

  cr->cr_usage = du;

  return cr->cr_event = e;
}

static void
restart_register(nua_handle_t *nh, tagi_t *tags)
{
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg;
513
  nua_dialog_usage_t *du = cr->cr_usage;
514
  struct outbound_connect *oc = nua_dialog_usage_private(du);
515
  int unregistering = du && du->du_terminating;
516
  sip_contact_t *contact = NULL, *previous = NULL;
517 518 519 520 521 522 523

  cr->cr_restart = NULL;

  if (!cr->cr_msg)
    return;

  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1,
524 525 526 527 528 529 530 531
		     SIP_METHOD_UNKNOWN,
		     TAG_NEXT(tags));

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

  if (unregistering)
    unregister_expires_contacts(msg, sip_object(msg));
532

533 534 535 536 537
  if (oc) {
    if (oc->oc_add_contact) {
      contact = oc->oc_rcontact;
      if (oc->oc_previous && oc->oc_previous->m_expires)
	previous = oc->oc_previous;
538 539
    }
  }
540

541 542 543 544 545
  cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta,
				    process_response_to_register, nh, NULL,
				    msg,
				    SIPTAG_CONTACT(contact),
				    SIPTAG_CONTACT(previous),
546 547
				    SIPTAG_END(), TAG_NEXT(tags));

548
  if (cr->cr_orq) {
549
    oc->oc_registering = 1;
550 551
  }
  else
552 553 554 555 556 557 558 559 560 561
    msg_destroy(msg);
}

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;
562
  struct outbound_connect *oc = nua_dialog_usage_private(du);
563 564 565 566 567
  int status;
  char const *phrase;
  sip_t *req = sip_object(cr->cr_msg);

  assert(sip);
568
  assert(du && du->du_class == nua_outbound_connect);
569 570 571 572 573 574
  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());

575 576
  nua_dialog_store_peer_info(nh, nh->nh_ds, sip);

577
  if (oc->oc_prefs.natify && status >= 200) {
578 579
    int reregister;

580
    reregister = outbound_connect_check_for_nat(oc, orq, sip);
581 582

    if (reregister < 0)
583
      SET_STATUS1(NUA_INTERNAL_ERROR);
584
    else if (reregister > 0) {
585 586 587
      msg_t *msg = msg_ref_create(cr->cr_msg);
      if (nua_creq_check_restart(nh, cr, orq, sip, restart_register)) {
	msg_destroy(msg);
588
	return 0;
589 590 591 592
      }

      assert(cr->cr_msg == NULL);
      cr->cr_msg = msg;
593

594
      if (reregister > 1) {
595
	/* We can try to reregister immediately */
596 597 598
	nua_creq_restart_with(nh, cr, orq, 100, "Updated Contact",
			      restart_register,
			      TAG_END());
599 600 601 602 603
      }
      else {
	nua_creq_save_restart(nh, cr, orq, 100, "Updated Contact",
			      restart_register);
      }
604

605 606 607
      return 0;
    }
  }
608

609 610 611 612 613 614
  if (status >= 300) {
    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register))
      return 0;
    du->du_ready = 0;
  }
  else if (status < 300) {
615 616
    du->du_ready = 1;

617
    if (!du->du_terminating && sip->sip_contact)
618
      oc->oc_registered = oc->oc_registering;
619
    else
620
      oc->oc_registered = 0;
621

622
    if (oc->oc_registered) {
623 624 625 626
      sip_time_t now = sip_now(), delta, mindelta;
      sip_contact_t const *m, *m0;

      /** Search for lowest delta of SIP contacts in sip->sip_contact */
627
      mindelta = SIP_TIME_MAX;
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

      for (m = sip->sip_contact; m; m = m->m_next) {
	if (m->m_url->url_type != url_sip)
	  continue;
	for (m0 = req->sip_contact; m0; m0 = m0->m_next)
	  if (url_cmp(m->m_url, m0->m_url) == 0) {
	    delta = sip_contact_expires(m, sip->sip_expires, sip->sip_date,
					3600, /* XXX */
					now);
	    if (delta > 0 && delta < mindelta)
	      mindelta = delta;
	    break;
	  }
      }

643 644 645
      if (mindelta == SIP_TIME_MAX)
	mindelta = 3600;

646 647
      nua_dialog_usage_set_refresh(du, mindelta);
      du->du_pending = refresh_register;
648 649 650 651 652 653
    }

    if (!du->du_terminating) {
#if HAVE_SIGCOMP
      struct sigcomp_compartment *cc;
      cc = nta_outgoing_compartment(orq);
654 655
      sigcomp_compartment_unref(oc->oc_compartment);
      oc->oc_compartment = cc;
656 657 658
#endif
    }
  }
659

660
  /*  RFC 3608 Section 6.1 Procedures at the UA
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

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

677 678
  */
  if (!du->du_terminating && status < 300) {
679 680
    su_free(nh->nh_home, oc->oc_route);
    oc->oc_route = sip_route_dup(nh->nh_home, sip->sip_service_route);
681 682
  }
  else {
683 684
    su_free(nh->nh_home, oc->oc_route);
    oc->oc_route = NULL;
685
  }
686

687 688 689 690 691
  /* RFC 3327 */
  /* We are mainly interested in the last part of the Path header */
  if (!du->du_terminating && status < 300) {
    sip_path_t *path = sip->sip_path;

692
    while (path && path->r_next)
693 694
      path = path->r_next;

695 696 697 698
    if (!oc->oc_path || !path ||
	url_cmp_all(oc->oc_path->r_url, path->r_url)) {
      su_free(nh->nh_home, oc->oc_path);
      oc->oc_path = sip_path_dup(nh->nh_home, path);
699 700 701
    }
  }

702
  if (!du->du_terminating && status < 300) {
703 704 705
    if (sip->sip_to->a_url->url_type == url_sips)
      oc->oc_secure = 1;

706
    if (!oc->oc_prev) {
707
      /* Add to the list of registrations */
708 709 710 711
      if ((oc->oc_next = nh->nh_nua->nua_registrations))
	oc->oc_next->oc_prev = &oc->oc_next;
      oc->oc_prev = &nh->nh_nua->nua_registrations;
      nh->nh_nua->nua_registrations = oc;
712 713 714
    }
  }

715 716 717 718 719
  if (!du->du_terminating && status < 300 && oc->oc_prefs.gruuize) {
    outbound_connect_gruuize(oc, sip);
  }


720 721
  if (!du->du_terminating && status < 300 && oc->oc_nat_detected)
    outbound_connect_start_keepalive(oc, 15, orq);
722
  else
723
    outbound_connect_stop_keepalive(oc);
724

725 726 727
  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
}

728
void
729 730 731 732
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;
733
  outbound_connect *oc = nua_dialog_usage_private(du);
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
  nua_event_t e;
  msg_t *msg;
  sip_t *sip;

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

  if (now > 0)
    e = nua_r_register;
  else
    e = nua_r_destroy, du->du_terminating = 1;

750
  outbound_connect_stop_keepalive(oc);
751

752 753 754 755 756 757 758 759
  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 (sip) {
760
    int unregistering = now == 0;
761
    sip_contact_t *contact = NULL, *previous = NULL;
762 763 764 765

    if (unregistering)
      unregister_expires_contacts(msg, sip);

766 767 768 769 770
    if (oc) {
      if (oc->oc_add_contact) {
	contact = oc->oc_rcontact;
	if (oc->oc_previous && oc->oc_previous->m_expires)
	  previous = oc->oc_previous;
771 772 773
      }
    }

774 775 776
    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				      process_response_to_register, nh, NULL,
				      msg,
777 778
				      SIPTAG_CONTACT(contact),
				      SIPTAG_CONTACT(previous),
779 780 781 782 783 784 785 786
				      SIPTAG_END(), TAG_NEXT(NULL));
  }

  if (!cr->cr_orq) {
    if (du->du_terminating)
      nua_dialog_usage_remove(nh, nh->nh_ds, du);
    msg_destroy(msg);
    msg_destroy(cr->cr_msg);
787
    UA_EVENT2(e, NUA_INTERNAL_ERROR, TAG_END());
788 789 790 791 792 793
    return;
  }

  cr->cr_usage = du;
  cr->cr_event = e;
}
794

795
/* ---------------------------------------------------------------------- */
796
/* Register usage interface */
797

798
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
799

800
int
Pekka Pessi's avatar
Pekka Pessi committed
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
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,
	  NUTAG_URL_REF(contact1),
	  NUTAG_SIPS_URL_REF(contact2),
	  NUTAG_CERTIFICATE_DIR_REF(certificate_dir),
	  TAG_END());

  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,
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0 &&
830
	nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
831 832 833 834 835
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;

836
    if (nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
			    TPTAG_IDENT("stun"),
			    TPTAG_PUBLIC(tport_type_stun), /* use stun */
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;
  }
  else if ((!contact1 ||
	    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)) {
    return -1;
  }

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

  return 0;
}

int
nua_stack_init_registrations(nua_t *nua)
864 865 866 867
{
  /* Create initial identities: peer-to-peer, public, sips */
  sip_via_t const *v;
  nua_handle_t *dnh = nua->nua_dhandle;
868

869 870
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
871
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 1);
872
  }
873

874 875
  v = nta_agent_via(nua->nua_nta);
  if (v) {
876
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
877
  }
878 879
  else {
    sip_via_t v[2];
880

881 882 883 884 885 886
    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.";
887

888
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
889 890
  }

891
  nta_agent_bind_tport_update(nua->nua_nta, nua,
892
			      nua_stack_tport_update);
893

894 895 896 897 898 899
  return 0;
}

static
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
{
900 901
  outbound_connect *default_oc;
  outbound_connect const *defaults = nua->nua_registrations;
902 903
  sip_via_t *via = nta_agent_via(nta);
  
904
  default_oc = outbound_connect_by_aor(defaults, NULL, 1);
905

906 907
  if (default_oc) {
    assert(default_oc->oc_via);
908

909
    outbound_connect_contacts_from_via(default_oc,
910 911 912 913 914 915 916
				     via,
				     via->v_next);

    /* refresh_register(nua_handle_t *nh, nua_dialog_usage_t *du, sip_time_t now); */
  }

  return;
917 918
}

919

920 921 922 923
sip_contact_t const *nua_contact_by_aor(nua_t *nua,
					url_t const *aor,
					int only_default)
{
924
  outbound_connect *oc = nua->nua_registrations;
925

926
  oc = outbound_connect_by_aor(oc, aor, only_default);
927

928
  return outbound_connect_contact(oc);
929 930
}

Pekka Pessi's avatar
Pekka Pessi committed
931
/** @internal Return a string descibing our features. */
932 933 934 935 936 937 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 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
static
char *nua_stack_register_features(nua_handle_t *nh)
{
  char *retval;
  su_strlst_t *l = su_strlst_create(NULL);
  su_home_t *home = su_strlst_home(l);

  if (!l)
    return NULL;

  if (NH_PGET(nh, instance))
    su_slprintf(l, ";+sip.instance=\"<%s>\"", NH_PGET(nh, instance));

  if (NH_PGET(nh, callee_caps)) {
    sip_allow_t const *allow = NH_PGET(nh, allow);

    if (allow) {
      su_strlst_append(l, ";methods=\"");
      if (allow->k_items) {
	int i;
	for (i = 0; allow->k_items[i]; i++) {
	  su_strlst_append(l, allow->k_items[i]);
	  if (allow->k_items[i + 1])
	    su_strlst_append(l, ",");
	}
      }
      su_strlst_append(l, "\"");
    }

    if (nh->nh_soa) {
      char **media = soa_media_features(nh->nh_soa, 0, home);

      while (*media) {
	su_strlst_append(l, ";");
	su_strlst_append(l, *media++);
      }
    }
  }

  retval = su_strlst_join(l, nh->nh_home, "");

  su_strlst_destroy(l);

  return retval;
}

Pekka Pessi's avatar
Pekka Pessi committed
978 979 980 981 982
/**@internal
 * Fix contacts for un-REGISTER.
 *
 * Remove (possible non-zero) "expires" parameters from contacts and extra
 * contacts, add Expire: 0.
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
 */
static
void unregister_expires_contacts(msg_t *msg, sip_t *sip)
{
  sip_contact_t *m;
  int unregister_all;

  /* Remove payload */
  while (sip->sip_payload)
    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_payload);
  while (sip->sip_content_type)
    sip_header_remove(msg, sip, (sip_header_t *)sip->sip_content_type);

  for (m = sip->sip_contact; m; m = m->m_next) {
    if (m->m_url->url_type == url_any)
      break;
    msg_header_remove_param(m->m_common, "expires");
#if 0
    msg_header_add_param(msg_home(msg), m->m_common, "expires=0");
#endif
  }

  unregister_all = m && (m != sip->sip_contact || m->m_next);

  sip_add_tl(msg, sip,
	     /* Remove existing contacts */
	     TAG_IF(unregister_all, SIPTAG_CONTACT(NONE)),
	     /* Add '*' contact: 0 */
	     TAG_IF(unregister_all, SIPTAG_CONTACT_STR("*")),
	     SIPTAG_EXPIRES_STR("0"),
	     TAG_END());
}


Pekka Pessi's avatar
Pekka Pessi committed
1017
/** @internal Callback from outbound_connect */
1018
static int nua_stack_register_status(nua_handle_t *nh, outbound_connect *oc,
1019 1020 1021 1022 1023 1024 1025
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;

  ta_start(ta, tag, value);

1026 1027
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1028 1029 1030 1031 1032 1033 1034
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1035
/** @internal Callback from outbound_connect */
1036
static int nua_stack_register_failed(nua_handle_t *nh, outbound_connect *oc,
1037 1038 1039 1040 1041 1042
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  ta_start(ta, tag, value);

1043 1044
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

/* ====================================================================== */
/* Register-usage side */

static
Pekka Pessi's avatar
Pekka Pessi committed
1056
int outbound_connect_nat_detect(outbound_connect *oc, sip_t const *);
1057 1058 1059

/* ---------------------------------------------------------------------- */

Pekka Pessi's avatar
Pekka Pessi committed
1060
/** @internal Check if there is a NAT between us and registrar */
1061
int outbound_connect_check_for_nat(struct outbound_connect *oc,
Pekka Pessi's avatar
Pekka Pessi committed
1062 1063
				   nta_outgoing_t *orq,
				   sip_t const *sip)
1064 1065
{
  int binding_changed;
1066
  sip_contact_t *m = oc->oc_rcontact;
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082

#if 0
  if (host_is_domain(v->v_host)) {
    /*
     * If we use domain name in Via, we assume that application
     * knows something we don't.
     * Just use ordinary contact unless domain name ends with ".invalid"
     */
    char const *invalid = strcasestr(v->v_host, ".invalid");

    if (invalid)
      invalid += (sizeof ".invalid") - 1;
    if (invalid && invalid[0] == '.') /* ... or .invalid. */
      invalid++;

    if (!invalid || invalid[0] != '\0') {
1083
      if (!oc->oc_rcontact)
1084
	...
1085
      if (!oc->oc_rcontact)
1086 1087 1088 1089 1090 1091
	return -1;
      return 0;
    }
  }
#endif

1092
  binding_changed = outbound_connect_nat_detect(oc, sip);
1093 1094

  /* Contact was set by application, do not change it */
1095
  if (oc->oc_by_application)
1096 1097
    return 0;

1098 1099
  if (!oc->oc_nat_detected) {
    if (oc->oc_add_contact)