nua_register.c 53.8 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
void outbound_connect_start_keepalive(struct outbound_connect *ru,
112 113
				    unsigned interval,
				    nta_outgoing_t *register_trans);
114

115
void outbound_connect_stop_keepalive(struct outbound_connect *ru);
116

117
int outbound_connect_check_accept(sip_accept_t const *accept);
118

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

123
sip_contact_t const *outbound_connect_contact(outbound_connect const *ru);
124

125 126
char const * const outbound_connect_content_type;
nua_usage_class const *nua_outbound_connect;
127

128
struct outbound_owner_vtable
129
{
130 131
  int oo_size;
  int (*oo_status)(nua_owner_t *, outbound_connect *ru,
132 133
		   int status, char const *phrase,
		   tag_type_t tag, tag_value_t value, ...);
134 135 136 137 138 139
  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, ...);
140
};
141

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

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

192
  unsigned :0;
193

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
  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 */
216

217
#if HAVE_SIGCOMP
218
  struct sigcomp_compartment *oc_compartment;
219 220
#endif
};
221

222 223 224
/* ======================================================================== */
/* REGISTER */

225 226
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);
227 228 229 230 231

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

232 233
static void unregister_expires_contacts(msg_t *msg, sip_t *sip);

234
static char *nua_stack_register_features(nua_handle_t *nh);
235

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

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

244
outbound_owner_vtable nua_stack_register_callbacks = {
245 246 247 248 249 250
    sizeof nua_stack_register_callbacks,
    nua_stack_register_status,
    nua_stack_register_failed,
    nua_stack_register_failed,
  };

Pekka Pessi's avatar
Pekka Pessi committed
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 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
/**@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
 */


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

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

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

434
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_outbound_connect, NULL);
435
  if (!du)
436
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
437 438 439 440 441
  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));
442

443
  outbound_connect_set_features(oc, nua_stack_register_features(nh));
444

445
  outbound_connect_stop_keepalive(oc);
446

447 448
  if (du->du_msg)
    cr->cr_msg = msg_ref_create(du->du_msg);
449

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

456 457
  if (sip) {
    du->du_terminating = terminating;
458

459 460 461 462
    if (du->du_msg)
      msg_destroy(du->du_msg);
    du->du_msg = msg_ref_create(cr->cr_msg);

463
    if (sip->sip_contact)
464
      outbound_connect_set_contact(oc, sip->sip_contact);
465

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

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

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

    if (cr->cr_orq)
491
      oc->oc_registering = 1;
492
  }
493 494 495 496

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

  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;
510
  nua_dialog_usage_t *du = cr->cr_usage;
511
  struct outbound_connect *oc = nua_dialog_usage_private(du);
512
  int unregistering = du && du->du_terminating;
513
  sip_contact_t *contact = NULL, *previous = NULL;
514 515 516 517 518 519 520

  cr->cr_restart = NULL;

  if (!cr->cr_msg)
    return;

  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1,
521 522 523 524 525 526 527 528
		     SIP_METHOD_UNKNOWN,
		     TAG_NEXT(tags));

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

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

530 531 532 533 534
  if (oc) {
    if (oc->oc_add_contact) {
      contact = oc->oc_rcontact;
      if (oc->oc_previous && oc->oc_previous->m_expires)
	previous = oc->oc_previous;
535 536
    }
  }
537

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

545
  if (cr->cr_orq) {
546
    oc->oc_registering = 1;
547 548
  }
  else
549 550 551 552 553 554 555 556 557 558
    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;
559
  struct outbound_connect *oc = nua_dialog_usage_private(du);
560 561 562 563 564
  int status;
  char const *phrase;
  sip_t *req = sip_object(cr->cr_msg);

  assert(sip);
565
  assert(du && du->du_class == nua_outbound_connect);
566 567 568 569 570 571
  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());

572 573
  nua_dialog_store_peer_info(nh, nh->nh_ds, sip);

574
  if (oc->oc_prefs.natify && status >= 200) {
575 576
    int reregister;

577
    reregister = outbound_connect_check_for_nat(oc, orq, sip);
578 579

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

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

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

602 603 604
      return 0;
    }
  }
605

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

614
    if (!du->du_terminating && sip->sip_contact)
615
      oc->oc_registered = oc->oc_registering;
616
    else
617
      oc->oc_registered = 0;
618

619
    if (oc->oc_registered) {
620 621 622 623
      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 */
624
      mindelta = SIP_TIME_MAX;
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639

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

640 641 642
      if (mindelta == SIP_TIME_MAX)
	mindelta = 3600;

643 644
      nua_dialog_usage_set_refresh(du, mindelta);
      du->du_pending = refresh_register;
645 646 647 648 649 650
    }

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

657
  /*  RFC 3608 Section 6.1 Procedures at the UA
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

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

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

684 685 686 687 688
  /* 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;

689
    while (path && path->r_next)
690 691
      path = path->r_next;

692 693 694 695
    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);
696 697 698
    }
  }

699
  if (!du->du_terminating && status < 300) {
700
    if (!oc->oc_prev) {
701
      /* Add to the list of registrations */
702 703 704 705
      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;
706 707 708
    }
  }

709 710
  if (!du->du_terminating && status < 300 && oc->oc_nat_detected)
    outbound_connect_start_keepalive(oc, 15, orq);
711
  else
712
    outbound_connect_stop_keepalive(oc);
713

714 715 716
  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
}

