nta.c 264 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
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
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 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 nta.c
Pekka Pessi's avatar
Pekka Pessi committed
26
 * @brief Sofia SIP Transaction API implementation
Pekka Pessi's avatar
Pekka Pessi committed
27 28 29 30 31 32 33 34 35 36 37 38
 * 
 * This source file has been divided into sections as follows:
 * 1) agent
 * 2) tport handling
 * 3) dispatching messages received from network
 * 4) message creation, message utility
 * 5) stateless operation
 * 6) dialogs (legs)
 * 7) server transactions (incoming)
 * 8) client transactions (outgoing)
 * 9) resolving URLs for client transactions
 * 10) 100rel reliable responses (reliable)
Pekka Pessi's avatar
Pekka Pessi committed
39
 * 11) SigComp handling and public transport interface
Pekka Pessi's avatar
Pekka Pessi committed
40 41 42 43 44 45 46 47
 * 
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * 
 * @date Created: Tue Jun 13 02:57:51 2000 ppessi
 */

#include "config.h"

48
#include <sofia-sip/string0.h>
Pekka Pessi's avatar
Pekka Pessi committed
49 50 51 52 53 54

/** @internal SU message argument structure type */
#define SU_MSG_ARG_T   union sm_arg_u
/** @internal SU timer argument pointer type */
#define SU_TIMER_ARG_T struct nta_agent_s

55 56 57 58
#include <sofia-sip/su_alloc.h>
#include <sofia-sip/su.h>
#include <sofia-sip/su_time.h>
#include <sofia-sip/su_tagarg.h>
Pekka Pessi's avatar
Pekka Pessi committed
59

60 61
#include <sofia-sip/base64.h>
#include <sofia-sip/su_uniqueid.h>
Pekka Pessi's avatar
Pekka Pessi committed
62

63 64 65 66
#include <sofia-sip/sip.h>
#include <sofia-sip/sip_header.h>
#include <sofia-sip/sip_util.h>
#include <sofia-sip/sip_status.h>
Pekka Pessi's avatar
Pekka Pessi committed
67

68
#include <sofia-sip/msg_addr.h>
Pekka Pessi's avatar
Pekka Pessi committed
69 70

#include "nta_internal.h"
71 72
#include "sofia-sip/nta_stateless.h"
#include "sofia-sip/url_tag.h"
Pekka Pessi's avatar
Pekka Pessi committed
73

74 75 76 77 78 79 80 81
#if !defined(random) && defined(_WIN32)
#define random rand
#endif

#if !defined(EMSGSIZE) && defined(_WIN32)
#define EMSGSIZE WSAEMSGSIZE
#endif

Pekka Pessi's avatar
Pekka Pessi committed
82 83 84 85 86 87 88 89
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <limits.h>
#include <errno.h>

Pekka Pessi's avatar
Pekka Pessi committed
90 91 92
/* From AM_INIT/AC_INIT in our "config.h" */
char const nta_version[] = PACKAGE_VERSION;

Pekka Pessi's avatar
Pekka Pessi committed
93 94 95 96 97 98 99 100 101 102 103
#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
static char const __func__[] = "nta";
#endif

#define NONE ((void *)-1)

/* Internal tags */

104
/* Delay sending of request */
Pekka Pessi's avatar
Pekka Pessi committed
105 106 107 108 109 110 111
#define NTATAG_DELAY_SENDING(x) ntatag_delay_sending, tag_bool_v((x))
#define NTATAG_DELAY_SENDING_REF(x) \
ntatag_delay_sending_ref, tag_bool_vr(&(x))

extern tag_typedef_t ntatag_delay_sending;
extern tag_typedef_t ntatag_delay_sending_ref;

112
/* Allow sending incomplete responses */
Pekka Pessi's avatar
Pekka Pessi committed
113 114 115 116 117 118 119
#define NTATAG_INCOMPLETE(x) ntatag_incomplete, tag_bool_v((x))
#define NTATAG_INCOMPLETE_REF(x) \
ntatag_incomplete_ref, tag_bool_vr(&(x))

extern tag_typedef_t ntatag_incomplete;
extern tag_typedef_t ntatag_incomplete_ref;

120 121
nta_compressor_vtable_t *nta_compressor_vtable = NULL;

Pekka Pessi's avatar
Pekka Pessi committed
122 123 124 125 126 127 128 129 130 131 132 133
/* Agent */
static int agent_tag_init(nta_agent_t *self);
static int agent_timer_init(nta_agent_t *agent);
static void agent_timer(su_root_magic_t *rm, su_timer_t *, nta_agent_t *);
static int agent_launch_terminator(nta_agent_t *agent);
static void agent_kill_terminator(nta_agent_t *agent);
static int agent_set_params(nta_agent_t *agent, tagi_t *tags);
static void agent_set_udp_params(nta_agent_t *self, unsigned udp_mtu);
static int agent_get_params(nta_agent_t *agent, tagi_t *tags);

/* Transport interface */
static sip_via_t const *agent_tport_via(tport_t *tport);
Pekka Pessi's avatar
Pekka Pessi committed
134
static int outgoing_insert_via(nta_outgoing_t *orq, sip_via_t const *);
Pekka Pessi's avatar
Pekka Pessi committed
135 136 137 138 139
static int nta_tpn_by_via(tp_name_t *tpn, sip_via_t const *v, int *using_rport);

static msg_t *nta_msg_create_for_transport(nta_agent_t *agent, int flags,
					   char const data[], unsigned dlen);

140 141 142 143
static int complete_response(msg_t *response, 
			     int status, char const *phrase, 
			     msg_t const *request);

144 145
#define IF_SIGCOMP_TPTAG_COMPARTMENT(cc)     TAG_IF(cc, TPTAG_COMPARTMENT(cc)),
#define IF_SIGCOMP_TPTAG_COMPARTMENT_REF(cc) TPTAG_COMPARTMENT_REF(cc),
Pekka Pessi's avatar
Pekka Pessi committed
146

147
struct sigcomp_compartment;
148

Pekka Pessi's avatar
Pekka Pessi committed
149
struct sigcomp_compartment *
150
nta_compartment_ref(struct sigcomp_compartment *cc);
Pekka Pessi's avatar
Pekka Pessi committed
151 152 153

static
struct sigcomp_compartment *
154 155
agent_compression_compartment(nta_agent_t *sa, tport_t *tp, tp_name_t const *tpn,
			      int new_if_needed);
Pekka Pessi's avatar
Pekka Pessi committed
156 157

static
158 159
int agent_accept_compressed(nta_agent_t *sa, msg_t *msg,
			    struct sigcomp_compartment *cc);
Pekka Pessi's avatar
Pekka Pessi committed
160

161 162 163 164 165
static int agent_close_compressor(nta_agent_t *sa,
				  struct sigcomp_compartment *cc);

static int agent_zap_compressor(nta_agent_t *sa,
				struct sigcomp_compartment *cc);
Pekka Pessi's avatar
Pekka Pessi committed
166 167


Pekka Pessi's avatar
Pekka Pessi committed
168 169
static char const * stateful_branch(su_home_t *home, nta_agent_t *);
static char const * stateless_branch(nta_agent_t *, msg_t *, sip_t const *,
Pekka Pessi's avatar
Pekka Pessi committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
				    tp_name_t const *tp);

#define NTA_BRANCH_PRIME SU_U64_C(0xB9591D1C361C6521)
#define NTA_TAG_PRIME    SU_U64_C(0xB9591D1C361C6521)

HTABLE_PROTOS(leg_htable, lht, nta_leg_t);
static nta_leg_t *leg_find(nta_agent_t const *sa,
			   char const *method_name,
			   url_t const *request_uri,
			   sip_call_id_t const *i,
			   char const *from_tag,
			   url_t const *from_uri,
			   char const *to_tag,
			   url_t const *to_uri);
static nta_leg_t *dst_find(nta_agent_t const *sa, url_t const *u0,
			   char const *method);
static void leg_recv(nta_leg_t *, msg_t *, sip_t *, tport_t *);
static void leg_free(nta_agent_t *sa, nta_leg_t *leg);

#define NTA_HASH(i, cs) ((i)->i_hash + 26839U * (uint32_t)(cs))

HTABLE_PROTOS(incoming_htable, iht, nta_incoming_t);
static nta_incoming_t *incoming_create(nta_agent_t *agent,
				       msg_t *request,
				       sip_t *sip,
				       tport_t *tport,
				       char const *tag);
static int incoming_callback(nta_leg_t *leg, nta_incoming_t *irq, sip_t *sip);
static void incoming_free(nta_incoming_t *irq);
static inline void incoming_cut_off(nta_incoming_t *irq);
static inline void incoming_reclaim(nta_incoming_t *irq);
static void incoming_queue_init(incoming_queue_t *, 
				unsigned timeout);
static void incoming_queue_adjust(nta_agent_t *sa, 
				  incoming_queue_t *queue, 
				  unsigned timeout);

static inline
nta_incoming_t *incoming_find(nta_agent_t const *agent, sip_t const *sip,
			      sip_via_t const *v,
			      nta_incoming_t **merge,
			      nta_incoming_t **ack);
static int incoming_reply(nta_incoming_t *irq, msg_t *msg, sip_t *sip);
static inline int incoming_recv(nta_incoming_t *irq, msg_t *msg, sip_t *sip,
				tport_t *tport);
static inline int incoming_ack(nta_incoming_t *irq, msg_t *msg, sip_t *sip,
			       tport_t *tport);
static inline int incoming_cancel(nta_incoming_t *irq, msg_t *msg, sip_t *sip,
				  tport_t *tport);
static inline int incoming_merge(nta_incoming_t *irq, msg_t *msg, sip_t *sip,
				 tport_t *tport);
static inline int incoming_timestamp(nta_incoming_t *, msg_t *, sip_t *);
static inline int incoming_timer(nta_agent_t *, su_duration_t);

static nta_reliable_t *reliable_mreply(nta_incoming_t *,
				       nta_prack_f *, nta_reliable_magic_t *,
				       msg_t *, sip_t *);
static int reliable_send(nta_incoming_t *, nta_reliable_t *, msg_t *, sip_t *);
static int reliable_final(nta_incoming_t *irq, msg_t *msg, sip_t *sip);
static msg_t *reliable_response(nta_incoming_t *irq);
static int reliable_recv(nta_incoming_t *, msg_t *, sip_t *, tport_t *);
static void reliable_flush(nta_incoming_t *irq);
static void reliable_timeout(nta_incoming_t *irq, int timeout);

HTABLE_PROTOS(outgoing_htable, oht, nta_outgoing_t);
static nta_outgoing_t *outgoing_create(nta_agent_t *agent,
				       nta_response_f *callback,
				       nta_outgoing_magic_t *magic,
				       url_string_t const *route_url,
				       tp_name_t const *tpn,
				       msg_t *msg,
				       tag_type_t tag, tag_value_t value, ...);
static void outgoing_queue_init(outgoing_queue_t *, 
				unsigned timeout);
static void outgoing_queue_adjust(nta_agent_t *sa, 
				  outgoing_queue_t *queue, 
				  unsigned timeout);
static void outgoing_free(nta_outgoing_t *orq);
static inline void outgoing_cut_off(nta_outgoing_t *orq);
static inline void outgoing_reclaim(nta_outgoing_t *orq);
static nta_outgoing_t *outgoing_find(nta_agent_t const *sa,
				     msg_t const *msg,
				     sip_t const *sip,
				     sip_via_t const *v);
static int outgoing_recv(nta_outgoing_t *orq, int status, msg_t *, sip_t *);
255
static void outgoing_default_recv(nta_outgoing_t *, int, msg_t *, sip_t *);
Pekka Pessi's avatar
Pekka Pessi committed
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
static inline int outgoing_timer(nta_agent_t *, su_duration_t);
static int outgoing_recv_reliable(nta_outgoing_t *orq, msg_t *msg, sip_t *sip);

