nua_register.c 59.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>
54
#include <sofia-sip/tport.h>
Pekka Pessi's avatar
Pekka Pessi committed
55
#include <sofia-sip/tport_tag.h>
56 57 58 59 60

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

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

#include <assert.h>

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

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,
82 83 84
			  char const *options,
			  unsigned dgram_interval,
			  unsigned stream_interval);
85

86 87 88 89
int outbound_connect_set_options(outbound_connect *oc,
				 char const *options,
				 unsigned dgram_interval,
				 unsigned stream_interval);
90

91
int outbound_connect_set_features(outbound_connect *ru, char *features);
92

93
int outbound_connect_check_for_nat(struct outbound_connect *ru,
94 95 96
				 nta_outgoing_t *orq,
				 sip_t const *sip);

97
int outbound_connect_contacts_from_via(outbound_connect *ru,
98 99 100
				     sip_via_t const *via,
				     sip_via_t const *pair);

101
int outbound_connect_set_contact(struct outbound_connect *ru,
102 103
			       sip_contact_t *m);

104
int outbound_connects_from_via(struct outbound_connect **list,
105 106 107 108
			     nua_owner_t *owner,
			     sip_via_t const *via,
			     int public);

109
int outbound_connect_set_contact_by_aor(struct outbound_connect *ru,
110
				      url_t const *aor,
111
				      outbound_connect const *defaults);
112

113
outbound_connect *outbound_connect_by_aor(outbound_connect const *usages,
114 115 116
				      url_t const *aor,
				      int only_default);

117 118
int outbound_connect_gruuize(struct outbound_connect *oc, sip_t const *sip);

119
void outbound_connect_start_keepalive(struct outbound_connect *ru,
120 121
				      unsigned interval,
				      nta_outgoing_t *register_trans);
122

123
void outbound_connect_stop_keepalive(struct outbound_connect *ru);
124

125
int outbound_connect_check_accept(sip_accept_t const *accept);
126

127 128 129
int outbound_connect_process_options(struct outbound_connect *usages,
				     nta_incoming_t *irq,
				     sip_t const *sip);
130

131
sip_contact_t const *outbound_connect_contact(outbound_connect const *ru);
132

133 134
sip_route_t const *outbound_connect_route(outbound_connect const *ru);

135 136
char const * const outbound_connect_content_type;
nua_usage_class const *nua_outbound_connect;
137

138
struct outbound_owner_vtable
139
{
140 141
  int oo_size;
  int (*oo_status)(nua_owner_t *, outbound_connect *ru,
142 143
		   int status, char const *phrase,
		   tag_type_t tag, tag_value_t value, ...);
144 145 146 147 148 149
  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, ...);
150 151 152 153 154 155 156 157
  int (*oo_credentials)(nua_owner_t *, auth_client_t **auc);
};

enum outbound_feature {
  outbound_feature_unsupported = 0,
  outbound_feature_unsure = 1,
  outbound_feature_supported = 2,
  outbound_feature_required = 3
158
};
159

160 161 162 163 164 165 166 167 168 169 170 171 172
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 {
173 174
    unsigned dgram_interval;	/**< Default keepalive interval for datagram */
    unsigned stream_interval;	/**< Default keepalive interval for streams */
175 176 177 178 179 180 181 182 183 184 185 186 187 188
    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 {
189 190
    /* See enum outbound_feature: */
    /* 0 do not support, 1 - perhaps supports, 2 - supports, 3 - requires */
191 192 193 194 195 196
    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;
197

198
  /* The registration state machine. */
Pekka Pessi's avatar
Pekka Pessi committed
199
  /** Initial REGISTER containing oc_rcontact has been sent */
200
  unsigned oc_registering:1;
Pekka Pessi's avatar
Pekka Pessi committed
201
  /** 2XX response to REGISTER containg oc_rcontact has been received */
202
  unsigned oc_registered:1;
Pekka Pessi's avatar
Pekka Pessi committed
203 204
  /**The registration has been validated:
   * We have successfully sent OPTIONS to ourselves.
205
   */
206
  unsigned oc_validated:1;
Pekka Pessi's avatar
Pekka Pessi committed
207
  /** The registration has been validated once.
208 209 210
   *   We have successfully sent OPTIONS to ourselves, so do not give
   *   up if OPTIONS probe fails.
   */
211
  unsigned oc_once_validated:1;
212

213
  unsigned :0;
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  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 */
237
  auth_client_t *oc_auc[1];	/**< Authenticator for OPTIONS */
238

239
#if HAVE_SIGCOMP
240
  struct sigcomp_compartment *oc_compartment;
241 242
#endif
};
243

244 245 246
/* ======================================================================== */
/* REGISTER */

247 248
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);
249 250 251 252 253

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