717
void
718 719 720 721
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;
722
  outbound_connect *oc = nua_dialog_usage_private(du);
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
  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;

739
  outbound_connect_stop_keepalive(oc);
740

741 742 743 744 745 746 747 748
  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) {
749
    int unregistering = now == 0;
750
    sip_contact_t *contact = NULL, *previous = NULL;
751 752 753 754

    if (unregistering)
      unregister_expires_contacts(msg, sip);

755 756 757 758 759
    if (oc) {
      if (oc->oc_add_contact) {
	contact = oc->oc_rcontact;
	if (oc->oc_previous && oc->oc_previous->m_expires)
	  previous = oc->oc_previous;
760 761 762
      }
    }

763 764 765
    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				      process_response_to_register, nh, NULL,
				      msg,
766 767
				      SIPTAG_CONTACT(contact),
				      SIPTAG_CONTACT(previous),
768 769 770 771 772 773 774 775
				      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);
776
    UA_EVENT2(e, NUA_INTERNAL_ERROR, TAG_END());
777 778 779 780 781 782
    return;
  }

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

784
/* ---------------------------------------------------------------------- */
785
/* Register usage interface */
786

787
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
788

789
int
Pekka Pessi's avatar
Pekka Pessi committed
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
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 &&
819
	nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
820 821 822 823 824
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;

825
    if (nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
			    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)
853 854 855 856
{
  /* Create initial identities: peer-to-peer, public, sips */
  sip_via_t const *v;
  nua_handle_t *dnh = nua->nua_dhandle;
857

858 859
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
860
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 1);
861
  }
862

863 864
  v = nta_agent_via(nua->nua_nta);
  if (v) {
865
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
866
  }
867 868
  else {
    sip_via_t v[2];
869

870 871 872 873 874 875
    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.";
876

877
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
878 879
  }

880
  nta_agent_bind_tport_update(nua->nua_nta, nua,
881
			      nua_stack_tport_update);
882

883 884 885 886 887 888
  return 0;
}

static
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
{
889 890
  outbound_connect *default_oc;
  outbound_connect const *defaults = nua->nua_registrations;
891 892
  sip_via_t *via = nta_agent_via(nta);
  
893
  default_oc = outbound_connect_by_aor(defaults, NULL, 1);
894

895 896
  if (default_oc) {
    assert(default_oc->oc_via);
897

898
    outbound_connect_contacts_from_via(default_oc,
899 900 901 902 903 904 905
				     via,
				     via->v_next);

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

  return;
906 907
}

908

909 910 911 912
sip_contact_t const *nua_contact_by_aor(nua_t *nua,
					url_t const *aor,
					int only_default)
{
913
  outbound_connect *oc = nua->nua_registrations;
914

915
  oc = outbound_connect_by_aor(oc, aor, only_default);
916

917
  return outbound_connect_contact(oc);
918 919
}

Pekka Pessi's avatar
Pekka Pessi committed
920
/** @internal Return a string descibing our features. */
921 922 923 924 925 926 927 928 929 930 931 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
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
967 968 969 970 971
/**@internal
 * Fix contacts for un-REGISTER.
 *
 * Remove (possible non-zero) "expires" parameters from contacts and extra
 * contacts, add Expire: 0.
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
 */
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
1006
/** @internal Callback from outbound_connect */
1007
static int nua_stack_register_status(nua_handle_t *nh, outbound_connect *oc,
1008 1009 1010 1011 1012 1013 1014
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;

  ta_start(ta, tag, value);

1015 1016
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1017 1018 1019 1020 1021 1022 1023
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1024
/** @internal Callback from outbound_connect */
1025
static int nua_stack_register_failed(nua_handle_t *nh, outbound_connect *oc,
1026 1027 1028 1029 1030 1031
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  ta_start(ta, tag, value);

1032 1033
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

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

static
Pekka Pessi's avatar
Pekka Pessi committed
1045
int outbound_connect_nat_detect(outbound_connect *oc, sip_t const *);
1046 1047 1048

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

Pekka Pessi's avatar
Pekka Pessi committed
1049
/** @internal Check if there is a NAT between us and registrar */
1050
int outbound_connect_check_for_nat(struct outbound_connect *oc,
Pekka Pessi's avatar
Pekka Pessi committed
1051 1052
				   nta_outgoing_t *orq,
				   sip_t const *sip)
1053 1054
{
  int binding_changed;
1055
  sip_contact_t *m = oc->oc_rcontact;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

#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') {
1072
      if (!oc->oc_rcontact)
1073
	...
1074
      if (!oc->oc_rcontact)
1075 1076 1077 1078 1079 1080
	return -1;
      return 0;
    }
  }
#endif

1081
  binding_changed = outbound_connect_nat_detect(oc, sip);
1082 1083

  /* Contact was set by application, do not change it */
1084
  if (oc->oc_by_application)
1085 1086
    return 0;

1087 1088
  if (!oc->oc_nat_detected) {
    if (oc->oc_add_contact)
1089
      return 0;
1090
    oc->oc_add_contact = 1;
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    return 2;
  }

  /* We have detected NAT. Now, what to do?
   * 1) do nothing - register as usual and let proxy take care of it?
   * 2) try to detect our public nat binding and use it
   * 2A) use public vias from nta generated by STUN or UPnP
   * 2B) use SIP Via header
   */

  /* Do we have to ask for reregistration */
  if (!m || binding_changed > 1) {