/* Internal message passing */
union sm_arg_u {
  struct leg_recv_s {
    nta_leg_t    *leg;
    msg_t        *msg;
    tport_t      *tport;
  } a_leg_recv[1];

  struct outgoing_recv_s {
    nta_outgoing_t *orq;
    msg_t          *msg;
    sip_t          *sip;
    int             status;
  } a_outgoing_recv[1];

  incoming_queue_t a_incoming_queue[1];
  outgoing_queue_t a_outgoing_queue[1];
};

/* Global module data */

/**@var NTA_DEBUG
 *
 * Environment variable determining the default debug log level.
 *
 * The NTA_DEBUG environment variable is used to determine the default
 * debug logging level. The normal level is 3.
 * 
 * @sa <su_debug.h>, su_log_global, SOFIA_DEBUG
 */
extern char const NTA_DEBUG[];

#ifndef SU_DEBUG
#define SU_DEBUG 3
#endif

/**Debug log for @b nta module. 
 * 
 * The nta_log is the log object used by @b nta module. The level of
 * #nta_log is set using #NTA_DEBUG environment variable.
 */
su_log_t nta_log[] = { SU_LOG_INIT("nta", "NTA_DEBUG", SU_DEBUG) };

/* ====================================================================== */
/* 1) Agent */

/**
 * Create an NTA agent object.
 *
 * The function nta_agent_create() creates an NTA agent object.  The agent
 * object creates and binds a server socket with address specified in @e url.
 * If the @e host portion of the @e url is @c "*", the agent listens to all
 * addresses available on the host.
 *
 * When a message is received, the agent object parses it.  If the result is
 * a valid SIP message, the agent object passes the message to the
 * application by invoking the nta_message_f @e callback function.
 *
 * @note
 * The @e url can be either parsed url (of type url_t ()), or a valid
 * SIP URL as a string.
 *
 * @note
 * If @e url is @c NULL, the default @e url @c "sip:*" is used.
 * @par
 * If @p transport parameters are specified in @a url, agent uses only
 * specified transport type.
 *
 * @par
 * If an @p maddr parameter is specified in @e url, agent binds to the
 * specified address, but uses @e host part of @e url in @b Contact and @b
 * Via headers.  The @p maddr parameter is also included, unless it equals
 * to @c INADDR_ANY (@p 0.0.0.0 or @p [::]).
 *
 * @param root          pointer to a su_root_t used for synchronization
 * @param contact_url   URL that agent uses to bind the server sockets
 * @param callback      pointer to callback function
 * @param magic         pointer to user data
 * @param tag,value,... other arguments
 *
 * @note It is possible to provide -1 as @a contact_url.
 * 
 * @retval handle to the agent when successful,
 * @retval NULL upon an error.
 *
 */
nta_agent_t *nta_agent_create(su_root_t *root,
			      url_string_t const *contact_url,
			      nta_message_f *callback,
			      nta_agent_magic_t *magic,
			      tag_type_t tag, tag_value_t value, ...)
{
  nta_agent_t *agent;
  ta_list ta;

  if (root == NULL)
    return su_seterrno(EINVAL), NULL;

  ta_start(ta, tag, value);

359
  if ((agent = su_home_new(sizeof(*agent)))) {
Pekka Pessi's avatar
Pekka Pessi committed
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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
    agent->sa_root = root;
    agent->sa_callback = callback;
    agent->sa_magic = magic;
    agent->sa_flags = MSG_DO_CANONIC;

    agent->sa_maxsize         = 2 * 1024 * 1024;
    agent->sa_t1 	      = NTA_SIP_T1;
    agent->sa_t2 	      = NTA_SIP_T2;
    agent->sa_t4              = NTA_SIP_T4;
    agent->sa_t1x64 	      = 64 * NTA_SIP_T1;
    agent->sa_drop_prob       = 0;
    agent->sa_is_a_uas        = 0;
    agent->sa_progress        = 60 * 1000;
    agent->sa_user_via        = 0;
    agent->sa_extra_100       = 0;
    agent->sa_pass_100        = 0;
    agent->sa_timeout_408     = 1;
    agent->sa_pass_408        = 0;
    agent->sa_merge_482       = 0;
    agent->sa_cancel_2543     = 0;
    agent->sa_cancel_487      = 1;
    agent->sa_invite_100rel   = 0;
    agent->sa_timestamp       = 0;
    agent->sa_use_naptr       = 1;
    agent->sa_use_srv         = 1;
    agent->sa_auto_comp       = 0;
    agent->sa_server_rport    = 1;

    /* RFC 3261 section 8.1.1.6 */
    sip_max_forwards_init(agent->sa_max_forwards)->mf_count = 70;

    if (getenv("SIPCOMPACT"))
      agent->sa_flags |= MSG_DO_COMPACT;

    agent_set_params(agent, ta_args(ta));

    if (agent->sa_mclass == NULL)
      agent->sa_mclass = sip_default_mclass();

    agent->sa_in.re_t1 = &agent->sa_in.re_list;
    
    incoming_queue_init(agent->sa_in.proceeding, 0);
    incoming_queue_init(agent->sa_in.preliminary, agent->sa_t1x64); /* P1 */
    incoming_queue_init(agent->sa_in.inv_completed, agent->sa_t1x64); /* H */
    incoming_queue_init(agent->sa_in.inv_confirmed, agent->sa_t4); /* I */
    incoming_queue_init(agent->sa_in.completed, agent->sa_t1x64); /* J */
    incoming_queue_init(agent->sa_in.terminated, 0);
    incoming_queue_init(agent->sa_in.final_failed, 0); 

    agent->sa_out.re_t1 = &agent->sa_out.re_list;

    outgoing_queue_init(agent->sa_out.delayed, 0);
    outgoing_queue_init(agent->sa_out.resolving, 0);
    outgoing_queue_init(agent->sa_out.trying, agent->sa_t1x64); /* F */
    outgoing_queue_init(agent->sa_out.completed, agent->sa_t4); /* K */
    outgoing_queue_init(agent->sa_out.terminated, 0); 
    /* Special queues (states) for outgoing INVITE transactions */
    outgoing_queue_init(agent->sa_out.inv_calling, agent->sa_t1x64); /* B */
    outgoing_queue_init(agent->sa_out.inv_proceeding, 0); 
    outgoing_queue_init(agent->sa_out.inv_completed, 32000); /* Timer D */

    if (leg_htable_resize(agent->sa_home, agent->sa_dialogs, 0) < 0 ||
	leg_htable_resize(agent->sa_home, agent->sa_defaults, 0) < 0 ||
	outgoing_htable_resize(agent->sa_home, agent->sa_outgoing, 0) < 0 ||
	incoming_htable_resize(agent->sa_home, agent->sa_incoming, 0) < 0) {
      SU_DEBUG_0(("nta_agent_create: failure with %s\n", "hash tables"));
      goto deinit;
    }
    SU_DEBUG_9(("nta_agent_create: initialized %s\n", "hash tables"));

    if (contact_url != (url_string_t *)-1 &&
	nta_agent_add_tport(agent, contact_url, ta_tags(ta)) < 0) {
      SU_DEBUG_7(("nta_agent_create: failure with %s\n", "transport"));
      goto deinit;
    }
    SU_DEBUG_9(("nta_agent_create: initialized %s\n", "transports"));

    if (agent_tag_init(agent) < 0) {
      SU_DEBUG_3(("nta_agent_create: failure with %s\n", "random identifiers"));
      goto deinit;
    }
    SU_DEBUG_9(("nta_agent_create: initialized %s\n", "random identifiers"));

    if (agent_timer_init(agent) < 0) {
      SU_DEBUG_0(("nta_agent_create: failure with %s\n", "timer"));
      goto deinit;
    }
    SU_DEBUG_9(("nta_agent_create: initialized %s\n", "timer"));

    if (agent_launch_terminator(agent) == 0)
      SU_DEBUG_9(("nta_agent_create: initialized %s\n", "threads"));

#if HAVE_SOFIA_SRESOLV
    agent->sa_resolver = sres_resolver_create(root, NULL, ta_tags(ta));
    if (!agent->sa_resolver) {
      SU_DEBUG_0(("nta_agent_create: failure with %s\n", "resolver"));
    }
    SU_DEBUG_9(("nta_agent_create: initialized %s\n", "resolver"));
#endif

    ta_end(ta);

    return agent;

  deinit:
    nta_agent_destroy(agent);
  }

  ta_end(ta);

  return NULL;
}

/**
 * Destroy an NTA agent object.
 *
 * @param agent the NTA agent object to be destroyed.
 *
 */
void nta_agent_destroy(nta_agent_t *agent)
{
  if (agent) {
    size_t i;
    outgoing_htable_t *oht = agent->sa_outgoing;
    incoming_htable_t *iht = agent->sa_incoming;
    /* Currently, this is pretty pointless, as legs don't keep any resources */
    leg_htable_t *lht;
    nta_leg_t *leg;

    for (i = 0, lht = agent->sa_dialogs; i < lht->lht_size; i++) {
      if ((leg = lht->lht_table[i])) {
	SU_DEBUG_3(("nta_agent_destroy: destroying dialog with <"
		    URL_PRINT_FORMAT ">\n",
		    URL_PRINT_ARGS(leg->leg_remote->a_url)));
	leg_free(agent, leg);
      }
    }

    for (i = 0, lht = agent->sa_defaults; i < lht->lht_size; i++) {
      if ((leg = lht->lht_table[i])) {
	SU_DEBUG_3(("%s: destroying leg for <" 
		    URL_PRINT_FORMAT ">\n",
		    __func__, URL_PRINT_ARGS(leg->leg_url)));
	leg_free(agent, leg);
      }
    }

    if (agent->sa_default_leg)
      leg_free(agent, agent->sa_default_leg);

    for (i = iht->iht_size; i-- > 0; )
      while (iht->iht_table[i]) {
	nta_incoming_t *irq = iht->iht_table[i];

	if (!irq->irq_destroyed)
	  SU_DEBUG_3(("%s: destroying %s server transaction from <"
		      URL_PRINT_FORMAT ">\n",
		      __func__, irq->irq_rq->rq_method_name,
		      URL_PRINT_ARGS(irq->irq_from->a_url)));

	incoming_free(irq);
      }

    for (i = oht->oht_size; i-- > 0;)
      while (oht->oht_table[i]) {
	nta_outgoing_t *orq = oht->oht_table[i];

	if (!orq->orq_destroyed)
	  SU_DEBUG_3(("%s: destroying %s client transaction to <"
		      URL_PRINT_FORMAT ">\n",
		      __func__, orq->orq_method_name,
		      URL_PRINT_ARGS(orq->orq_to->a_url)));

	outgoing_free(orq);
      }

    su_timer_destroy(agent->sa_timer), agent->sa_timer = NULL;

#   if HAVE_SOFIA_SRESOLV
    sres_resolver_destroy(agent->sa_resolver), agent->sa_resolver = NULL;
#   endif

    tport_destroy(agent->sa_tports), agent->sa_tports = NULL;

    agent_kill_terminator(agent);

546
    su_home_unref(agent->sa_home);
Pekka Pessi's avatar
Pekka Pessi committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
  }
}

/** Return agent context. */
nta_agent_magic_t *nta_agent_magic(nta_agent_t const *agent)
{
  return agent ? agent->sa_magic : NULL;
}