254 255
static void unregister_expires_contacts(msg_t *msg, sip_t *sip);

256
static char *nua_stack_register_features(nua_handle_t *nh);
257

258
static int nua_stack_register_status(nua_handle_t *, outbound_connect *oc,
259 260 261
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

262
static int nua_stack_register_failed(nua_handle_t *, outbound_connect *oc,
263 264 265
				     int status, char const *phrase,
				     tag_type_t tag, tag_value_t value, ...);

266 267
static int nua_stack_register_credentials(nua_handle_t *, auth_client_t **auc);

268
outbound_owner_vtable nua_stack_register_callbacks = {
269 270 271 272
    sizeof nua_stack_register_callbacks,
    nua_stack_register_status,
    nua_stack_register_failed,
    nua_stack_register_failed,
273
    nua_stack_register_credentials
274 275
  };

Pekka Pessi's avatar
Pekka Pessi committed
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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
/**@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
 */


440
int
441 442
nua_stack_register(nua_t *nua, nua_handle_t *nh, nua_event_t e,
		   tagi_t const *tags)
443 444
{
  nua_dialog_usage_t *du;
445
  struct outbound_connect *oc = NULL;
446 447 448
  struct nua_client_request *cr = nh->nh_cr;
  msg_t *msg = NULL;
  sip_t *sip;
449
  int terminating = e != nua_r_register;
450 451

  if (nh->nh_special && nh->nh_special != nua_r_register)
452
    return UA_EVENT2(e, 900, "Invalid handle for REGISTER");
453
  if (cr->cr_orq)
454
    return UA_EVENT2(e, 900, "Request already in progress");
455

456
  nua_stack_init_handle(nua, nh, nh_has_register, "", TAG_NEXT(tags));
457
  nh->nh_special = nua_r_register;
458

459
  du = nua_dialog_usage_add(nh, nh->nh_ds, nua_outbound_connect, NULL);
460
  if (!du)
461
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
462 463 464 465
  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,
466 467 468 469 470
			NH_PGET(nh, outbound),
			NH_PGET(nh, keepalive),
			NH_PISSET(nh, keepalive_stream) ?
			NH_PGET(nh, keepalive_stream) : 
			NH_PGET(nh, keepalive));
471

472
  outbound_connect_set_features(oc, nua_stack_register_features(nh));
473

474
  outbound_connect_stop_keepalive(oc);
475

476 477
  if (du->du_msg)
    cr->cr_msg = msg_ref_create(du->du_msg);
478

479
  msg = nua_creq_msg(nua, nh, cr, cr->cr_msg != NULL,
480
		     SIP_METHOD_REGISTER,
481
		     TAG_IF(!terminating, NUTAG_USE_DIALOG(1)),
482 483 484
		     TAG_NEXT(tags));
  sip = sip_object(msg);

485 486
  if (sip) {
    du->du_terminating = terminating;
487

488 489 490 491
    if (du->du_msg)
      msg_destroy(du->du_msg);
    du->du_msg = msg_ref_create(cr->cr_msg);

492
    if (sip->sip_contact)
493
      outbound_connect_set_contact(oc, sip->sip_contact);
494

495 496 497
    if (!oc->oc_rcontact) {
      outbound_connect_set_contact_by_aor(oc, sip->sip_to->a_url,
					  nh->nh_nua->nua_registrations);
498
      /* Try first time without contact if we are not natifying */
499
      oc->oc_add_contact = !oc->oc_prefs.natify;
500
      oc->oc_add_contact = 1;	/* Try always with contact */
501 502 503 504 505 506 507
    }

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

    cr->cr_orq =
508 509 510
      nta_outgoing_mcreate(nua->nua_nta,
			   process_response_to_register, nh, NULL,
			   msg,
511 512 513 514
			   TAG_IF(oc->oc_add_contact,
				  SIPTAG_CONTACT(oc->oc_rcontact)),
			   TAG_IF(oc->oc_add_contact,
				  SIPTAG_CONTACT(oc->oc_previous)),
515 516 517
			   SIPTAG_END(),
			   TAG_IF(terminating, NTATAG_SIGCOMP_CLOSE(1)),
			   TAG_IF(!terminating, NTATAG_COMP("sigcomp")),
518
			   TAG_NEXT(tags));
519 520

    if (cr->cr_orq)
521
      oc->oc_registering = 1;
522
  }
523 524 525 526

  if (!cr->cr_orq) {
    msg_destroy(msg);
    msg_destroy(cr->cr_msg), cr->cr_msg = NULL;
527
    nua_dialog_usage_remove(nh, nh->nh_ds, du);    
528
    return UA_EVENT1(e, NUA_INTERNAL_ERROR);
529 530 531 532 533 534 535 536 537 538 539 540
  }

  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;
541
  nua_dialog_usage_t *du = cr->cr_usage;
542
  struct outbound_connect *oc = nua_dialog_usage_private(du);
543
  int unregistering = du && du->du_terminating;
544
  sip_contact_t *contact = NULL, *previous = NULL;
545 546 547 548 549 550 551

  cr->cr_restart = NULL;

  if (!cr->cr_msg)
    return;

  msg = nua_creq_msg(nh->nh_nua, nh, cr, 1,
552 553 554 555 556 557 558 559
		     SIP_METHOD_UNKNOWN,
		     TAG_NEXT(tags));

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

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

561 562 563 564 565
  if (oc) {
    if (oc->oc_add_contact) {
      contact = oc->oc_rcontact;
      if (oc->oc_previous && oc->oc_previous->m_expires)
	previous = oc->oc_previous;
566 567
    }
  }
568

569 570 571 572 573
  cr->cr_orq = nta_outgoing_mcreate(nh->nh_nua->nua_nta,
				    process_response_to_register, nh, NULL,
				    msg,
				    SIPTAG_CONTACT(contact),
				    SIPTAG_CONTACT(previous),
574 575
				    SIPTAG_END(), TAG_NEXT(tags));

576
  if (cr->cr_orq) {
577
    oc->oc_registering = 1;
578 579
  }
  else
580 581 582 583 584 585 586 587 588 589
    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;
590
  struct outbound_connect *oc = nua_dialog_usage_private(du);
591 592 593 594 595
  int status;
  char const *phrase;
  sip_t *req = sip_object(cr->cr_msg);

  assert(sip);
596
  assert(du && du->du_class == nua_outbound_connect);
597 598 599 600 601 602
  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());

