nua_register.c 56.6 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
sip_route_t const *outbound_connect_route(outbound_connect const *ru);

129 130
char const * const outbound_connect_content_type;
nua_usage_class const *nua_outbound_connect;
131

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

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

196
  unsigned :0;
197

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  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 */
220

221
#if HAVE_SIGCOMP
222
  struct sigcomp_compartment *oc_compartment;
223 224
#endif
};
225

226 227 228
/* ======================================================================== */
/* REGISTER */

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

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

236 237
static void unregister_expires_contacts(msg_t *msg, sip_t *sip);

238
static char *nua_stack_register_features(nua_handle_t *nh);
239

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

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

248
outbound_owner_vtable nua_stack_register_callbacks = {
249 250 251 252 253 254
    sizeof nua_stack_register_callbacks,
    nua_stack_register_status,
    nua_stack_register_failed,
    nua_stack_register_failed,
  };

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


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

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

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

438
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_outbound_connect, NULL);
439
  if (!du)
440
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
441 442 443 444 445
  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));
446

447
  outbound_connect_set_features(oc, nua_stack_register_features(nh));
448

449
  outbound_connect_stop_keepalive(oc);
450

451 452
  if (du->du_msg)
    cr->cr_msg = msg_ref_create(du->du_msg);
453

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

460 461
  if (sip) {
    du->du_terminating = terminating;
462

463 464 465 466
    if (du->du_msg)
      msg_destroy(du->du_msg);
    du->du_msg = msg_ref_create(cr->cr_msg);

467
    if (sip->sip_contact)
468
      outbound_connect_set_contact(oc, sip->sip_contact);
469

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

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

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

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

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

  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;
515
  nua_dialog_usage_t *du = cr->cr_usage;
516
  struct outbound_connect *oc = nua_dialog_usage_private(du);
517
  int unregistering = du && du->du_terminating;
518
  sip_contact_t *contact = NULL, *previous = NULL;
519 520 521 522 523 524 525

  cr->cr_restart = NULL;

  if (!cr->cr_msg)
    return;

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

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

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

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

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

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

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

577 578
  nua_dialog_store_peer_info(nh, nh->nh_ds, sip);

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

582
    reregister = outbound_connect_check_for_nat(oc, orq, sip);
583 584

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

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

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

607 608 609
      return 0;
    }
  }
610

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

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

624
    if (oc->oc_registered) {
625 626 627 628
      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 */
629
      mindelta = SIP_TIME_MAX;
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

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

645 646 647
      if (mindelta == SIP_TIME_MAX)
	mindelta = 3600;

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

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

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

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

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

689 690 691 692 693
  /* 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;

694
    while (path && path->r_next)
695 696
      path = path->r_next;

697 698 699 700
    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);
701 702 703
    }
  }

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

708
    if (!oc->oc_prev) {
709
      /* Add to the list of registrations */
710 711 712 713
      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;
714 715 716
    }
  }

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


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

727 728 729
  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
}

730
void
731 732 733 734
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;
735
  outbound_connect *oc = nua_dialog_usage_private(du);
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
  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;

752
  outbound_connect_stop_keepalive(oc);
753

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

    if (unregistering)
      unregister_expires_contacts(msg, sip);

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

776 777 778
    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				      process_response_to_register, nh, NULL,
				      msg,
779 780
				      SIPTAG_CONTACT(contact),
				      SIPTAG_CONTACT(previous),
781 782 783 784 785 786 787 788
				      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);
789
    UA_EVENT2(e, NUA_INTERNAL_ERROR, TAG_END());
790 791 792 793 794 795
    return;
  }

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

797
/* ---------------------------------------------------------------------- */
798
/* Register usage interface */
799

800 801 802 803
#if HAVE_SOFIA_STUN
#include <sofia-sip/stun.h>
#endif

804
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
805

806
int
Pekka Pessi's avatar
Pekka Pessi committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
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 &&
836
	nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
837 838 839 840 841
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;

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

Pekka Pessi's avatar
Pekka Pessi committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  }
  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)