/** Return @b Contact header.
 *
 * The function nta_agent_contact() returns a @b Contact header, which can be
 * used to reach @a agent.
 *
 * @param agent NTA agent object
 *
 * @return The function nta_agent_contact() returns a sip_contact_t object
 * corresponding to the @a agent.
 *
 * User agents can insert the @b Contact header in the outgoing REGISTER,
 * INVITE, and ACK requests and replies to incoming INVITE and OPTIONS
 * transactions.
 *
 * Proxies can use the @b Contact header to create appropriate @b Record-Route
 * headers:
 * @code
 * r_r = sip_record_route_create(msg_home(msg),
 *	 			 sip->sip_request->rq_url,
 *				 contact->m_url);
 * @endcode
 */
sip_contact_t *nta_agent_contact(nta_agent_t const *agent)
{
  return agent ? agent->sa_contact : NULL;
}

/** Return a list of @b Via headers.
 *
 * The function nta_agent_via() returns @b Via headers for all activated
 * transport.
 *
 * @param agent NTA agent object
 *
 * @return The function nta_agent_via() returns a list of sip_via_t objects
 * used by the @a agent.
 */
sip_via_t *nta_agent_via(nta_agent_t const *agent)
{
  return agent ? agent->sa_vias : NULL;
}

598 599

/** Return a list of public (UPnP, STUN) @b Via headers.
600
 *
601 602
 * The function nta_agent_public_via() returns public @b Via headers for all activated
 * transports.
603 604
 *
 * @param agent NTA agent object
605 606 607
 *
 * @return The function nta_agent_public_via() returns a list of sip_via_t objects
 * used by the @a agent.
608 609 610 611 612 613
 */
sip_via_t *nta_agent_public_via(nta_agent_t const *agent)
{
  return agent ? agent->sa_public_vias : NULL;
}

Pekka Pessi's avatar
Pekka Pessi committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
/** Return @b User-Agent header.
 *
 * The function nta_agent_name() returns a @b User-Agent information with
 * NTA version.
 *
 * @param agent NTA agent object
 *
 * @return The function nta_agent_contact() returns a string containing the
 * @a agent version.
 */
char const *nta_agent_version(nta_agent_t const *agent)
{
  return "nta" "/" VERSION;
}

/** Initialize default tag */
static int agent_tag_init(nta_agent_t *self)
{
  sip_contact_t *m = self->sa_contact;
  uint32_t hash = 1;

  if (m) {

    if (m->m_url->url_user)
      hash = 914715421U * hash + msg_hash_string(m->m_url->url_user);
    if (m->m_url->url_host)
      hash = 914715421U * hash + msg_hash_string(m->m_url->url_host);
    if (m->m_url->url_port)
      hash = 914715421U * hash + msg_hash_string(m->m_url->url_port);
    if (m->m_url->url_params)
      hash = 914715421U * hash + msg_hash_string(m->m_url->url_params);
  }

  if (hash == 0)
    hash = 914715421U;

  self->sa_branch = NTA_BRANCH_PRIME * su_ntp_now();
  self->sa_branch *= hash;

  self->sa_tags = NTA_TAG_PRIME * self->sa_branch;

  return 0;
}

/** Initialize agent timer. */
static
int agent_timer_init(nta_agent_t *agent)
{
  return su_timer_set(agent->sa_timer =
		      su_timer_create(su_root_task(agent->sa_root),
				      NTA_SIP_T1 / 8),
		      agent_timer,
		      agent);
}

/**
 * Agent timer routine.
 */
static
void agent_timer(su_root_magic_t *rm, su_timer_t *timer, nta_agent_t *agent)
{
  su_duration_t now = su_time_ms(agent->sa_now = su_now());
  int again;

  now += now == 0;

  agent->sa_millisec = now;

  again = outgoing_timer(agent, now);
  again = incoming_timer(agent, now) || again;

  agent->sa_millisec = 0;

  if (again)
    su_timer_set_at(timer, agent_timer, agent, su_time_add(su_now(), 1));
  else
    su_timer_set(timer, agent_timer, agent);
}

/** Calculate nonzero value for timer */
static inline
su_duration_t set_timeout(nta_agent_t const *agent, su_duration_t offset)
{
  su_duration_t now;

#if 0
  if (agent->sa_millisec)
    now = agent->sa_millisec;
  else
#endif
    now = (su_duration_t)su_time_ms(su_now());

  now += offset;

  return now ? now : 1;
}


/** Return current timeval. */
713
static
Pekka Pessi's avatar
Pekka Pessi committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
su_time_t agent_now(nta_agent_t const *agent)
{
  return agent->sa_millisec ? agent->sa_now : su_now();
}


/** Launch transaction terminator task */
static
int agent_launch_terminator(nta_agent_t *agent)
{
#ifdef TPTAG_THRPSIZE
  if (agent->sa_tport_threadpool) {
    su_home_threadsafe(agent->sa_home);
    return su_clone_start(agent->sa_root, 
			  agent->sa_terminator,
			  NULL,
			  NULL,
			  NULL);
  }
#endif
  return -1;
}

/** Kill transaction terminator task */
static
void agent_kill_terminator(nta_agent_t *agent)
{
  su_clone_wait(agent->sa_root, agent->sa_terminator);
}


/**Set NTA Parameters.
 *
 * The nta_agent_set_params() function sets the stack parameters. The
 * parameters determine the way NTA handles the retransmissions, how long
 * NTA keeps transactions alive, does NTA apply proxy or user-agent logic to
 * INVITE transactions, or how the @b Via headers are generated.
 *
 * @note 
 * Setting the parameters NTATAG_MAXSIZE(), NTATAG_UDP_MTU(),
 * NTATAG_SIP_T1X64(), NTATAG_SIP_T1(), NTATAG_SIP_T2(), NTATAG_SIP_T4() to
 * 0 selects the default value.
 *
 * @TAGS
 * NTATAG_ALIASES(), NTATAG_BAD_REQ_MASK(), NTATAG_BAD_RESP_MASK(),
 * NTATAG_CANCEL_2543(), NTATAG_CANCEL_487(), NTATAG_DEBUG_DROP_PROB(),
 * NTATAG_DEFAULT_PROXY(), NTATAG_EXTRA_100(), NTATAG_MAXSIZE(),
 * NTATAG_UDP_MTU(), NTATAG_MERGE_482(), NTATAG_PASS_100(),
Pekka Pessi's avatar
Pekka Pessi committed
762 763
 * NTATAG_PRELOAD(), NTATAG_REL100(), NTATAG_RPORT(), NTATAG_SERVER_RPORT(),
 * NTATAG_TCP_RPORT(),
Pekka Pessi's avatar
Pekka Pessi committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 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 819 820
 * NTATAG_SIPFLAGS(), NTATAG_SIP_T1X64(), NTATAG_SIP_T1(), NTATAG_SIP_T2(),
 * NTATAG_SIP_T4(), NTATAG_SMIME(), NTATAG_STATELESS(), NTATAG_TAG_3261(),
 * NTATAG_TIMEOUT_408(), NTATAG_PASS_408(), NTATAG_UA(), NTATAG_USER_VIA(),
 * and NTATAG_USE_TIMESTAMP().
 */
int nta_agent_set_params(nta_agent_t *agent,
			 tag_type_t tag, tag_value_t value, ...)
{
  int retval;

  if (agent) {
    ta_list ta;
    ta_start(ta, tag, value);
    retval = agent_set_params(agent, ta_args(ta));
    ta_end(ta);
  } else {
    su_seterrno(EINVAL);
    retval = -1;
  }

  return retval;
}