603 604
  if (!du->du_terminating)
    nua_dialog_store_peer_info(nh, nh->nh_ds, sip);
605

606
  if (!du->du_terminating && oc->oc_prefs.natify && status >= 200) {
607 608
    int reregister;

609
    reregister = outbound_connect_check_for_nat(oc, orq, sip);
610 611

    if (reregister < 0)
612
      SET_STATUS1(NUA_INTERNAL_ERROR);
613
    else if (reregister > 0) {
614 615 616
      msg_t *msg = msg_ref_create(cr->cr_msg);
      if (nua_creq_check_restart(nh, cr, orq, sip, restart_register)) {
	msg_destroy(msg);
617
	return 0;
618 619 620 621
      }

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

623
      if (reregister > 1) {
624
	/* We can try to reregister immediately */
625 626 627
	nua_creq_restart_with(nh, cr, orq, 100, "Updated Contact",
			      restart_register,
			      TAG_END());
628 629 630 631 632
      }
      else {
	nua_creq_save_restart(nh, cr, orq, 100, "Updated Contact",
			      restart_register);
      }
633

634 635 636
      return 0;
    }
  }
637

638 639 640 641 642 643
  if (status >= 300) {
    if (nua_creq_check_restart(nh, cr, orq, sip, restart_register))
      return 0;
    du->du_ready = 0;
  }
  else if (status < 300) {
644 645
    du->du_ready = 1;

646
    if (!du->du_terminating && sip->sip_contact)
647
      oc->oc_registered = oc->oc_registering;
648
    else
649
      oc->oc_registered = 0;
650

651
    if (oc->oc_registered) {
652 653 654 655
      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 */
656
      mindelta = SIP_TIME_MAX;
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

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

672 673 674
      if (mindelta == SIP_TIME_MAX)
	mindelta = 3600;

675 676
      nua_dialog_usage_set_refresh(du, mindelta);
      du->du_pending = refresh_register;
677 678 679 680 681 682
    }

    if (!du->du_terminating) {
#if HAVE_SIGCOMP
      struct sigcomp_compartment *cc;
      cc = nta_outgoing_compartment(orq);
683 684
      sigcomp_compartment_unref(oc->oc_compartment);
      oc->oc_compartment = cc;
685 686 687
#endif
    }
  }