876 877 878 879
{
  /* Create initial identities: peer-to-peer, public, sips */
  sip_via_t const *v;
  nua_handle_t *dnh = nua->nua_dhandle;
880

881 882
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
883
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 1);
884
  }
885

886 887
  v = nta_agent_via(nua->nua_nta);
  if (v) {
888
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
889
  }
890 891
  else {
    sip_via_t v[2];
892

893 894 895 896 897 898
    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.";
899

900
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
901 902
  }

903
  nta_agent_bind_tport_update(nua->nua_nta, nua,
904
			      nua_stack_tport_update);
905

906 907 908 909 910 911
  return 0;
}

static
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
{
912 913
  outbound_connect *default_oc;
  outbound_connect const *defaults = nua->nua_registrations;
914 915
  sip_via_t *via = nta_agent_via(nta);
  
916
  default_oc = outbound_connect_by_aor(defaults, NULL, 1);
917

918 919
  if (default_oc) {
    assert(default_oc->oc_via);
920

921
    outbound_connect_contacts_from_via(default_oc,
922 923 924 925 926 927 928
				     via,
				     via->v_next);

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

  return;
929 930
}

931

932 933 934 935
sip_contact_t const *nua_contact_by_aor(nua_t *nua,
					url_t const *aor,
					int only_default)
{
936
  outbound_connect *oc = nua->nua_registrations;
937

938
  oc = outbound_connect_by_aor(oc, aor, only_default);
939

940
  return outbound_connect_contact(oc);
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
/** Add a Contact (and Route) header to initial request */
int nua_add_contact_by_aor(nua_handle_t *nh,
			   url_t const *aor,
			   msg_t *msg, 
			   sip_t *sip,
			   int add_contact,
			   int add_service_route)
{
  outbound_connect *oc;

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

  oc = outbound_connect_by_aor(nh->nh_nua->nua_registrations, aor, 0);

  if (oc == NULL)
    return -1;

  if (add_contact) {
    sip_contact_t const *m = outbound_connect_contact(oc);
    if (msg_header_add_dup(msg, (msg_pub_t *)sip, (void const *)m) < 0)
      return -1;
  }

  if (add_service_route) {
    sip_route_t const *sr = outbound_connect_route(oc);
    if (msg_header_add_dup(msg, (msg_pub_t *)sip, (void const *)sr) < 0)
      return -1;
  }

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
976
/** @internal Return a string descibing our features. */
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 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
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
1023 1024 1025 1026 1027
/**@internal
 * Fix contacts for un-REGISTER.
 *
 * Remove (possible non-zero) "expires" parameters from contacts and extra
 * contacts, add Expire: 0.
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
 */
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
1062
/** @internal Callback from outbound_connect */
1063
static int nua_stack_register_status(nua_handle_t *nh, outbound_connect *oc,
1064 1065 1066 1067 1068 1069 1070
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;

  ta_start(ta, tag, value);

1071 1072
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1073 1074 1075 1076 1077 1078 1079
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1080
/** @internal Callback from outbound_connect */
1081
static int nua_stack_register_failed(nua_handle_t *nh, outbound_connect *oc,
1082 1083 1084 1085 1086 1087
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  ta_start(ta, tag, value);

1088 1089
  nua_stack_event(nh->nh_nua, nh, NULL,
		  nua_i_outbound, status, phrase,
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
		  ta_tags(ta));

  ta_end(ta);

  return 0;
}

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

static
Pekka Pessi's avatar
Pekka Pessi committed
1101
int outbound_connect_nat_detect(outbound_connect *oc, sip_t const *);
1102 1103 1104

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

Pekka Pessi's avatar
Pekka Pessi committed
1105
/** @internal Check if there is a NAT between us and registrar */
1106
int outbound_connect_check_for_nat(struct outbound_connect *oc,
Pekka Pessi's avatar
Pekka Pessi committed
1107 1108
				   nta_outgoing_t *orq,
				   sip_t const *sip)
1109 1110
{
  int binding_changed;
1111
  sip_contact_t *m = oc->oc_rcontact;
1112 1113 1114 1115 1116 1117