/** Internal function for setting tags */
static
int agent_set_params(nta_agent_t *agent, tagi_t *tags)
{
  int n, m;
  unsigned bad_req_mask = agent->sa_bad_req_mask;
  unsigned bad_resp_mask = agent->sa_bad_resp_mask;
  unsigned maxsize    = agent->sa_maxsize;
  unsigned udp_mtu    = agent->sa_udp_mtu;
  unsigned sip_t1     = agent->sa_t1;
  unsigned sip_t2     = agent->sa_t2;
  unsigned sip_t4     = agent->sa_t4;
  unsigned sip_t1x64  = agent->sa_t1x64;
  unsigned blacklist  = agent->sa_blacklist;
  int ua              = agent->sa_is_a_uas;
  unsigned progress   = agent->sa_progress;
  int stateless       = agent->sa_is_stateless;
  unsigned drop_prob  = agent->sa_drop_prob;
  int user_via        = agent->sa_user_via;
  int extra_100       = agent->sa_extra_100;
  int pass_100        = agent->sa_pass_100;
  int timeout_408     = agent->sa_timeout_408;
  int pass_408        = agent->sa_pass_408;
  int merge_482       = agent->sa_merge_482;
  int cancel_2543     = agent->sa_cancel_2543;
  int cancel_487      = agent->sa_cancel_487;
  int invite_100rel   = agent->sa_invite_100rel;
  int use_timestamp   = agent->sa_timestamp;
  int use_naptr       = agent->sa_use_naptr;
  int use_srv         = agent->sa_use_srv;
  void *smime         = agent->sa_smime;
  uint32_t flags      = agent->sa_flags;
  int rport           = agent->sa_rport;
  int server_rport    = agent->sa_server_rport;
Pekka Pessi's avatar
Pekka Pessi committed
821
  int tcp_rport       = agent->sa_tcp_rport;
Pekka Pessi's avatar
Pekka Pessi committed
822 823 824 825 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 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  unsigned preload         = agent->sa_preload;
  unsigned threadpool      = agent->sa_tport_threadpool;
  char const *sigcomp = agent->sa_sigcomp_options;
  char const *algorithm = NONE;
  msg_mclass_t *mclass = NONE;
  sip_contact_t const *aliases = NONE;
  url_string_t const *proxy = NONE;
  tport_t *tport;

  su_home_t *home = agent->sa_home;

  n = tl_gets(tags,
	      NTATAG_MCLASS_REF(mclass),
	      NTATAG_BAD_REQ_MASK_REF(bad_req_mask),
	      NTATAG_BAD_RESP_MASK_REF(bad_resp_mask),
	      NTATAG_ALIASES_REF(aliases),
	      NTATAG_UA_REF(ua),
	      NTATAG_STATELESS_REF(stateless),
	      NTATAG_MAXSIZE_REF(maxsize),
	      NTATAG_UDP_MTU_REF(udp_mtu),
	      NTATAG_SIP_T1_REF(sip_t1),
	      NTATAG_SIP_T2_REF(sip_t2),
	      NTATAG_SIP_T4_REF(sip_t4),
	      NTATAG_SIP_T1X64_REF(sip_t1x64),
	      NTATAG_PROGRESS_REF(progress),
	      NTATAG_BLACKLIST_REF(blacklist),
	      NTATAG_DEBUG_DROP_PROB_REF(drop_prob),
	      NTATAG_USER_VIA_REF(user_via),
	      NTATAG_EXTRA_100_REF(extra_100),
	      NTATAG_PASS_100_REF(pass_100),
	      NTATAG_TIMEOUT_408_REF(timeout_408),
	      NTATAG_PASS_408_REF(pass_408),
	      NTATAG_MERGE_482_REF(merge_482),
	      NTATAG_DEFAULT_PROXY_REF(proxy),
	      NTATAG_CANCEL_2543_REF(cancel_2543),
	      NTATAG_CANCEL_487_REF(cancel_487),
	      NTATAG_REL100_REF(invite_100rel),
	      NTATAG_USE_TIMESTAMP_REF(use_timestamp),
	      NTATAG_USE_NAPTR_REF(use_naptr),
	      NTATAG_USE_SRV_REF(use_srv),
#if HAVE_SOFIA_SMIME
	      NTATAG_SMIME_REF(smime),
#endif
	      NTATAG_SIPFLAGS_REF(flags),
	      NTATAG_RPORT_REF(rport),
	      NTATAG_SERVER_RPORT_REF(server_rport),
Pekka Pessi's avatar
Pekka Pessi committed
868
	      NTATAG_TCP_RPORT_REF(tcp_rport),
Pekka Pessi's avatar
Pekka Pessi committed
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
	      NTATAG_PRELOAD_REF(preload),
#ifdef TPTAG_THRPSIZE
	      /* If threadpool is enabled, start a separate "reaper thread" */
	      TPTAG_THRPSIZE_REF(threadpool),
#endif
	      NTATAG_SIGCOMP_OPTIONS_REF(sigcomp),
	      NTATAG_SIGCOMP_ALGORITHM_REF(algorithm),
	      TAG_END());

  if (mclass != NONE)
    agent->sa_mclass = mclass ? mclass : sip_default_mclass();

  m = 0;
  for (tport = agent->sa_tports; tport; tport = tport_next(tport)) {
    m = tport_set_params(tport, TAG_NEXT(tags));
  }

Pekka Pessi's avatar
Pekka Pessi committed
886
  if (n == 0 || m == -1)
Pekka Pessi's avatar
Pekka Pessi committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    return m;

  n += m;

  if (aliases != NONE) {
    sip_contact_t const *m, *m_next;

    m = agent->sa_aliases;
    agent->sa_aliases = sip_contact_dup(home, aliases);

    for (; m; m = m_next) {	/* Free old aliases */
      m_next = m->m_next;
      su_free(home, (void *)m);
    }
  }

  if (proxy != NONE) {
    url_t *dp = url_hdup(home, proxy->us_url);

    url_sanitize(dp);

    if (dp == NULL || dp->url_type == url_sip || dp->url_type == url_sips) {
      if (agent->sa_default_proxy)
	su_free(home, agent->sa_default_proxy);
      agent->sa_default_proxy = dp;
    }
    else
Pekka Pessi's avatar
Pekka Pessi committed
914
      n = -1;
Pekka Pessi's avatar
Pekka Pessi committed
915 916 917
  }

  if (algorithm != NONE)
918
    agent->sa_algorithm = su_strdup(home, algorithm);
Pekka Pessi's avatar
Pekka Pessi committed
919 920 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 967 968 969 970 971 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

  if (str0cmp(sigcomp, agent->sa_sigcomp_options)) {
    int msg_avlist_d(su_home_t *home, char **ss, msg_param_t const **pparams);
    char const * const *l = NULL;
    char *s = su_strdup(home, sigcomp);
    char *s1 = su_strdup(home, s), *s2 = s1;

    if (s && s2 && msg_avlist_d(home, &s2, &l) == 0 && *s2 == '\0') {
      su_free(home, (void *)agent->sa_sigcomp_options);
      su_free(home, (void *)agent->sa_sigcomp_option_list);
      agent->sa_sigcomp_options = s;
      agent->sa_sigcomp_option_free = s1;
      agent->sa_sigcomp_option_list = l;
    } else {
      su_free(home, s);
      su_free(home, s1);
      su_free(home, (void *)l);
      n = -1;
    }
  }

  if (maxsize == 0) maxsize = 2 * 1024 * 1024;
  if (maxsize > NTA_TIME_MAX) maxsize = NTA_TIME_MAX;
  agent->sa_maxsize = maxsize;

  if (udp_mtu == 0) udp_mtu = 1300;
  if (udp_mtu > 65535) udp_mtu = 65535;
  if (agent->sa_udp_mtu != udp_mtu)
    agent_set_udp_params(agent, udp_mtu);

  if (sip_t1 == 0) sip_t1 = NTA_SIP_T1;
  if (sip_t1 > NTA_TIME_MAX) sip_t1 = NTA_TIME_MAX;
  agent->sa_t1 = sip_t1;

  if (sip_t2 == 0) sip_t2 = NTA_SIP_T2;
  if (sip_t2 > NTA_TIME_MAX) sip_t2 = NTA_TIME_MAX;
  agent->sa_t2 = sip_t2;

  if (sip_t4 == 0) sip_t4 = NTA_SIP_T4;
  if (sip_t4 > NTA_TIME_MAX) sip_t4 = NTA_TIME_MAX;
  if (agent->sa_t4 != sip_t4) {
    incoming_queue_adjust(agent, agent->sa_in.inv_confirmed, sip_t4);
    outgoing_queue_adjust(agent, agent->sa_out.completed, sip_t4);
  }
  agent->sa_t4 = sip_t4;

  if (sip_t1x64 == 0) sip_t1x64 = NTA_SIP_T1 * 64;
  if (sip_t1x64 > NTA_TIME_MAX) sip_t1x64 = NTA_TIME_MAX;
  if (agent->sa_t1x64 != sip_t1x64) {
    incoming_queue_adjust(agent, agent->sa_in.preliminary, sip_t1x64);
    incoming_queue_adjust(agent, agent->sa_in.completed, sip_t1x64);
    incoming_queue_adjust(agent, agent->sa_in.inv_completed, sip_t1x64);
    outgoing_queue_adjust(agent, agent->sa_out.trying, sip_t1x64);
    outgoing_queue_adjust(agent, agent->sa_out.inv_calling, sip_t1x64);
  }
  agent->sa_t1x64 = sip_t1x64;
  agent->sa_blacklist = blacklist;

  if (progress == 0)
    progress = 60 * 1000;
  agent->sa_progress = progress;

  agent->sa_bad_req_mask = bad_req_mask;
  agent->sa_bad_resp_mask = bad_resp_mask;

  agent->sa_is_a_uas = ua != 0;
  agent->sa_is_stateless = stateless != 0;
  agent->sa_drop_prob = drop_prob < 1000 ? drop_prob : 1000;
  agent->sa_user_via = user_via != 0;
  agent->sa_extra_100 = extra_100 != 0;
  agent->sa_pass_100 = pass_100 != 0;
  agent->sa_timeout_408 = timeout_408 != 0;
  agent->sa_pass_408 = pass_408 != 0;
  agent->sa_merge_482 = merge_482 != 0;
  agent->sa_cancel_2543 = cancel_2543 != 0;
  agent->sa_cancel_487 = cancel_487 != 0;
  agent->sa_invite_100rel = invite_100rel != 0;
  agent->sa_timestamp = use_timestamp != 0;
  agent->sa_use_naptr = use_naptr != 0;
  agent->sa_use_srv = use_srv != 0;
  agent->sa_smime = smime;
  agent->sa_flags = flags & MSG_FLG_USERMASK;
  agent->sa_rport = rport != 0;
1002
  agent->sa_server_rport = server_rport != 0;
Pekka Pessi's avatar
Pekka Pessi committed
1003
  agent->sa_tcp_rport = tcp_rport != 0;
Pekka Pessi's avatar
Pekka Pessi committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
  agent->sa_preload = preload;
  agent->sa_tport_threadpool = threadpool;

  return n;
}

static 
void agent_set_udp_params(nta_agent_t *self, unsigned udp_mtu)
{
  tport_t *tp;

  self->sa_udp_mtu = udp_mtu;

  /* Set via fields for the tports */
  for (tp = tport_primaries(self->sa_tports); tp; tp = tport_next(tp)) {
Pekka Pessi's avatar
Pekka Pessi committed
1019
    if (tport_is_udp(tp))
Pekka Pessi's avatar
Pekka Pessi committed
1020 1021 1022 1023 1024 1025 1026 1027 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 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
      tport_set_params(tp,
		       TPTAG_TIMEOUT(2 * self->sa_t1x64),
		       TPTAG_MTU(self->sa_udp_mtu),
		       TAG_END());
  }
}

/**Get NTA Parameters.
 *
 * The nta_agent_get_params() function retrieves the stack parameters. The
 * parameters determine the way NTA handles the retransmissions, how long
 * NTA keeps transactions alive, does NTA apply proxy or user-agent logic to
 * INVITE transactions, or how the @b Via headers are generated.
 *
 * @TAGS
 * NTATAG_ALIASES_REF(), NTATAG_CANCEL_2543_REF(), NTATAG_CANCEL_487_REF(),
 * NTATAG_CONTACT_REF(), NTATAG_DEBUG_DROP_PROB_REF(),
 * NTATAG_DEFAULT_PROXY_REF(), NTATAG_EXTRA_100_REF(), NTATAG_MAXSIZE_REF(),
 * NTATAG_MERGE_482_REF(), NTATAG_PASS_100_REF(), NTATAG_PRELOAD_REF(),
 * NTATAG_REL100_REF(), NTATAG_RPORT_REF(), NTATAG_SIPFLAGS_REF(),
 * NTATAG_SIP_T1X64_REF(), NTATAG_SIP_T1_REF(), NTATAG_SIP_T2_REF(),
 * NTATAG_SIP_T4_REF(), NTATAG_SMIME_REF(), NTATAG_STATELESS_REF(),
 * NTATAG_TAG_3261_REF(), NTATAG_TIMEOUT_408_REF(), NTATAG_PASS_408_REF(),
 * NTATAG_UA_REF(), NTATAG_USER_VIA_REF(), and NTATAG_USE_TIMESTAMP_REF().
 *
 */
int nta_agent_get_params(nta_agent_t *agent,
			 tag_type_t tag, tag_value_t value, ...)
{
  int n;
  ta_list ta;

  if (agent) {
    ta_start(ta, tag, value);
    n = agent_get_params(agent, ta_args(ta));
    ta_end(ta);
  } else {
    su_seterrno(EINVAL);
    n = -1;
  }

  return n;
}

/** Get NTA parameters */
static
int agent_get_params(nta_agent_t *agent, tagi_t *tags)
{
  return
    tl_tgets(tags,
	     NTATAG_MCLASS(agent->sa_mclass),
	     NTATAG_CONTACT(agent->sa_contact),
	     NTATAG_ALIASES(agent->sa_aliases),
	     NTATAG_UA(agent->sa_is_a_uas),
	     NTATAG_STATELESS(agent->sa_is_stateless),
	     NTATAG_MAXSIZE(agent->sa_maxsize),
	     NTATAG_UDP_MTU(agent->sa_udp_mtu),
	     NTATAG_SIP_T1(agent->sa_t1),
	     NTATAG_SIP_T2(agent->sa_t2),
	     NTATAG_SIP_T4(agent->sa_t4),
	     NTATAG_SIP_T1X64(agent->sa_t1x64),
	     NTATAG_BLACKLIST(agent->sa_blacklist),
	     NTATAG_DEBUG_DROP_PROB(agent->sa_drop_prob),
	     NTATAG_USER_VIA(agent->sa_user_via),
	     NTATAG_EXTRA_100(agent->sa_extra_100),
	     NTATAG_PASS_100(agent->sa_pass_100),
	     NTATAG_TIMEOUT_408(agent->sa_timeout_408),
	     NTATAG_PASS_408(agent->sa_pass_408),
	     NTATAG_MERGE_482(agent->sa_merge_482),
	     NTATAG_DEFAULT_PROXY(agent->sa_default_proxy),
	     NTATAG_CANCEL_2543(agent->sa_cancel_2543),
	     NTATAG_CANCEL_487(agent->sa_cancel_487),
1092
	     NTATAG_TAG_3261(1),
Pekka Pessi's avatar
Pekka Pessi committed
1093 1094 1095 1096 1097 1098
	     NTATAG_REL100(agent->sa_invite_100rel),
	     NTATAG_USE_TIMESTAMP(agent->sa_timestamp),
	     NTATAG_USE_NAPTR(agent->sa_use_naptr),
	     NTATAG_USE_SRV(agent->sa_use_srv),
#if HAVE_SOFIA_SMIME
	     NTATAG_SMIME(agent->sa_smime),
1099 1100
#else
	     NTATAG_SMIME(NULL),
Pekka Pessi's avatar
Pekka Pessi committed
1101 1102 1103 1104
#endif
	     NTATAG_SIPFLAGS(agent->sa_flags),
	     NTATAG_RPORT(agent->sa_rport),
	     NTATAG_PRELOAD(agent->sa_preload),
1105
	     NTATAG_SIGCOMP_ALGORITHM(agent->sa_algorithm),
Pekka Pessi's avatar
Pekka Pessi committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
	     NTATAG_SIGCOMP_OPTIONS(agent->sa_sigcomp_options ?
				    agent->sa_sigcomp_options :
				    "sip"),
	     TAG_END());
}