688

689
  /*  RFC 3608 Section 6.1 Procedures at the UA
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

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

706 707
  */
  if (!du->du_terminating && status < 300) {
708 709
    su_free(nh->nh_home, oc->oc_route);
    oc->oc_route = sip_route_dup(nh->nh_home, sip->sip_service_route);
710 711
  }
  else {
712 713
    su_free(nh->nh_home, oc->oc_route);
    oc->oc_route = NULL;
714
  }
715

716 717 718 719 720
  /* 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;

721
    while (path && path->r_next)
722 723
      path = path->r_next;

724 725 726 727
    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);
728 729 730
    }
  }

731
  if (!du->du_terminating && status < 300) {
732 733 734
    if (sip->sip_to->a_url->url_type == url_sips)
      oc->oc_secure = 1;

735
    if (!oc->oc_prev) {
736
      /* Add to the list of registrations */
737 738 739 740
      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;
741 742 743
    }
  }

744 745 746 747
  if (!du->du_terminating && status < 300 && oc->oc_prefs.gruuize) {
    outbound_connect_gruuize(oc, sip);
  }

748 749 750 751 752 753 754
  if (!du->du_terminating && status < 300 && oc->oc_nat_detected) {
    tport_t *tport = nta_outgoing_transport(orq);
    unsigned interval = tport_is_dgram(tport) ? 
      oc->oc_prefs.dgram_interval : oc->oc_prefs.stream_interval;
    tport_unref(tport);
    outbound_connect_start_keepalive(oc, 1000 * interval, orq);
  }
755
  else
756
    outbound_connect_stop_keepalive(oc);
757

758 759 760
  if (du->du_terminating || status >= 300)
    nua_dialog_usage_remove(nh, nh->nh_ds, du);

761 762 763
  return nua_stack_process_response(nh, cr, orq, sip, TAG_END());
}

764
void
765 766 767 768
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;
769
  outbound_connect *oc = nua_dialog_usage_private(du);
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  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;

786
  outbound_connect_stop_keepalive(oc);
787

788 789 790 791 792 793 794 795
  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) {
796
    int unregistering = now == 0;
797
    sip_contact_t *contact = NULL, *previous = NULL;
798 799 800 801

    if (unregistering)
      unregister_expires_contacts(msg, sip);

802 803 804 805 806
    if (oc) {
      if (oc->oc_add_contact) {
	contact = oc->oc_rcontact;
	if (oc->oc_previous && oc->oc_previous->m_expires)
	  previous = oc->oc_previous;
807 808 809
      }
    }

810 811 812
    cr->cr_orq = nta_outgoing_mcreate(nua->nua_nta,
				      process_response_to_register, nh, NULL,
				      msg,
813 814
				      SIPTAG_CONTACT(contact),
				      SIPTAG_CONTACT(previous),
815
				      SIPTAG_END(), TAG_NEXT(NULL));
816 817 818

    if (cr->cr_orq)
      oc->oc_registering = 1;
819 820 821 822 823 824 825
  }

  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);