/**Get NTA statistics.
 *
 * The nta_agent_get_stats() function retrieves the stack statistics.
 *
 * @TAGS
 * @TAG NTATAG_S_*
 *
 */
int nta_agent_get_stats(nta_agent_t *agent,
			tag_type_t tag, tag_value_t value, ...)
{
  int n;
  ta_list ta;

  if (!agent)
    return su_seterrno(EINVAL), -1;

  ta_start(ta, tag, value);

  n = tl_tgets(ta_args(ta),
	       NTATAG_S_IRQ_HASH(agent->sa_incoming->iht_size),
	       NTATAG_S_ORQ_HASH(agent->sa_outgoing->oht_size),
	       NTATAG_S_LEG_HASH(agent->sa_dialogs->lht_size),
	       NTATAG_S_IRQ_HASH_USED(agent->sa_incoming->iht_used),
	       NTATAG_S_ORQ_HASH_USED(agent->sa_outgoing->oht_used),
	       NTATAG_S_LEG_HASH_USED(agent->sa_dialogs->lht_used),
	       NTATAG_S_RECV_MSG(agent->sa_stats->as_recv_msg),
	       NTATAG_S_RECV_REQUEST(agent->sa_stats->as_recv_request),
	       NTATAG_S_RECV_RESPONSE(agent->sa_stats->as_recv_response),
	       NTATAG_S_BAD_MESSAGE(agent->sa_stats->as_bad_message),
	       NTATAG_S_BAD_REQUEST(agent->sa_stats->as_bad_request),
	       NTATAG_S_BAD_RESPONSE(agent->sa_stats->as_bad_response),
	       NTATAG_S_DROP_REQUEST(agent->sa_stats->as_drop_request),
	       NTATAG_S_DROP_RESPONSE(agent->sa_stats->as_drop_response),
	       NTATAG_S_CLIENT_TR(agent->sa_stats->as_client_tr),
	       NTATAG_S_SERVER_TR(agent->sa_stats->as_server_tr),
	       NTATAG_S_DIALOG_TR(agent->sa_stats->as_dialog_tr),
	       NTATAG_S_ACKED_TR(agent->sa_stats->as_acked_tr),
	       NTATAG_S_CANCELED_TR(agent->sa_stats->as_canceled_tr),
	       NTATAG_S_TRLESS_REQUEST(agent->sa_stats->as_trless_request),
	       NTATAG_S_TRLESS_TO_TR(agent->sa_stats->as_trless_to_tr),
	       NTATAG_S_TRLESS_RESPONSE(agent->sa_stats->as_trless_response),
	       NTATAG_S_TRLESS_200(agent->sa_stats->as_trless_200),
	       NTATAG_S_MERGED_REQUEST(agent->sa_stats->as_merged_request),
	       NTATAG_S_SENT_MSG(agent->sa_stats->as_sent_msg),
	       NTATAG_S_SENT_REQUEST(agent->sa_stats->as_sent_request),
	       NTATAG_S_SENT_RESPONSE(agent->sa_stats->as_sent_response),
	       NTATAG_S_RETRY_REQUEST(agent->sa_stats->as_retry_request),
	       NTATAG_S_RETRY_RESPONSE(agent->sa_stats->as_retry_response),
	       NTATAG_S_RECV_RETRY(agent->sa_stats->as_recv_retry),
	       NTATAG_S_TOUT_REQUEST(agent->sa_stats->as_tout_request),
	       NTATAG_S_TOUT_RESPONSE(agent->sa_stats->as_tout_response),
	       TAG_END());

  ta_end(ta);

  return n;
}

/**Calculate a new unique tag.
 *
 * This function generates a series of 2**64 unique tags for @b From or @b To
 * headers. The start of the tag series is derived from the NTP time the NTA
 * agent was initialized.
 *
 */
Pekka Pessi's avatar
Pekka Pessi committed
1178
char const *nta_agent_newtag(su_home_t *home, char const *fmt, nta_agent_t *sa)
Pekka Pessi's avatar
Pekka Pessi committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
{
  char tag[(8 * 8 + 4)/ 5 + 1];

  if (sa == NULL)
    return su_seterrno(EINVAL), NULL;

  /* XXX - use a cryptographically safe func here? */
  sa->sa_tags += NTA_TAG_PRIME;

  msg_random_token(tag, sizeof(tag) - 1, &sa->sa_tags, sizeof(sa->sa_tags));

  if (fmt && fmt[0])
    return su_sprintf(home, fmt, tag);
  else
    return su_strdup(home, tag);
}

/**
 * Calculate branch value.
 */
Pekka Pessi's avatar
Pekka Pessi committed
1199
static char const *stateful_branch(su_home_t *home, nta_agent_t *sa)
Pekka Pessi's avatar
Pekka Pessi committed
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
{
  char branch[(8 * 8 + 4)/ 5 + 1];

  /* XXX - use a cryptographically safe func here? */
  sa->sa_branch += NTA_BRANCH_PRIME;

  msg_random_token(branch, sizeof(branch) - 1, 
		   &sa->sa_branch, sizeof(sa->sa_branch));

  return su_sprintf(home, "branch=z9hG4bK%s", branch);
}

1212
#include <sofia-sip/su_md5.h>
Pekka Pessi's avatar
Pekka Pessi committed
1213 1214 1215 1216 1217 1218 1219

/**
 * Calculate branch value for stateless operation.
 * 
 * XXX - should include HMAC of previous Via line.
 */
static
Pekka Pessi's avatar
Pekka Pessi committed
1220
char const *stateless_branch(nta_agent_t *sa, 
Pekka Pessi's avatar
Pekka Pessi committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
			     msg_t *msg,
			     sip_t const *sip, 
			     tp_name_t const *tpn)
{
  su_md5_t md5[1];
  uint8_t digest[SU_MD5_DIGEST_SIZE];
  char branch[(SU_MD5_DIGEST_SIZE * 8 + 4)/ 5 + 1];
  sip_route_t const *r;

  assert(sip->sip_request);

  if (!sip->sip_via)
    return stateful_branch(msg_home(msg), sa);

  su_md5_init(md5);

  su_md5_str0update(md5, tpn->tpn_host);
  su_md5_str0update(md5, tpn->tpn_port);

  url_update(md5, sip->sip_request->rq_url);
  if (sip->sip_call_id) {
    su_md5_str0update(md5, sip->sip_call_id->i_id);
  }
  if (sip->sip_from) {
    url_update(md5, sip->sip_from->a_url);
    su_md5_stri0update(md5, sip->sip_from->a_tag);
  }
  if (sip->sip_to) {
    url_update(md5, sip->sip_to->a_url);
Pekka Pessi's avatar
Pekka Pessi committed
1250 1251
    /* XXX - some broken implementations include To tag in CANCEL */
    /* su_md5_str0update(md5, sip->sip_to->a_tag); */
Pekka Pessi's avatar
Pekka Pessi committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  }
  if (sip->sip_cseq) {
    uint32_t cseq = htonl(sip->sip_cseq->cs_seq);
    su_md5_update(md5, &cseq, sizeof(cseq));
  }

  for (r = sip->sip_route; r; r = r->r_next)
    url_update(md5, r->r_url);

  su_md5_digest(md5, digest);

  msg_random_token(branch, sizeof(branch) - 1, digest, sizeof(digest));

  return su_sprintf(msg_home(msg), "branch=z9hG4bK.%s", branch);
}

/* ====================================================================== */
/* 2) Transport interface */

/* Local prototypes */
Pekka Pessi's avatar
Pekka Pessi committed
1272
static int agent_create_master_transport(nta_agent_t *self, tagi_t *tags);
1273
static int agent_init_via(nta_agent_t *self, tport_t *primaries, int use_maddr);
Pekka Pessi's avatar
Pekka Pessi committed
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
static int agent_init_contact(nta_agent_t *self);
static void agent_recv_message(nta_agent_t *agent,
			       tport_t *tport,
			       msg_t *msg,
			       sip_via_t *tport_via,
			       su_time_t now);
static void agent_tp_error(nta_agent_t *agent,
			   tport_t *tport,
			   int errcode,
			   char const *remote);
1284
static void agent_update_tport(nta_agent_t *agent, tport_t *);
Pekka Pessi's avatar
Pekka Pessi committed
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

/**For each transport, we have name used by tport module, SRV prefixes used
 * for resolving, and NAPTR service/conversion.
 */
static 
struct sipdns_tport {
  char name[6];			/**< Named used by tport module */
  char port[6];			/**< Default port number */
  char prefix[14];		/**< Prefix for SRV domains */
  char service[10];		/**< NAPTR service */
}
#define SIPDNS_TRANSPORTS (4)
const sipdns_tports[SIPDNS_TRANSPORTS] = {
  { "udp",  "5060", "_sip._udp.",  "SIP+D2U"  },
  { "tcp",  "5060", "_sip._tcp.",  "SIP+D2T"  },
1300 1301
  { "sctp", "5060", "_sip._sctp.", "SIP+D2S" },
  { "tls",  "5061", "_sips._tcp.", "SIPS+D2T"  },
Pekka Pessi's avatar
Pekka Pessi committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
};

static char const * const tports_sip[] =
  {
    "udp", "tcp", "sctp", NULL
  };

static char const * const tports_sips[] =
  {
    "tls", NULL
  };

1314
static tport_stack_class_t nta_agent_class[1] =
Pekka Pessi's avatar
Pekka Pessi committed
1315 1316 1317 1318 1319
  {{
    sizeof(nta_agent_class),
    agent_recv_message,
    agent_tp_error,
    (void *)nta_msg_create_for_transport,
1320
    agent_update_tport,
Pekka Pessi's avatar
Pekka Pessi committed
1321 1322 1323 1324 1325 1326 1327
  }};


/** Add a transport to the agent.
 *
 * The function nta_agent_add_tport() creates a new transport and binds it
 * to the port specified by the @a uri. The @a uri must have sip: or sips:
1328 1329 1330
 * scheme or be a wildcard uri ("*"). The @a uri syntax allowed is as
 * follows:
 *
1331
 * @code url <scheme>:<host>[:<port>]<url-params> @endcode
1332
 * where <url-params> may be
1333
 * @code
1334 1335 1336
 * ;transport=<xxx>
 * ;maddr=<actual addr>
 * ;comp=sigcomp
1337
 * @endcode
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
 *
 * The scheme part determines which transports are used. "sip" implies UDP
 * and TCP, "sips" TLS over TCP. In the future, more transports can be
 * supported, for instance, "sip" can use SCTP or DCCP, "sips" DTLS or TLS
 * over SCTP.
 *
 * The "host" part determines what address/domain name is used in Contact.
 * An "*" in "host" part is shorthand for any local IP address. 0.0.0.0
 * means that the only the IPv4 addresses are used. [::] means that only
 * the IPv6 addresses are used. If a domain name or a specific IP address
 * is given as "host" part, an additional "maddr" parameter can be used to
 * control which addresses are used by the stack when binding listen
 * sockets for incoming requests.
 *
 * The "port" determines what port is used in contact, and to which port the
 * stack binds in order to listen for incoming requests. Empty or missing
 * port means that default port should be used (5060 for sip, 5061 for
 * sips). An "*" in "port" part means any port, i.e., the stack binds to an
 * ephemeral port.
 *
1358 1359 1360 1361 1362 1363
 * The "transport" parameter determines the transport protocol that is used
 * and how they are preferred. If no protocol is specified, both UDP and TCP
 * are used for SIP URL and TLS for SIPS URL. The preference can be
 * indicated with a comma-separated list of transports, for instance,
 * parameter @code transport=tcp,udp @endocde indicates that TCP is
 * preferred to UDP.
1364 1365 1366
 *
 * The "maddr" parameter determines to which address the stack binds in
 * order to listen for incoming requests. An "*" in "maddr" parameter is
1367 1368
 * shorthand for any local IP address. 0.0.0.0 means that only IPv4 sockets
 * are created. [::] means that only IPv6 sockets are created.
1369 1370 1371 1372 1373
 *
 * The "comp" parameter determines the supported compression protocol.
 * Currently only sigcomp is supported (with suitable library.
 *
 * @par Examples:
1374 1375 1376
 * @code sip:172.21.40.24;maddr=* @endcode \n
 * @code sip:172.21.40.24:50600;transport=TCP,UDP;comp=sigcomp @endcode \n
 * @code sips:* @endcode
Pekka Pessi's avatar
Pekka Pessi committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
 *
 * @return
 * On success, zero is returned. On error, -1 is returned, and @a errno is
 * set appropriately.
 */