826
    UA_EVENT2(e, NUA_INTERNAL_ERROR, TAG_END());
827 828 829 830 831 832
    return;
  }

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

834
/* ---------------------------------------------------------------------- */
835
/* Register usage interface */
836

837 838 839 840
#if HAVE_SOFIA_STUN
#include <sofia-sip/stun.h>
#endif

841
static void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta);
842

843
int
Pekka Pessi's avatar
Pekka Pessi committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
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 &&
873
	nta_agent_add_tport(nua->nua_nta, URL_STRING_MAKE("sip:*:*"),
Pekka Pessi's avatar
Pekka Pessi committed
874 875 876 877 878
			    TPTAG_IDENT("sip"),
			    TPTAG_CERTIFICATE(certificate_dir),
			    TAG_NEXT(nua->nua_args)) < 0)
      return -1;

879 880 881 882 883 884 885 886 887 888 889 890
#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
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
  }
  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)
913 914 915 916
{
  /* Create initial identities: peer-to-peer, public, sips */
  sip_via_t const *v;
  nua_handle_t *dnh = nua->nua_dhandle;
917

918 919
  v = nta_agent_public_via(nua->nua_nta);
  if (v) {
920
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 1);
921
  }
922

923 924
  v = nta_agent_via(nua->nua_nta);
  if (v) {
925
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
926
  }
927 928
  else {
    sip_via_t v[2];
929

930 931 932 933 934 935
    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.";
936

937
    outbound_connects_from_via(&nua->nua_registrations, dnh, v, 0);
938 939
  }

940
  nta_agent_bind_tport_update(nua->nua_nta, nua,
941
			      nua_stack_tport_update);
942

943 944 945 946 947 948
  return 0;
}

static
void nua_stack_tport_update(nua_t *nua, nta_agent_t *nta)
{
949 950
  outbound_connect *default_oc;
  outbound_connect const *defaults = nua->nua_registrations;
951 952
  sip_via_t *via = nta_agent_via(nta);
  
953
  default_oc = outbound_connect_by_aor(defaults, NULL, 1);
954

955 956
  if (default_oc) {
    assert(default_oc->oc_via);
957

958
    outbound_connect_contacts_from_via(default_oc,
959 960 961 962 963 964 965
				     via,
				     via->v_next);

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

  return;
966 967
}

968

969 970 971 972
sip_contact_t const *nua_contact_by_aor(nua_t *nua,
					url_t const *aor,
					int only_default)
{
973
  outbound_connect *oc = nua->nua_registrations;
974

975
  oc = outbound_connect_by_aor(oc, aor, only_default);
976

977
  return outbound_connect_contact(oc);
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
/** 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
1013
/** @internal Return a string descibing our features. */
1014 1015 1016
static
char *nua_stack_register_features(nua_handle_t *nh)
{
1017
  char *retval = NULL;
1018 1019 1020 1021 1022 1023 1024
  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))
1025
    su_slprintf(l, "+sip.instance=\"<%s>\"", NH_PGET(nh, instance));
1026 1027 1028 1029 1030

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

    if (allow) {
1031 1032
      /* Skip ";" if this is first one */
      su_strlst_append(l, ";methods=\"" + (su_strlst_len(l) == 0));
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
      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) {
1048 1049
	if (su_strlst_len(l))
	  su_strlst_append(l, ";");
1050 1051 1052 1053 1054
	su_strlst_append(l, *media++);
      }
    }
  }

1055 1056
  if (su_strlst_len(l))
    retval = su_strlst_join(l, nh->nh_home, "");
1057 1058 1059 1060 1061 1062

  su_strlst_destroy(l);

  return retval;
}

Pekka Pessi's avatar
Pekka Pessi committed
1063 1064 1065 1066 1067
/**@internal
 * Fix contacts for un-REGISTER.
 *
 * Remove (possible non-zero) "expires" parameters from contacts and extra
 * contacts, add Expire: 0.
1068 1069 1070 1071 1072 1073 1074
 */
static
void unregister_expires_contacts(msg_t *msg, sip_t *sip)
{
  sip_contact_t *m;
  int unregister_all;

1075 1076 1077