int nta_agent_add_tport(nta_agent_t *self,
			url_string_t const *uri,
			tag_type_t tag, tag_value_t value, ...)
{
  url_t *url;
  char tp[32];
  char maddr[256];
  char comp[32];
  tp_name_t tpn[1] = {{ NULL }};
  char const * const * tports = tports_sip;
  int error;
  ta_list ta;

  if (self == NULL) {
    su_seterrno(EINVAL);
    return -1;
  }

  if (uri == NULL)
    uri = (url_string_t *)"sip:*";
  else if (url_string_p(uri) ?
	   strcmp(uri->us_str, "*") == 0 :
	   uri->us_url->url_type == url_any) {
    uri = (url_string_t *)"sip:*:*";
  }

  if (!(url = url_hdup(self->sa_home, uri->us_url)) ||
      (url->url_type != url_sip && url->url_type != url_sips)) {
    if (url_string_p(uri))
      SU_DEBUG_1(("nta: %s: invalid bind URL\n", uri->us_str));
    else
      SU_DEBUG_1(("nta: invalid bind URL\n"));
    su_seterrno(EINVAL);
    return -1;
  }

1418 1419 1420 1421
  tpn->tpn_canon = url->url_host;
  tpn->tpn_host = url->url_host;
  tpn->tpn_port = url_port(url);

Pekka Pessi's avatar
Pekka Pessi committed
1422 1423 1424
  if (url->url_type == url_sip) {
    tpn->tpn_proto = "*";
    tports = tports_sip;
1425 1426
    if (!tpn->tpn_port || !tpn->tpn_port[0]) 
      tpn->tpn_port = SIP_DEFAULT_SERV;
Pekka Pessi's avatar
Pekka Pessi committed
1427 1428 1429
  }
  else {
    assert(url->url_type == url_sips);
1430
    tpn->tpn_proto = "*";
Pekka Pessi's avatar
Pekka Pessi committed
1431
    tports = tports_sips;
1432 1433
    if (!tpn->tpn_port || !tpn->tpn_port[0]) 
      tpn->tpn_port = SIPS_DEFAULT_SERV;
Pekka Pessi's avatar
Pekka Pessi committed
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
  }

  if (url->url_params) {
    if (url_param(url->url_params, "transport", tp, sizeof(tp)) > 0) {
      if (strchr(tp, ',')) {
	int i; char *t, *tps[9];

	/* Split tp into transports */
	for (i = 0, t = tp; t && i < 8; i++) {
	  tps[i] = t;
	  if ((t = strchr(t, ',')))
	    *t++ = '\0';
	}

	tps[i] = NULL;
	tports = (char const * const *)tps;
      } else {
	tpn->tpn_proto = tp;
      }
    }
    if (url_param(url->url_params, "maddr", maddr, sizeof(maddr)) > 0)
      tpn->tpn_host = maddr;
    if (url_param(url->url_params, "comp", comp, sizeof(comp)) > 0)
      tpn->tpn_comp = comp;
1458 1459 1460 1461 1462 1463

    if (tpn->tpn_comp && 
	(nta_compressor_vtable == NULL || 
	 strcasecmp(tpn->tpn_comp, nta_compressor_vtable->ncv_name) != 0)) {
      SU_DEBUG_1(("nta(%p): comp=%s not supported for " URL_PRINT_FORMAT "\n",
		  self, tpn->tpn_comp, URL_PRINT_ARGS(url)));
Pekka Pessi's avatar
Pekka Pessi committed
1464 1465 1466 1467 1468 1469
    }
  }

  ta_start(ta, tag, value);

  if (self->sa_tports == NULL) {
Pekka Pessi's avatar
Pekka Pessi committed
1470
    if (agent_create_master_transport(self, ta_args(ta)) < 0) {
Pekka Pessi's avatar
Pekka Pessi committed
1471
      error = su_errno();
Pekka Pessi's avatar
Pekka Pessi committed
1472
      SU_DEBUG_1(("nta: cannot create master transport: %s\n",
Pekka Pessi's avatar
Pekka Pessi committed
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
		  su_strerror(error)));
      goto error;
    }
  }

  if (tport_tbind(self->sa_tports, tpn, tports, ta_tags(ta)) < 0) {
    error = su_errno();
    SU_DEBUG_1(("nta: bind(%s:%s;transport=%s%s%s%s%s): %s\n",
		tpn->tpn_canon, tpn->tpn_port, tpn->tpn_proto,
		tpn->tpn_canon != tpn->tpn_host ? ";maddr=" : "",
		tpn->tpn_canon != tpn->tpn_host ? tpn->tpn_host : "",
		tpn->tpn_comp ? ";comp=" : "",
		tpn->tpn_comp ? tpn->tpn_comp : "",
		su_strerror(error)));
    goto error;
  }
  else
    SU_DEBUG_5(("nta: bound to (%s:%s;transport=%s%s%s%s%s)\n",
		tpn->tpn_canon, tpn->tpn_port, tpn->tpn_proto,
		tpn->tpn_canon != tpn->tpn_host ? ";maddr=" : "",
		tpn->tpn_canon != tpn->tpn_host ? tpn->tpn_host : "",
		tpn->tpn_comp ? ";comp=" : "",
		tpn->tpn_comp ? tpn->tpn_comp : ""));

  /* XXX - when to use maddr? */
1498
  if ((agent_init_via(self, tport_primaries(self->sa_tports), 0)) < 0) {
Pekka Pessi's avatar
Pekka Pessi committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    error = su_errno();
    SU_DEBUG_1(("nta: cannot create Via headers\n"));
    goto error;
  }
  else
    SU_DEBUG_9(("nta: Via fields initialized\n"));

  if ((agent_init_contact(self)) < 0) {
    error = su_errno();
    SU_DEBUG_1(("nta: cannot create Contact header\n"));
    goto error;
  }
  else
    SU_DEBUG_9(("nta: Contact header created\n"));

  su_free(self->sa_home, url);
  ta_end(ta);

  return 0;

 error:
  ta_end(ta);
  su_seterrno(error);
  return -1;
}

Pekka Pessi's avatar
Pekka Pessi committed
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
static
int agent_create_master_transport(nta_agent_t *self, tagi_t *tags)
{
  self->sa_tports = 
    tport_tcreate(self, nta_agent_class, self->sa_root,
		  TPTAG_SDWN_ERROR(0),
		  TPTAG_IDLE(1800000),
		  TPTAG_DEBUG_DROP(self->sa_drop_prob),
		  TAG_NEXT(tags));

  if (!self->sa_tports)
    return -1;

  SU_DEBUG_9(("nta: master transport created\n"));

  return 0;
}

Pekka Pessi's avatar
Pekka Pessi committed
1543 1544 1545

/** Initialize Via headers. */
static
1546
int agent_init_via(nta_agent_t *self, tport_t *primaries, int use_maddr)
Pekka Pessi's avatar
Pekka Pessi committed
1547
{
Pekka Pessi's avatar
Pekka Pessi committed
1548
  sip_via_t *via = NULL, *new_via, *dup_via, *v, **vv = &via;
1549
  sip_via_t *new_vias, **next_new_via, *new_publics, **next_new_public;
Pekka Pessi's avatar
Pekka Pessi committed
1550
  tport_t *tp;
Pekka Pessi's avatar
Pekka Pessi committed
1551
  su_addrinfo_t const *ai;
Pekka Pessi's avatar
Pekka Pessi committed
1552

Pekka Pessi's avatar
Pekka Pessi committed
1553 1554 1555
  su_home_t autohome[SU_HOME_AUTO_SIZE(2048)];

  su_home_auto(autohome, sizeof autohome);
Pekka Pessi's avatar
Pekka Pessi committed
1556 1557 1558 1559 1560 1561 1562 1563 1564

  self->sa_tport_ip4 = 0;
  self->sa_tport_ip6 = 0;
  self->sa_tport_udp = 0;
  self->sa_tport_tcp = 0;
  self->sa_tport_sctp = 0;
  self->sa_tport_tls = 0;

  /* Set via fields for the tports */
1565
  for (tp = primaries; tp; tp = tport_next(tp)) {
Pekka Pessi's avatar
Pekka Pessi committed
1566
    int maddr, first_via;
Pekka Pessi's avatar
Pekka Pessi committed
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
    tp_name_t tpn[1];
    char const *comp = NULL;

    *tpn = *tport_name(tp);

    assert(tpn->tpn_proto);
    assert(tpn->tpn_canon);
    assert(tpn->tpn_host);
    assert(tpn->tpn_port);

#if 0
    if (getenv("SIP_UDP_CONNECT")
	&& strcmp(tpn->tpn_proto, "udp") == 0)
      tport_set_params(tp, TPTAG_CONNECT(1), TAG_END());
#endif

    if (tport_has_ip4(tp)) self->sa_tport_ip4 = 1;
1584 1585

#if SU_HAVE_IN6
Pekka Pessi's avatar
Pekka Pessi committed
1586
    if (tport_has_ip6(tp)) self->sa_tport_ip6 = 1;
1587
#endif
Pekka Pessi's avatar
Pekka Pessi committed
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597

    if (strcasecmp(tpn->tpn_proto, "udp") == 0)
      self->sa_tport_udp = 1;
    else if (strcasecmp(tpn->tpn_proto, "tcp") == 0)
      self->sa_tport_tcp = 1;
    else if (strcasecmp(tpn->tpn_proto, "sctp") == 0)
      self->sa_tport_sctp = 1;

    if (tport_has_tls(tp)) self->sa_tport_tls = 1;

Pekka Pessi's avatar
Pekka Pessi committed
1598
    first_via = 1;
Pekka Pessi's avatar
Pekka Pessi committed
1599

1600 1601 1602 1603 1604
    ai = tport_get_address(tp);

    for (; ai; ai = ai->ai_next) {
      char host[TPORT_HOSTPORTSIZE] = "";
      char sport[8];
Pekka Pessi's avatar
Pekka Pessi committed
1605 1606
      char const *canon = ai->ai_canonname;
      su_sockaddr_t *su = (void *)ai->ai_addr;
1607
      int port;
Pekka Pessi's avatar
Pekka Pessi committed
1608

1609 1610 1611 1612 1613 1614 1615
      if (su) {
	inet_ntop(su->su_family, SU_ADDR(su), host, sizeof host);
	maddr = use_maddr && strcasecmp(canon, host) != 0;
	port = ntohs(su->su_port);
      }
      else {
	msg_random_token(host, 16, NULL, 0);
1616 1617
	canon = strcat(host, ".is.invalid");
	maddr = 0;
1618 1619 1620
	port = 0;
      }
	
Pekka Pessi's avatar
Pekka Pessi committed
1621 1622 1623 1624
      if (strncasecmp(tpn->tpn_proto, "tls", 3)
	  ? port == SIP_DEFAULT_PORT
	  : port == SIPS_DEFAULT_PORT)
	port = 0;
Pekka Pessi's avatar
Pekka Pessi committed
1625

1626
      snprintf(sport, sizeof sport, ":%u", port);
Pekka Pessi's avatar
Pekka Pessi committed
1627 1628
      
      comp = tpn->tpn_comp;
Pekka Pessi's avatar
Pekka Pessi committed
1629

1630 1631 1632 1633 1634 1635 1636 1637
      SU_DEBUG_9(("nta: agent_init_via: "
		  "%s/%s %s%s%s%s%s%s (%s)\n",
		  SIP_VERSION_CURRENT, tpn->tpn_proto,
		  canon, port ? sport : "",
		  maddr ? ";maddr=" : "", maddr ? host : "",
		  comp ? ";comp=" : "", comp ? comp : "",
		  tpn->tpn_ident ? tpn->tpn_ident : "*"));

Pekka Pessi's avatar
Pekka Pessi committed
1638
      v = sip_via_format(autohome,
1639
			 "%s/%s %s%s%s%s%s%s",
Pekka Pessi's avatar
Pekka Pessi committed
1640
			 SIP_VERSION_CURRENT, tpn->tpn_proto,
1641
			 canon, port ? sport : "",
Pekka Pessi's avatar
Pekka Pessi committed
1642 1643
			 maddr ? ";maddr=" : "", maddr ? host : "",
			 comp ? ";comp=" : "", comp ? comp : "");
1644 1645
      if (v == NULL)
	goto error;
Pekka Pessi's avatar
Pekka Pessi committed
1646 1647

      v->v_comment = tpn->tpn_ident;
1648
      v->v_common->h_data = tp;	/* Nasty trick */
Pekka Pessi's avatar
Pekka Pessi committed
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
      *vv = v; vv = &(*vv)->v_next;
    }
  }

  /* Duplicate the list bind to the transports */
  new_via = sip_via_dup(self->sa_home, via);
  /* Duplicate the complete list shown to the application */
  dup_via = sip_via_dup(self->sa_home, via);

  if (via && (!new_via || !dup_via)) {
    msg_header_free(self->sa_home, (void *)new_via);
    msg_header_free(self->sa_home, (void *)dup_via);
1661
    goto error;
Pekka Pessi's avatar
Pekka Pessi committed
1662 1663
  }

1664 1665
  new_vias = NULL, next_new_via = &new_vias;
  new_publics = NULL, next_new_public = &new_publics;
Pekka Pessi's avatar
Pekka Pessi committed
1666 1667

  /* Set via field magic for the tports */
1668
  for (tp = primaries; tp; tp = tport_next(tp)) {
Pekka Pessi's avatar
Pekka Pessi committed
1669 1670 1671 1672 1673
    assert(via->v_common->h_data == tp);
    v = tport_magic(tp);
    tport_set_magic(tp, new_via);
    msg_header_free(self->sa_home, (void *)v);

1674 1675 1676 1677 1678
    if (tport_is_public(tp))
      *next_new_public = dup_via;
    else
      *next_new_via = dup_via;

Pekka Pessi's avatar
Pekka Pessi committed
1679
    while (via->v_next && via->v_next->v_common->h_data == tp)
1680
      via = via->v_next, new_via = new_via->v_next, dup_via = dup_via->v_next;
Pekka Pessi's avatar
Pekka Pessi committed
1681 1682
    
    via = via->v_next;
1683
    /* Break the link in via list between transports */
Pekka Pessi's avatar
Pekka Pessi committed
1684
    vv = &new_via->v_next, new_via = *vv, *vv = NULL;
1685 1686 1687 1688 1689 1690
    vv = &dup_via->v_next, dup_via = *vv, *vv = NULL;

    if (tport_is_public(tp))
      while (*next_new_public) next_new_public = &(*next_new_public)->v_next;
    else
      while (*next_new_via) next_new_via = &(*next_new_via)->v_next;
Pekka Pessi's avatar
Pekka Pessi committed
1691 1692
  }

1693 1694 1695
  assert(dup_via == NULL);
  assert(new_via == NULL);

Pekka Pessi's avatar
Pekka Pessi committed
1696 1697 1698
  if (self->sa_tport_udp)
    agent_set_udp_params(self, self->sa_udp_mtu);

1699 1700 1701 1702 1703 1704 1705 1706
  v = self->sa_vias;
  self->sa_vias = new_vias; 
  msg_header_free(self->sa_home, (void *)v);

  v = self->sa_public_vias;
  self->sa_public_vias = new_publics;
  msg_header_free(self->sa_home, (void *)v);

Pekka Pessi's avatar
Pekka Pessi committed
1707 1708
  su_home_deinit(autohome);

Pekka Pessi's avatar
Pekka Pessi committed
1709
  return 0;
1710 1711 1712 1713

 error:
  su_home_deinit(autohome);
  return -1;
Pekka Pessi's avatar
Pekka Pessi committed
1714 1715 1716
}


1717
/** Initialize main contact header. */
Pekka Pessi's avatar
Pekka Pessi committed
1718 1719 1720
static
int agent_init_contact(nta_agent_t *self)
{
1721
  sip_via_t const *v1, *v2;
1722
  char const *tp;
Pekka Pessi's avatar
Pekka Pessi committed
1723 1724 1725 1726

  if (self->sa_contact)
    return 0;

1727 1728 1729 1730 1731 1732 1733 1734
  if (self->sa_vias)
    v1 = self->sa_vias;
  else
    v1 = self->sa_public_vias;

  if (!v1)
    return -1;

1735
  tp = strrchr(v1->v_protocol, '/');
1736 1737 1738
  if (!tp++)
    return -1;

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  v2 = v1->v_next;

  if (v2 && 
      strcasecmp(v1->v_host, v2->v_host) == 0 &&
      strcasecmp(v1->v_port, v2->v_port) == 0) {
    char const *p1 = v1->v_protocol, *p2 = v2->v_protocol;

    if (strcasecmp(p1, sip_transport_udp))
      p1 = v2->v_protocol, p2 = v1->v_protocol;

    if (strcasecmp(p1, sip_transport_udp) == 0 &&
	strcasecmp(p2, sip_transport_tcp) == 0)
      /* Do not include transport if we have both UDP and TCP */
      tp = NULL;
  }
Pekka Pessi's avatar
Pekka Pessi committed
1754

1755
  self->sa_contact = 
1756
    sip_contact_create_from_via_with_transport(self->sa_home, v1, NULL, tp);
Pekka Pessi's avatar
Pekka Pessi committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767

  if (!self->sa_contact)
    return -1;

  return 0;
}

/** Return Via line corresponging to tport. */
static
sip_via_t const *agent_tport_via(tport_t *tport)
{
Pekka Pessi's avatar
Pekka Pessi committed
1768 1769 1770 1771
  sip_via_t *v = tport_magic(tport);
  while (v && v->v_next)
    v = v->v_next;
  return v;
Pekka Pessi's avatar
Pekka Pessi committed
1772 1773 1774 1775
}

/** Insert Via to a request message */
static
Pekka Pessi's avatar
Pekka Pessi committed
1776 1777
int outgoing_insert_via(nta_outgoing_t *orq, 
			sip_via_t const *via)
Pekka Pessi's avatar
Pekka Pessi committed
1778
{
Pekka Pessi's avatar
Pekka Pessi committed
1779 1780
  nta_agent_t *self = orq->orq_agent;
  msg_t *msg = orq->orq_request;
Pekka Pessi's avatar
Pekka Pessi committed
1781
  sip_t *sip = sip_object(msg);
Pekka Pessi's avatar
Pekka Pessi committed
1782 1783
  char const *branch = orq->orq_via_branch;
  int user_via = orq->orq_user_via;
Pekka Pessi's avatar
Pekka Pessi committed
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
  sip_via_t *v;
  int clear = 0;

  assert(sip); assert(via);

  if (user_via && sip->sip_via) {
    /* Use existing Via provided by application */
    v = sip->sip_via;
  }
  else if (msg && via && sip->sip_request &&
	   (v = sip_via_copy(msg_home(msg), via))) {
1795
    msg_header_insert(msg, (msg_pub_t *)sip, (msg_header_t *)v);
Pekka Pessi's avatar
Pekka Pessi committed
1796 1797 1798 1799
  }
  else
    return -1;

1800 1801 1802 1803
  if (!v->v_rport && 
      ((self->sa_rport && v->v_protocol == sip_transport_udp) ||
       (self->sa_tcp_rport && v->v_protocol == sip_transport_tcp)))
    msg_header_add_param(msg_home(msg), v->v_common, "rport");
Pekka Pessi's avatar
Pekka Pessi committed
1804

Pekka Pessi's avatar
Pekka Pessi committed
1805 1806 1807
  if (!orq->orq_tpn->tpn_comp)
    msg_header_remove_param(v->v_common, "comp");

1808 1809 1810 1811 1812 1813
  if (branch && branch != v->v_branch) {
    char const *bvalue = branch + strcspn(branch, "=");
    if (*bvalue) bvalue++;
    if (!v->v_branch || strcasecmp(bvalue, v->v_branch))
      msg_header_replace_param(msg_home(msg), v->v_common, branch);
  }
Pekka Pessi's avatar
Pekka Pessi committed
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835

  if (via->v_protocol != v->v_protocol &&
      strcasecmp(via->v_protocol, v->v_protocol))
    clear = 1, v->v_protocol = via->v_protocol;

  /* XXX - should we do this? */
  if (via->v_host != v->v_host &&
      str0cmp(via->v_host, v->v_host))
    clear = 1, v->v_host = via->v_host;

  if (via->v_port != v->v_port &&
      str0cmp(via->v_port, v->v_port))
    clear = 1, v->v_port = via->v_port;

  if (clear)
    msg_fragment_clear(v->v_common);

  return 0;
}

/** Get destination name from Via. 
 *
1836 1837 1838
 * If @a using_rport is non-null, try rport.
 * If *using_rport is non-zero, try rport even if <protocol> is not UDP.
 * If <protocol> is UDP, set *using_rport to zero.
Pekka Pessi's avatar
Pekka Pessi committed
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855
 */
static
int nta_tpn_by_via(tp_name_t *tpn, sip_via_t const *v, int *using_rport)
{
  if (!v)
    return -1;

  tpn->tpn_proto = sip_via_transport(v);
  tpn->tpn_canon = v->v_host;

  if (v->v_maddr)
    tpn->tpn_host = v->v_maddr;
  else if (v->v_received)
    tpn->tpn_host = v->v_received;
  else
    tpn->tpn_host = v->v_host;

Pekka Pessi's avatar
Pekka Pessi committed
1856
  tpn->tpn_port = sip_via_port(v, using_rport);
Pekka Pessi's avatar
Pekka Pessi committed
1857
  tpn->tpn_comp = v->v_comp;
Pekka Pessi's avatar
Pekka Pessi committed
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
  tpn->tpn_ident = NULL;

  return 0;
}

/** Get transport name from URL. */
int nta_tpn_by_url(su_home_t *home,
		   tp_name_t *tpn,
		   char const **scheme,
		   char const **port,
		   url_string_t const *us)
{
  url_t url[1];
  int n;
  char *b;

  n = url_xtra(us->us_url);
  b = su_alloc(home, n);

  if (b == NULL || url_dup(b, n, url, us->us_url) < 0) {
    su_free(home, b);
    return -1;
  }

  if (url->url_type != url_sip && 
      url->url_type != url_sips &&
      url->url_type != url_im &&
      url->url_type != url_pres) {
    su_free(home, b);
    return -1;
  }

  SU_DEBUG_7(("nta: selecting scheme %s\n", url->url_scheme));

  *scheme = url->url_scheme;
  if (strcasecmp(url->url_scheme, "sips") == 0)
    tpn->tpn_proto = "tls";
  else
    tpn->tpn_proto = "*";
  tpn->tpn_canon = url->url_host;
  tpn->tpn_host = url->url_host;

  if (url->url_params) {
    for (b = (char *)url->url_params; b[0]; b += n) {
      n = strcspn(b, ";");

      if (n > 10 && strncasecmp(b, "transport=", 10) == 0)
	tpn->tpn_proto = b + 10;
      else if (n > 5 && strncasecmp(b, "comp=", 5) == 0)
	tpn->tpn_comp = b + 5;
      else if (n > 6 && strncasecmp(b, "maddr=", 6) == 0)
	tpn->tpn_host = b + 6;

      if (b[n])
	b[n++] = '\0';
    }
  }

  if ((*port = url->url_port))
    tpn->tpn_port = url->url_port;

  tpn->tpn_ident = NULL;

  return 0;
}

/** Handle transport errors. */
static
void agent_tp_error(nta_agent_t *agent,
		    tport_t *tport,
		    int errcode,
		    char const *remote)
{
  su_llog(nta_log, 1,
	  "nta_agent: tport: %s%s%s\n",
	  remote ? remote : "", remote ? ": " : "",
	  su_strerror(errcode));
}

1937 1938 1939
/** Handle updated transport addresses */
static void agent_update_tport(nta_agent_t *self, tport_t *tport)
{
1940
  /* Initialize local Vias first */
1941 1942
  agent_init_via(self, tport_primaries(self->sa_tports), 0);

1943
  if (self->sa_update_tport) {
1944
    self->sa_update_tport(self->sa_update_magic, self);
1945 1946 1947 1948 1949 1950
  }
  else {
    /* XXX - we should do something else? */
    SU_DEBUG_3(("nta(%p): transport address updated\n", self));
  }
}
Pekka Pessi's avatar
Pekka Pessi committed
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963

/* ====================================================================== */
/* 3) Message dispatch */

static void agent_recv_request(nta_agent_t *agent,
			       msg_t *msg,
			       sip_t *sip,
			       tport_t *tport);
static int agent_check_request_via(nta_agent_t *agent,
				   msg_t *msg,
				   sip_t *sip,
				   sip_via_t *v,
				   tport_t *tport);
1964
static int agent_aliases(nta_agent_t const *, url_t [], tport_t *);
Pekka Pessi's avatar
Pekka Pessi committed
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
static void agent_recv_response(nta_agent_t*, msg_t *, sip_t *,
				sip_via_t *, tport_t*);
static void agent_recv_garbage(nta_agent_t*, msg_t*, tport_t*);


/** Handle incoming message. */
static
void agent_recv_message(nta_agent_t *agent,
			tport_t *tport,
			msg_t *msg,
			sip_via_t *tport_via,
			su_time_t now)
{
  sip_t *sip = sip_object(msg);

  agent->sa_millisec = su_time_ms(agent->sa_now = now);

  if (sip && sip->sip_request) {
    agent_recv_request(agent, msg, sip, tport);
  }
  else if (sip && sip->sip_status) {
    agent_recv_response(agent, msg, sip, tport_via, tport);
  }
  else {
    agent_recv_garbage(agent, msg, tport);
  }

  agent->sa_millisec = 0;
}

/** @internal Handle incoming requests. */
static
void agent_recv_request(nta_agent_t *agent,
			msg_t *msg,
			sip_t *sip,
			tport_t *tport)
{
  nta_leg_t *leg;
  nta_incoming_t *irq, *merge = NULL, *ack = NULL;
  sip_method_t method = sip->sip_request->rq_method;
  char const *method_name = sip->sip_request->rq_method_name;
  url_t url[1];
  unsigned cseq = sip->sip_cseq ? sip->sip_cseq->cs_seq : 0;
  int insane, errors, stream;

  agent->sa_stats->as_recv_msg++;
  agent->sa_stats->as_recv_request++;

  SU_DEBUG_5(("nta: received %s " URL_PRINT_FORMAT " %s (CSeq %u)\n",
	      method_name,
	      URL_PRINT_ARGS(sip->sip_request->rq_url),
	      sip->sip_request->rq_version, cseq));

  stream = tport_is_stream(tport);

2020
  /* Try to use compression on reverse direction if Via has comp=sigcomp  */
Pekka Pessi's avatar
Pekka Pessi committed
2021
  if (stream && 
2022
      sip->sip_via->v_comp &&
Pekka Pessi's avatar
Pekka Pessi committed
2023 2024
      tport_can_send_sigcomp(tport) &&
      tport_name(tport)->tpn_comp == NULL && 
2025 2026
      tport_has_compression(tport_parent(tport), sip->sip_via->v_comp)) {
    tport_set_compression(tport, sip->sip_via->v_comp);
Pekka Pessi's avatar
Pekka Pessi committed
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  }

  if (sip->sip_flags & MSG_FLG_TOOLARGE) {
    SU_DEBUG_5(("nta: %s (%u) is %s\n", 
		method_name, cseq, sip_413_Request_too_large));
    agent->sa_stats->as_bad_request++;
    nta_msg_treply(agent, msg, SIP_413_REQUEST_TOO_LARGE,
		   NTATAG_TPORT(tport),
		   NTATAG_INCOMPLETE(1),		   
		   TPTAG_SDWN_AFTER(stream),
		   TAG_END());
    return;
  }

  insane = 0;

  if (agent->sa_bad_req_mask)
    errors = msg_extract_errors(msg) & agent->sa_bad_req_mask;
  else
    errors = sip->sip_error != NULL;

  if (errors ||
      (sip->sip_flags & MSG_FLG_ERROR) /* Fatal error */ || 
      (insane = (sip_sanity_check(sip) < 0))) {
    sip_header_t const *h;
    char const *badname = NULL, *phrase;
    
    agent->sa_stats->as_bad_message++;
    agent->sa_stats->as_bad_request++;

    if (insane)
      SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq,
		  "failed sanity check"));

    for (h = (sip_header_t const *)sip->sip_error; h; h = h->sh_next) {
      char const *bad;

      if (h->sh_class == sip_error_class)
	bad = h->sh_error->er_name;
      else 
	bad = h->sh_class->hc_name;

      if (bad)
	SU_DEBUG_5(("nta: %s has bad %s header\n", method_name, bad));
      
      if (!badname)
	badname = bad;
    }

    if (sip->sip_via && method != sip_method_ack) {
      msg_t *reply = nta_msg_create(agent, 0);
      
      if (reply) {
	agent_check_request_via(agent, msg, sip, sip->sip_via, tport);

	if (badname)
	  phrase = su_sprintf(msg_home(reply), "Bad %s Header", badname);
	else
	  phrase = sip_400_Bad_request;

	SU_DEBUG_5(("nta: %s (%u) is %s\n", method_name, cseq, phrase));
	
2089 2090 2091 2092 2093 2094 2095
	nta_msg_mreply(agent, reply, sip_object(reply),
		       400, phrase,
		       msg,
		       NTATAG_TPORT(tport), 
		       NTATAG_INCOMPLETE(1), 
		       TPTAG_SDWN_AFTER(stream),
		       TAG_END());
Pekka Pessi's avatar
Pekka Pessi committed
2096 2097
      }
    } else {
2098
      msg_destroy(msg);
Pekka Pessi's avatar
Pekka Pessi committed
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
      if (stream)		/* Send FIN */
	tport_shutdown(tport, 1);
    }

    return;
  }

  if (str0casecmp(sip->sip_request->rq_version, sip_version_2_0) != 0) {
    agent->sa_stats->as_bad_request++;
    agent->sa_stats->as_bad_message++;

    SU_DEBUG_5(("nta: bad version %s for %s (%u)\n",
		sip->sip_request->rq_version, method_name, cseq));

    nta_msg_treply(agent, msg, SIP_505_VERSION_NOT_SUPPORTED,
		   NTATAG_TPORT(tport), 
		   TPTAG_SDWN_AFTER(stream),
		   TAG_END());

    return;
  }

  if (agent_check_request_via(agent, msg, sip, sip->sip_via, tport) < 0) {
    agent->sa_stats->as_bad_message++;
    agent->sa_stats->as_bad_request++;
    SU_DEBUG_5(("nta: %s (%u) %s\n", method_name, cseq, "has invalid Via"));
    msg_destroy(msg);
    return;
  }

  /* First, try existing incoming requests */
  irq = incoming_find(agent, sip, sip->sip_via, &merge, &ack);
  if (irq) {
    /* Match - this is a retransmission */
    SU_DEBUG_5(("nta: %s (%u) going to existing %s transaction\n",
		method_name, cseq, irq->irq_rq->rq_method_name));
    if (incoming_recv(irq, msg, sip, tport) >= 0)
      return;
  }
  else if (ack) {
    /* Match - this is an ACK or CANCEL or PRACK */
    SU_DEBUG_5(("nta: %s (%u) is going to %s (%u)\n",
		method_name, cseq,
		ack->irq_rq->rq_method_name, ack->irq_cseq->cs_seq));
    if (method == sip_method_ack) {
      if (incoming_ack(ack, msg, sip, tport) >= 0)
	return;
    }
    else if (method == sip_method_cancel) {
      if (incoming_cancel(ack, msg, sip, tport) >= 0)
	return;
    }
    else if (method == sip_method_prack) {
      if (reliable_recv(ack, msg, sip, tport) >= 0)
	return;
    }
    else {
      assert(!method);
    }
  }
  else if (merge) {
    SU_DEBUG_5(("nta: %s (%u) %s\n",
		method_name, cseq, "is a merged request"));
    if (incoming_merge(merge, msg, sip, tport) >= 0)
      return;
  }

  *url = *sip->sip_request->rq_url;
  url->url_params = NULL;
  agent_aliases(agent, url, tport); /* canonize urls */

  if ((leg = leg_find(agent, 
		      method_name, url, 
		      sip->sip_call_id,
		      sip->sip_from->a_tag, sip->sip_from->a_url, 
		      sip->sip_to->a_tag, sip->sip_to->a_url))) {
    /* Try existing dialog */
    SU_DEBUG_5(("nta: %s (%u) %s\n",
		method_name, cseq, "going to existing leg"));
    leg_recv(leg, msg, sip, tport);
    return;
  }
  else if (!agent->sa_is_stateless &&
	   (leg = dst_find(agent, url, method_name))) {
    /* Dialogless legs - let application process transactions statefully */
    SU_DEBUG_5(("nta: %s (%u) %s\n",
		method_name, cseq, "going to a dialogless leg"));
    leg_recv(leg, msg, sip, tport);
  }
  else if (!agent->sa_is_stateless && (leg = agent->sa_default_leg)) {
    SU_DEBUG_5(("nta: %s (%u) %s\n",
		method_name, cseq, "going to a default leg"));
    leg_recv(leg, msg, sip, tport);
  }
  else if (agent->sa_callback) {
    /* Stateless processing for request */
    agent->sa_stats->as_trless_request++;
    SU_DEBUG_5(("nta: %s (%u) %s\n", 
		method_name, cseq, "to message callback"));
    (void)agent->sa_callback(agent->sa_magic, agent, msg, sip);
  }
  else {
    agent->sa_stats->as_trless_request++;
    SU_DEBUG_5(("nta: %s (%u) no place to go: %d %s\n",
		method_name, cseq, SIP_501_NOT_IMPLEMENTED));
    if (method != sip_method_ack)
      nta_msg_treply(agent,