tport.c 170 KB
Newer Older
Pekka Pessi's avatar
Pekka Pessi committed
1 2 3 4 5 6 7
/*
 * This file is part of the Sofia-SIP package
 *
 * Copyright (C) 2005 Nokia Corporation.
 *
 * Contact: Pekka Pessi <pekka.pessi@nokia.com>
 *
8
 * This library is free software; you can redistribute it and/or
Pekka Pessi's avatar
Pekka Pessi committed
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 36 37 38 39 40 41 42 43 44 45 46 47
 * 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 tport.c Transport interface implementation.
 *
 * See tport.docs for more detailed description of tport interface.
 *
 * @author Pekka Pessi <Pekka.Pessi@nokia.com>
 * @author Ismo Puustinen <Ismo.H.Puustinen@nokia.com>
 * @author Tat Chan <Tat.Chan@nokia.com>
 * @author Kai Vehmanen <kai.vehmanen@nokia.com>
 *
 * @date Created: Thu Jul 20 12:54:32 2000 ppessi
 */

#include "config.h"

#include <string0.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>

#include <su.h>

48
#if HAVE_NETINET_TCP_H
Pekka Pessi's avatar
Pekka Pessi committed
49
#include <netinet/tcp.h>
50
#endif
Pekka Pessi's avatar
Pekka Pessi committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

#ifndef SU_DEBUG
#define SU_DEBUG 3
#endif

#define SU_LOG   tport_log

#include <su_debug.h>
#include <su_alloc.h>
#include <su_tagarg.h>

#include <su_localinfo.h>

#ifndef NONE
#define NONE ((void *)-1)
#endif

typedef struct tport_master tport_master_t;
typedef struct tport_nat_s tport_nat_t;

#define SU_WAKEUP_ARG_T struct tport_s
#define SU_TIMER_ARG_T struct tport_master
#define SU_ROOT_MAGIC_T struct tport_threadpool
#define SU_MSG_ARG_T union tport_su_msg_arg

#include <su_wait.h>

#include <msg.h>
#include <msg_addr.h>

#if HAVE_IP_RECVERR || HAVE_IPV6_RECVERR
#include <linux/types.h>
#include <linux/errqueue.h>
#include <sys/uio.h>
#endif

#if HAVE_SCTP && HAVE_NETINET_SCTP_H
#include <netinet/sctp.h>
#endif

#if HAVE_TLS
#include "tport_tls.h"
#else
typedef struct _tls_t tls_t;	/* dummy */
#endif

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

#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif

#ifndef IPPROTO_SCTP
#define IPPROTO_SCTP (132)
#endif

#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL (0)
#endif

#if HAVE_SOFIA_STUN
#include "stun.h"
#endif

#if HAVE_UPNP
#include "upnp_wrapper.h"
#endif

#include "tport.h"
#include "su_uniqueid.h"
#include <rbtree.h>

#if HAVE_FUNC
#elif HAVE_FUNCTION
#define __func__ __FUNCTION__
#else
char const __func__[] = "tport";
#endif

typedef struct tport_pending_s tport_pending_t;
typedef struct tport_threadpool tport_threadpool_t;
typedef struct tport_sigcomp_handler tport_sigcomp_handler_t;
typedef struct tport_sigcomp tport_sigcomp_t;
typedef struct tport_primary tport_primary_t;

struct sigcomp_state_handler;
struct sigcomp_algorithm;
struct sigcomp_udvm;
struct sigcomp_magic;

#if HAVE_SIGCOMP

/** Per-socket SigComp data */
struct tport_sigcomp {
  struct sigcomp_udvm          *sc_udvm;
  struct sigcomp_compartment   *sc_cc;
  struct sigcomp_compressor    *sc_compressor;
  struct sigcomp_buffer        *sc_output;
  unsigned                      sc_compressed; 

  struct sigcomp_buffer        *sc_input;
  unsigned                      sc_copied;
  
  enum {
    format_is_unknown,
    format_is_sigcomp,
    format_is_noncomp
  } sc_infmt, sc_outfmt;
};

#endif

/** Transport parameters */
typedef struct {
  unsigned tpp_mtu;		/**< Maximum packet size */
  unsigned tpp_idle;		/**< Allowed connection idle time. */
  unsigned tpp_timeout;		/**< Allowed idle time for message. */
  unsigned tpp_sigcomp_lifetime;  /**< SigComp compartment lifetime  */
  unsigned tpp_thrpsize;	/**< Size of thread pool */

  unsigned tpp_thrprqsize;	/**< Length of per-thread recv queue */
  unsigned tpp_qsize;		/**< Size of queue */

  unsigned tpp_drop;		/**< Packet drop probablity */

  unsigned tpp_conn_orient:1;   /**< Connection-orienteded */
  unsigned tpp_sdwn_error:1;	/**< If true, shutdown is error. */
  unsigned :0;

} tport_params_t;


/** Transport object.
 *
 * A transport object can be used in three roles, to represent transport
 * list (aka master transport), to represent available transports (aka
 * primary transport) and to represent actual transport connections (aka
 * secondary transport).
 */
struct tport_s {
  su_home_t           tp_home[1];       /**< Memory home */

  int                 tp_refs;		/**< Number of references to tport */

  tport_t *tp_left, *tp_right, *tp_dad; /**< Links in tport tree */

  tport_master_t     *tp_master;        /**< Master transport */
  tport_primary_t    *tp_pri;           /**< Primary transport */

  tport_params_t     *tp_params;        /**< Transport parameters */

  tp_magic_t         *tp_magic; 	/**< Context provided by consumer */

  unsigned            tp_black:1;       /**< Used by red-black-tree */

  unsigned            tp_conn_orient:1;	/**< Is connection-oriented */
  unsigned            tp_connected : 1;	/**< Has real connection */
  unsigned            tp_reusable:1;    /**< Can this connection be reused */
  unsigned            tp_closed : 1;    /**< This transport is closed */
  unsigned            tp_recv_close:1;  /**< Remote end has sent FIN */
  /** We will send FIN (1) or have sent FIN (2) */
  unsigned            tp_send_close:2; 

  unsigned:0;

  msg_t const        *tp_rlogged;       /**< Last logged when receiving */
  msg_t const        *tp_slogged;       /**< Last logged when sending */

  unsigned            tp_time;	        /**< When this transport was last used */

  tp_name_t           tp_name[1];	/**< Transport name.
					 * 
					 * This is either our name (if primary)
					 * or peer name (if secondary).
					 */

#define tp_protoname tp_name->tpn_proto
#define tp_canon     tp_name->tpn_canon
#define tp_host      tp_name->tpn_host
#define tp_port      tp_name->tpn_port
#define tp_ident     tp_name->tpn_ident

  su_socket_t  	      tp_socket;	/**< Socket of this tport*/
  int                 tp_index;		/**< Root registration index */
  int                 tp_events;        /**< Subscribed events */
  int                 tp_addrlen;       /**< Size fo tp_addr */
  su_sockaddr_t       tp_addr[1];	/**< Peer address */

#if HAVE_TLS
  tls_t              *tp_tls;
  char               *tp_tls_buffer;    /**< 2k Buffer  */
#endif

#if HAVE_SIGCOMP
  tport_sigcomp_t     tp_sigcomp[1];
#endif  

#if HAVE_SOFIA_STUN
  stun_socket_t      *tp_stun_socket;
#endif

  /* ==== Receive queue ================================================== */

  msg_t   	     *tp_msg;		/**< Message being received */

  /* ==== Pending messages =============================================== */

  tport_pending_t    *tp_pending;       /**< Pending requests */
  tport_pending_t    *tp_released;      /**< Released pends */
  unsigned            tp_plen;          /**< Size of tp_pending */
  unsigned            tp_pused;         /**< Used pends */
  unsigned            tp_reported;      /**< Report counter */

  /* ==== Send queue ===================================================== */

  msg_t             **tp_queue;		/**< Messages being sent */
  unsigned short      tp_qhead;		/**< Head of queue */

  msg_iovec_t        *tp_unsent;	/**< Pointer to first unsent iovec */
  unsigned            tp_unsentlen;	/**< Number of unsent iovecs */

  msg_iovec_t        *tp_iov;		/**< Iovecs allocated for sending */
  unsigned            tp_iovlen;	/**< Number of allocated iovecs */

  /* ==== Statistics  ===================================================== */
  
  struct {
    uint64_t sent_bytes, sent_on_line, recv_bytes, recv_on_line;
    uint64_t sent_msgs, recv_msgs;
  } tp_stats;
};

/** Primary structure */
struct tport_primary {
  tport_t             pri_primary[1];   /**< Transport part */
#if DOX
  su_home_t           pri_home[1];
  tport_t           **pri_stail;	/**< End of secondary list */
#else
#define pri_home      pri_primary->tp_home
#define pri_master    pri_primary->tp_master
#define pri_protoname pri_primary->tp_name->tpn_proto
#endif

  char                pri_ident[16];
  tport_primary_t    *pri_next;	        /**< Next primary tport */

  tport_t            *pri_secondary;	/**< Secondary tports */

  tport_threadpool_t *pri_threadpool;   /**< Worker threads */
  unsigned            pri_thrpsize;
  unsigned            pri_family : 8;   /**< Network family (INET/INET6) */
  unsigned            pri_socktype : 8; /**< Socket type  */
  unsigned            pri_protocol : 8;	/**< IP protocol number  */

  unsigned            pri_natted:1;	/**< Using natted address  */

  unsigned:0;

  tport_params_t      pri_params[1];      /**< Transport parameters */

};

/** Master structure */
struct tport_master {
  tport_t             mr_master[1];
#if DOX
  su_home_t           mr_home[1];
#else
#define mr_home mr_master->tp_home
#endif

  tp_stack_t  	     *mr_stack;        /**< Transport consumer */
  tp_stack_class_t 
               const *mr_tpac;		/**< Methods provided by stack */
  int                 mr_log;	/**< Log message contents? */
#define mr_msg_flags  mr_log	/**< Flags used by msg_t creation */
  su_root_t    	     *mr_root;		/**< SU root pointer */

  /**< Timer reclaiming unused connections and compartment */
  su_timer_t         *mr_timer;		
  /** File to dump received and sent data */
  FILE               *mr_dump_file;	

  tport_primary_t    *mr_primaries;     /**< List of primary contacts */

  tport_params_t      mr_params[1];
  
  unsigned            mr_boundserver:1; /**< Server has been bound */
  unsigned            mr_bindv6only:1; /**< We can bind separately to IPv6/4 */
  unsigned :0;

#if HAVE_SIGCOMP
  struct sigcomp_compartment   *mr_compartment;
#endif

  /* Delivery context */
  struct tport_delivery {
    tport_t              *d_tport;
    msg_t                *d_msg;
    tp_name_t             d_from[1];
    struct sigcomp_udvm **d_udvm;
  } mr_delivery[1];

  struct tport_nat_s {
    int initialized;
    int bound;
    int stun_enabled;
    char *external_ip_address;
#if HAVE_UPNP || HAVE_SOFIA_STUN
    int try_stun;
#endif
#if HAVE_UPNP
#endif
367
#if HAVE_SOFIA_STUN
Pekka Pessi's avatar
Pekka Pessi committed
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 546 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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    char *stun_server;
    stun_socket_t *stun_socket;
    stun_engine_t *stun;
#endif
  }                   mr_nat[1];
};

#define STACK_RECV(tp, msg, now)		       \
  (tp)->tp_master->mr_tpac->tpac_recv((tp)->tp_master->mr_stack, (tp), \
				      (msg), (tp)->tp_magic, (now))

#define STACK_ERROR(tp, errcode, dstname) \
  (tp)->tp_master->mr_tpac->tpac_error((tp)->tp_master->mr_stack, (tp), \
				       (errcode), (dstname))

#define STACK_SIGCOMP_ACCEPT(tp, msg)				  \
  (tp)->tp_master->mr_tpac->					  \
  tpac_sigcomp_accept((tp)->tp_master->mr_stack, (tp), (msg))

#define TP_STACK   tp_master->mr_stack

#define TP_SCTP_MSG_MAX (32768)

/* These should not overlap with existing AI flags. */
#define TP_AI_COMPRESSED 0x0010
/* Halfclose (shutdown(c, 1)) connection after sending message */
#define TP_AI_SHUTDOWN   0x0020
/* Close connection (shutdown(c, 2)) after sending message */
#define TP_AI_CLOSE      0x0020

/* Address was inaddr_any */
#define TP_AI_ANY        0x0040

typedef long unsigned LU; 	/* for printf() and friends */

char const tport_sigcomp_name[] = "sigcomp";

#if HAVE_SIGCOMP
static inline
int msg_is_compressed(msg_t *msg)
{
  return msg && 
    (msg_addrinfo(msg)->ai_flags & TP_AI_COMPRESSED) == TP_AI_COMPRESSED;
}

static inline
void msg_mark_as_compressed(msg_t *msg)
{
  if (msg)
    msg_addrinfo(msg)->ai_flags |= TP_AI_COMPRESSED;
}

static struct sigcomp_udvm *tport_init_udvm(tport_t *self);
static int tport_recv_sigcomp_r(tport_t *, msg_t **, struct sigcomp_udvm *);
static struct sigcomp_compartment *tport_primary_compartment(tport_master_t *);
static inline void tport_try_accept_sigcomp(tport_t *self, msg_t *msg);

static
char const *tport_canonize_comp(char const *comp)
{
  if (comp && strcasecmp(comp, tport_sigcomp_name) == 0)
    return tport_sigcomp_name;
  return NULL;
}

/** Check if transport can receive compressed messages */
int tport_can_recv_sigcomp(tport_t const *self)
{
  return self && self->tp_sigcomp->sc_infmt != format_is_noncomp;
}

/** Check if transport can send compressed messages */
int tport_can_send_sigcomp(tport_t const *self)
{
  return self && self->tp_sigcomp->sc_outfmt != format_is_noncomp;
}

/** Check if transport supports sigcomp */
int tport_has_compression(tport_t const *self, char const *comp)
{
  return
    self && comp && 
    self->tp_name->tpn_comp == tport_canonize_comp(comp);
}

/** Set/reset compression */
int tport_set_compression(tport_t *self, char const *comp)
{
  if (self == NULL)
    ;
  else if (comp == NULL) {
    if (self->tp_sigcomp->sc_outfmt != format_is_sigcomp) {
      self->tp_name->tpn_comp = NULL;
      return 0;
    }
  }
  else {
    comp = tport_canonize_comp(comp);

    if (comp && self->tp_sigcomp->sc_outfmt != format_is_noncomp) {
      self->tp_name->tpn_comp = comp;
      return 0;
    }
  }
  
  return -1;
}
#else

#define tport_try_accept_sigcomp(self, msg) ((void)0)
#define tport_canonize_comp(comp) ((void *)0)

int tport_can_recv_sigcomp(tport_t const *self)
{
  return 0;
}

int tport_can_send_sigcomp(tport_t const *self)
{
  return 0;
}

int tport_has_compression(tport_t const *self, char const *comp)
{
  return 0;
}

int tport_set_compression(tport_t *self, char const *comp)
{
  return (self == NULL || comp) ? -1 : 0;
}
#endif

/* Define macros for rbtree implementation */
#define TP_LEFT(tp) ((tp)->tp_left)
#define TP_RIGHT(tp) ((tp)->tp_right)
#define TP_PARENT(tp) ((tp)->tp_dad)
#define TP_SET_RED(tp) ((tp)->tp_black = 0)
#define TP_SET_BLACK(tp) ((tp)->tp_black = 1)
#define TP_IS_RED(tp) ((tp) && (tp)->tp_black == 0)
#define TP_IS_BLACK(tp) (!(tp) || (tp)->tp_black == 1)
#define TP_COPY_COLOR(dst, src) ((dst)->tp_black = (src)->tp_black)
#define TP_INSERT(tp) ((void)0)
#define TP_REMOVE(tp) ((tp)->tp_left = (tp)->tp_right = (tp)->tp_dad = NULL)

static inline int tp_cmp(tport_t const *a, tport_t const *b)
{
  if (a == b)
    return 0;
  
  if (a->tp_addrlen != b->tp_addrlen)
    return a->tp_addrlen - b->tp_addrlen;

  return memcmp(a->tp_addr, b->tp_addr, sizeof(a->tp_addr));
}

static inline int tprb_is_inserted(tport_t const *a)
{
  return a->tp_dad != 0 || a->tp_left != 0 || a->tp_right != 0;
}

RBTREE_PROTOS(static inline, tprb, tport_t);

RBTREE_BODIES(static inline, tprb, tport_t, 
	      TP_LEFT, TP_RIGHT, TP_PARENT,
	      TP_IS_RED, TP_SET_RED, TP_IS_BLACK, TP_SET_BLACK, TP_COPY_COLOR,
	      tp_cmp, TP_INSERT, TP_REMOVE);

enum {
  /** Default per-thread read queue length */
  THRP_PENDING = 8
};

struct tport_pending_s {
  //  tport_pending_t       *p_left, *p_right, *p_parent;
  void               *p_client;
  tport_pending_error_f *p_callback;
  msg_t              *p_msg;
  int                 p_reported;
};

/** Return true if transport is master. */
inline int tport_is_master(tport_t const *self)
{
  return 
    self && 
    self->tp_master->mr_master == self;
}

/** Return true if transport is primary. */
inline int tport_is_primary(tport_t const *self)
{
  return 
    self && 
    self->tp_pri->pri_primary == self;
}

/** Return true if transport is secondary. */
inline int tport_is_secondary(tport_t const *self)
{
  return 
    self && 
    self->tp_master->mr_master != self && 
    self->tp_pri->pri_primary != self;
}

/** Test if transport has been registered */
static inline int tport_is_registered(tport_t const *self)
{
  return self->tp_index != 0;
}

/** Test if transport is stream. */
inline int tport_is_stream(tport_t const *self)
{
  return self->tp_pri->pri_socktype == SOCK_STREAM;
}
 
/** Test if transport is dgram. */
static inline int tport_is_dgram(tport_t const *self)
{
  return self->tp_pri->pri_socktype == SOCK_DGRAM;
}
 
/** Test if transport is udp. */
inline int tport_is_udp(tport_t const *self)
{
  return self->tp_pri->pri_protocol == IPPROTO_UDP;
}
 
/** Test if transport is tcp. */
inline int tport_is_tcp(tport_t const *self)
{
  return self->tp_pri->pri_protocol == IPPROTO_TCP;
}
 
/** Test if transport is needs connect() before sending. */
static inline int tport_is_connection_oriented(tport_t const *self)
{
  return self->tp_conn_orient;
}

/** Test if transport has actual connection. */
static inline int tport_is_connected(tport_t const *self)
{
  return self->tp_connected;
}

/** Return 1 if transport is reliable, 0 otherwise.
 *
 * (Note that this is part of external API).
 */
620
int tport_is_reliable(tport_t const *self)
Pekka Pessi's avatar
Pekka Pessi committed
621 622 623 624 625 626 627 628
{
  return self != NULL && 
    (self->tp_pri->pri_socktype == SOCK_STREAM || 
     self->tp_pri->pri_socktype == SOCK_SEQPACKET);
}


/** Return true if transport supports IPv4 */
629
int tport_has_ip4(tport_t const *self)
Pekka Pessi's avatar
Pekka Pessi committed
630 631 632 633 634 635 636 637
{
  return self && 
    (self->tp_pri->pri_family == 0 || 
     self->tp_pri->pri_family == AF_INET 
     /* || self->tp_pri->pri_family2 == AF_INET */);
}

/** Return true if transport supports IPv6 */
638
int tport_has_ip6(tport_t const *self)
Pekka Pessi's avatar
Pekka Pessi committed
639 640 641 642 643 644
{
  return self && 
    (self->tp_pri->pri_family == 0 || self->tp_pri->pri_family == AF_INET6);
}

/** Return true if transport supports TLS. */
645
int tport_has_tls(tport_t const *self)
Pekka Pessi's avatar
Pekka Pessi committed
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
{
#if HAVE_TLS
  return self && self->tp_tls != NULL;
#else
  return 0;
#endif  
}

/** Test if transport has been closed */
static inline int tport_is_closed(tport_t const *self)
{
  return self->tp_closed;
}

/** Test if transport has been shut down */
static inline int tport_is_shutdown(tport_t const *self)
{
  return self->tp_closed || self->tp_send_close || self->tp_recv_close;
}


/** Test if transport is bound */
static inline int tport_is_bound(tport_t const *self)
{
  return self->tp_protoname != NULL;
}

/** MTU for transport  */
static inline unsigned tport_mtu(tport_t const *self)
{
  return self->tp_params->tpp_mtu;
}

static inline
int tport_has_sigcomp(tport_t const *self)
{
  return self->tp_name->tpn_comp != NULL;
}

685
static
Pekka Pessi's avatar
Pekka Pessi committed
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 713 714 715 716 717 718 719 720 721 722 723 724
int tport_events(tport_t const *self)
{
  int events = self->tp_events;

#if HAVE_TLS
  if (self->tp_tls) {
    events = tls_events(self->tp_tls, events);

    SU_DEBUG_7(("tport_events(%p): logical events%s%s%s%s real%s%s%s%s\n",
		self, (self->tp_events & SU_WAIT_IN) ? " IN" : "",
		(self->tp_events & SU_WAIT_OUT) ? " OUT" : "",
		(self->tp_events & SU_WAIT_HUP) ? " HUP" : "",
		(self->tp_events & SU_WAIT_ERR) ? " ERR" : "",
		(events & SU_WAIT_IN) ? " IN" : "",
		(events & SU_WAIT_OUT) ? " OUT" : "",
		(events & SU_WAIT_HUP) ? " HUP" : "",
		(events & SU_WAIT_ERR) ? " ERR" : ""));
  }
  else
#endif
    SU_DEBUG_7(("tport_events(%p): events%s%s%s%s\n", self,
		(events & SU_WAIT_IN) ? " IN" : "",
		(events & SU_WAIT_OUT) ? " OUT" : "",
		(events & SU_WAIT_HUP) ? " HUP" : "",
		(events & SU_WAIT_ERR) ? " ERR" : ""));
		
  return
    su_root_eventmask(self->tp_master->mr_root, 
		      self->tp_index, 
		      self->tp_socket, 
		      events);
}

/* NAT things */

static
struct tport_nat_s *
tport_nat_initialize_nat_traversal(tport_master_t *mr, 
				   tp_name_t const *tpn,
725 726
				   char const * const **return_transports,
				   tagi_t const *tags);
Pekka Pessi's avatar
Pekka Pessi committed
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 762 763 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 821 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 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 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 914 915 916 917 918 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 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 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 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 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 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

static
char *tport_nat_get_external_ip_address(struct tport_nat_s *nat);


#if HAVE_SOFIA_STUN
static
int tport_nat_stun_bind(struct tport_nat_s *nat,
			su_sockaddr_t su[1],
			socklen_t *sulen,
			su_socket_t s);
#endif

static
int tport_nat_traverse_nat(tport_master_t *, 
			   su_sockaddr_t su[1],
			   su_addrinfo_t const *ai,
			   su_socket_t s);

static
int tport_nat_set_canon(tport_t *self, struct tport_nat_s *nat);

static
int tport_nat_finish(tport_primary_t *self);

#define PASSIVE PASSIVE
#define ACTIVE  ACTIVE
enum socket_open { PASSIVE = 0, ACTIVE = 1 };

static 
tport_t *tport_connect(tport_primary_t *pri, su_addrinfo_t *ai, 
		       tp_name_t const *tpn);

static int tport_get_local_addrinfo(tport_master_t *mr, 
				    su_localinfo_t *li,
				    char const *port,
				    su_addrinfo_t const *hints,
				    su_addrinfo_t **return_ai);

static void tport_freeaddrinfo(tport_master_t *mr, su_addrinfo_t *ai);

#if HAVE_TLS
static tls_t *tport_init_tls(tagi_t *tags);
#endif

static int
  tport_bind_client(tport_master_t *self, tp_name_t const *tpn, 
		    char const * const transports[], tagi_t *tags),
  tport_bind_server(tport_master_t *, tp_name_t const *tpn, 
		    char const * const transports[], tagi_t *tags),

  tport_init_compression(tport_primary_t *self, char const *compression, 
			 tagi_t *tl),

  tport_setname(tport_t *, char const *, su_sockaddr_t const *, char const *),
  tport_recv(su_root_magic_t *m, su_wait_t *w, tport_t *self),
  tport_accept(su_root_magic_t *m, su_wait_t *w, tport_t *self),
  tport_resolve(tport_t *self, msg_t *msg, tp_name_t const *tpn),
  tport_send_msg(tport_t *, msg_t *, tp_name_t const *tpn,
		 struct sigcomp_compartment *cc),
  tport_vsend(tport_t *self, msg_t *msg, tp_name_t const *tpn,
	      msg_iovec_t iov[], int iovused,
	      struct sigcomp_compartment *cc),
  tport_vsend_iovec(tport_t const *, msg_t *, msg_iovec_t iov[], int iovused),
  tport_send_error(tport_t *, msg_t *, tp_name_t const *, char const *comp),
  tport_queue(tport_t *self, msg_t *msg),
  tport_queue_rest(tport_t *self, msg_t *msg, msg_iovec_t iov[], int iovused),
  tport_pending_error(tport_t *self, su_sockaddr_t const *dst, int error),
  tport_pending_errmsg(tport_t *self, msg_t *msg, int error),
  tport_launch_threadpool(tport_primary_t *pri),
  tport_kill_threadpool(tport_primary_t *pri),
  tport_thread_send(tport_t *, struct sigcomp_compartment *, 
		    msg_t *, unsigned mtu);

tport_t *tport_by_addrinfo(tport_primary_t const *pri,
			   su_addrinfo_t const *ai,
			   tp_name_t const *tpn);

void tport_peer_address(tport_t *self, msg_t *msg);
static unsigned long tport_now(void);
static void tport_tick(su_root_magic_t *, su_timer_t *, tport_master_t *mr);

#if HAVE_TLS
static int
  tport_tls_event(tport_t *self, int events),
  tport_tls_writevec(tport_t *self, msg_iovec_t iov[], int iovlen);
#endif

#if HAVE_SIGCOMP
static int 
tport_sigcomp_vsend(tport_t const *self, 
		    msg_t *msg, msg_iovec_t iov[], int iovused,
		    struct sigcomp_compartment *cc, tport_sigcomp_t *sc);
#endif 

static void
  tport_error_event(tport_t *self, int events),
  tport_send_event(tport_t *self, int events), 
  tport_hup_event(tport_t *self, int events),
  tport_recv_event(tport_t *self, int events);

static void tport_parse(tport_t *self, int complete, su_time_t now);
static void tport_deliver(tport_t *, msg_t *msg, msg_t *next,
			  struct sigcomp_udvm **udvm, su_time_t now);

static tport_primary_t *tport_alloc_primary(tport_master_t *tpm);
static tport_primary_t *tport_listen(tport_master_t *mr, 
				     su_addrinfo_t const *ai, 
				     char const *canon, char const *protoname,
				     int port,
				     tagi_t *tags);

static void tport_zap_primary(tport_primary_t *);

static tport_t *tport_alloc_secondary(tport_primary_t *pri);
static void tport_zap_secondary(tport_t *);

static void tport_close(tport_t *self);

static void tport_open_log(tport_master_t *mr, tagi_t *tags);
static void tport_dump_iovec(tport_t const *self, msg_t *msg, int n,
			     su_iovec_t const iov[], int iovused,
			     char const *what, char const *how);
static void tport_log_msg(tport_t *tp, msg_t *msg, char const *what, 
			  char const *via, char const *indent, su_time_t now);
static void tport_stamp(tport_t const *tp, msg_t *msg, char stamp[128], 
			char const *what, int n, char const *via,
			su_time_t now);

static char *localipname(int pf, char *buf, int bufsiz);
static void tport_error_report(tport_t *self, int errcode, 
			       su_sockaddr_t const *dst);
static int getprotohints(su_addrinfo_t *hints,
			 char const *proto, int flags);

static void tport_send_queue(tport_t *self);


/* Stack class used when transports are being destroyed */
static
void tport_destroy_recv(tp_stack_t *stack, tport_t *tp, 
			msg_t *msg, tp_magic_t *magic, 
			su_time_t received)
{
  msg_destroy(msg);
}

static
void tport_destroy_error(tp_stack_t *stack, tport_t *tp, 
			 int errcode, char const *remote)
{
}

static
msg_t *tport_destroy_alloc(tp_stack_t *stack, int flags, 
			   char const data[], unsigned len,
			   tport_t const *tp,
			   tp_client_t *tpc)
{
  return NULL;
}

/**@var TPORT_LOG
 *
 * Environment variable determining if parsed message contents are logged.
 *
 * If the TPORT_LOG environment variable is set, the tport module logs the
 * contents of parsed messages. This eases debugging the signaling greatly.
 * 
 * @sa TPORT_DUMP, TPORT_DEBUG, tport_log
 */
extern char const TPORT_LOG[];	/* dummy declaration for Doxygen */

/**@var TPORT_DUMP
 *
 * Environment variable for transport data dump.
 *
 * The received and sent data is dumped to the file specified by TPORT_DUMP
 * environment variable. This can be used to save message traces and help
 * hairy debugging tasks.
 * 
 * @sa TPORT_LOG, TPORT_DEBUG, tport_log
 */
extern char const TPORT_DUMP[];	/* dummy declaration for Doxygen */

/**@var TPORT_DEBUG
 *
 * Environment variable determining the debug log level for @b tport module.
 *
 * The TPORT_DEBUG environment variable is used to determine the debug logging
 * level for @b tport module. The default level is 3.
 * 
 * @sa <su_debug.h>, tport_log, SOFIA_DEBUG
 */
extern char const TPORT_DEBUG[]; /* dummy declaration for Doxygen */

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

/** Name for "any" transport. @internal */
static char const tpn_any[] = "*";

/** Create the master transport. @deprecated Use tport_tcreate(). */
tport_t *tport_create(tp_stack_t *stack,
		      tp_stack_class_t const *tpac,
		      su_root_t *root)
{
  return tport_tcreate(stack, tpac, root, TAG_END());
}

/** Create the master transport. */
tport_t *tport_tcreate(tp_stack_t *stack,
		       tp_stack_class_t const *tpac,
		       su_root_t *root, 
		       tag_type_t tag, tag_value_t value, ...)
{
  tport_master_t *mr;
  tp_name_t *tpn;
  tport_params_t *tpp;
  unsigned tick;
  ta_list ta;

  if (!stack || !tpac || !root) {
    su_seterrno(EINVAL);
    return NULL;
  }

  mr = su_home_clone(NULL, sizeof *mr);
  if (!mr)
    return NULL;

  SU_DEBUG_7(("%s(): %p\n", __func__, mr));

  mr->mr_stack = stack;
  mr->mr_tpac = tpac;
  mr->mr_root = root;

  mr->mr_master->tp_master = mr;
  mr->mr_master->tp_params = tpp = mr->mr_params;

  mr->mr_master->tp_reusable = 1;
  tpp->tpp_mtu = UINT_MAX;
  tpp->tpp_thrprqsize = THRP_PENDING;
  tpp->tpp_qsize = TPORT_QUEUESIZE;
  tpp->tpp_sdwn_error = 1;
  tpp->tpp_idle = UINT_MAX;
  tpp->tpp_timeout = UINT_MAX;
  tpp->tpp_sigcomp_lifetime = UINT_MAX;

  tpn = mr->mr_master->tp_name;
  tpn->tpn_proto = "*";
  tpn->tpn_host = "*";
  tpn->tpn_canon = "*";
  tpn->tpn_port = "*";

  ta_start(ta, tag, value);

  tport_set_params(mr->mr_master, ta_tags(ta));
  tport_open_log(mr, ta_args(ta));

  tick = 5000; /* For testing, usually 30000 is enough */  
  if (tpp->tpp_idle < 4 * tick)
    tick = tpp->tpp_idle / 4;
  if (tpp->tpp_timeout < 4 * tick)
    tick = tpp->tpp_timeout / 4;
  if (tick < 200)
    tick = 200;

  mr->mr_timer = su_timer_create(su_root_task(root), tick);
  su_timer_set(mr->mr_timer, tport_tick, mr);

  ta_end(ta);

  return mr->mr_master;
}

/** Destroy the master transport. */
void tport_destroy(tport_t *self)
{
  tport_master_t *mr;

  static tp_stack_class_t tport_destroy_tpac[1] = 
    {{
	sizeof tport_destroy_tpac,
	/* tpac_recv */ tport_destroy_recv,
	/* tpac_error */ tport_destroy_error,
	/* tpac_alloc */ tport_destroy_alloc,
	/* tpac_comp_accept */ NULL
      }};

  SU_DEBUG_7(("%s(%p)\n", __func__, self));

  if (self == NULL)
    return;
  
  assert(tport_is_master(self));
  if (!tport_is_master(self))
    return;

  mr = (tport_master_t *)self;
  mr->mr_tpac = tport_destroy_tpac;

  while (mr->mr_primaries)
    tport_zap_primary(mr->mr_primaries);

#if HAVE_SIGCOMP
  if (mr->mr_compartment)
    sigcomp_compartment_unref(mr->mr_compartment), mr->mr_compartment = NULL;
#endif

  if (mr->mr_dump_file)
    fclose(mr->mr_dump_file), mr->mr_dump_file = NULL;

  if (mr->mr_timer)
    su_timer_destroy(mr->mr_timer), mr->mr_timer = NULL;

  su_home_zap(mr->mr_home);
}

/** Allocate a primary transport */
static 
tport_primary_t *tport_alloc_primary(tport_master_t *mr)
{
  tport_primary_t *pri, **next;

  for (next = &mr->mr_primaries; *next; next = &(*next)->pri_next)
    ;

  if ((pri = su_home_clone(mr->mr_home, sizeof (*pri)))) {
    tport_t *tp = pri->pri_primary;
    tp->tp_master = mr;
    tp->tp_pri = pri;
    tp->tp_socket = SOCKET_ERROR;

    tp->tp_magic = mr->mr_master->tp_magic;

    tp->tp_params = pri->pri_params;
    memcpy(tp->tp_params, mr->mr_params, sizeof (*tp->tp_params));
    tp->tp_reusable = mr->mr_master->tp_reusable;

    SU_DEBUG_5(("%s(%p): new primary tport %p\n", __func__, mr, pri));
  }

  *next = pri;

  return pri;
}

/**Create a primary transport object with socket.
 *
 * Creates a primary transport object with a server socket, and then
 * registers the socket with suitable events to the root.
 *
 * @param dad   parent (master or primary) transport object
 * @param ai    pointer to addrinfo structure
 * @param canon canonical name of node
 * @param protoname name of the protocol
 */
static
tport_primary_t *tport_listen(tport_master_t *mr, su_addrinfo_t const *ai, 
			      char const *canon, char const *protoname,
			      int port,
			      tagi_t *tags)
{
  tport_primary_t *pri = NULL;

  su_socket_t s = SOCKET_ERROR;
  int index = 0, events = 0, nat_bound = 0;
  su_wakeup_f wakeup = NULL;
  su_wait_t wait[1] = { SU_WAIT_INIT };

  su_sockaddr_t su[1];
  socklen_t sulen = ai->ai_addrlen;

  int err;
  int errlevel = 3;
  char buf[TPORT_HOSTPORTSIZE];

  /* Log an error, return error */
#define TPORT_LISTEN_ERROR(errno, what)  \
  ((void)(err = errno, s != SOCKET_ERROR ? su_close(s) : 0,	     \
	    (SU_LOG_LEVEL >= errlevel ?				     \
	     su_llog(tport_log, errlevel,			     \
		     "%s(%p): %s(pf=%d %s/%s): %s\n",		     \
		     __func__, mr, #what, ai->ai_family,	     \
		     protoname,					     \
		     tport_hostport(buf, sizeof(buf), su, 2),	     \
		     su_strerror(err)) : (void)0),		     \
	    tport_zap_primary(pri),		                     \
	    su_seterrno(err)),					     \
     (void *)NULL)

  if (sulen > sizeof(su))
    return NULL;
  memcpy(su, ai->ai_addr, sulen);

  if (port > 0)
    su->su_port = htons(port);

  /* Create a primary transport object for another transport. */
  pri = tport_alloc_primary(mr);
  if (pri == NULL)
    return TPORT_LISTEN_ERROR(errno, tport_alloc_primary);
  pri->pri_family = ai->ai_family;
  pri->pri_socktype = ai->ai_socktype;
  pri->pri_protocol = ai->ai_protocol;

  if (tport_set_params(pri->pri_primary, TAG_NEXT(tags)) < 0)
    return TPORT_LISTEN_ERROR(su_errno(), tport_set_params);    

  if (ai->ai_protocol == IPPROTO_SCTP) {
    if (pri->pri_params->tpp_mtu > TP_SCTP_MSG_MAX)
      pri->pri_params->tpp_mtu = TP_SCTP_MSG_MAX;
  }

  s = su_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);

  if (s == SOCKET_ERROR) {
    if (ai->ai_family == AF_INET6 && su_errno() == EAFNOSUPPORT)
      errlevel = 7;
    return TPORT_LISTEN_ERROR(su_errno(), socket);
  }

  /* Passive open, do bind() (and listen() if connection-oriented). */

#ifdef __linux__
  /* Linux does not allow reusing TCP port while this one is open,
     so we can safely call su_setreuseaddr() before bind(). */
  if (ai->ai_socktype == SOCK_STREAM || ai->ai_socktype == SOCK_SEQPACKET)
    su_setreuseaddr(s, 1);
#endif

  nat_bound = tport_nat_traverse_nat(mr, su, ai, s);

  if (!nat_bound /* || !mr->mr_nat->stun_enabled */) {
    /* STUN has a problem or is not enabled */
    if (bind(s, &su->su_sa, sulen) == SOCKET_ERROR) {
      if (su_errno() == EADDRINUSE) errlevel = 7;
      return TPORT_LISTEN_ERROR(su_errno(), bind);
    }

    if (getsockname(s, &su->su_sa, &sulen) == SOCKET_ERROR)
      return TPORT_LISTEN_ERROR(su_errno(), getsockname);

#if __linux__
    if (ai->ai_family == AF_INET6) {
      if (SU_SOCKADDR_INADDR_ANY(su))
	/* pri->pri_family2 = AF_INET */ ;
      else if (IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr) ||
	       IN6_IS_ADDR_V4COMPAT(&su->su_sin6.sin6_addr))
	pri->pri_family = AF_INET;
    }
#endif
  }
    
  if (ai->ai_socktype == SOCK_STREAM || 
      ai->ai_socktype == SOCK_SEQPACKET) {
    /* Connection-oriented protocols listen and accept connections */
    wakeup = tport_accept;	/* accepting function will be registered */
    events = SU_WAIT_ACCEPT;

    /* XXX - we should take this from the current tags */
    if (listen(s, mr->mr_params->tpp_qsize) == SOCKET_ERROR)
      return TPORT_LISTEN_ERROR(su_errno(), listen);
#ifndef __linux__
    /* Allow reusing TCP sockets
     *
     * On Solaris & BSD, call setreuseaddr() after bind in order to avoid
     * binding to a port owned by an existing server.
     */
    su_setreuseaddr(s, 1);
#endif
  } else {
    /* Connectionless protocols sendto() and recvfrom() messages */
    wakeup = tport_recv;	/* receiving function will be registered */
    events = SU_WAIT_IN;

    if (ai->ai_protocol == IPPROTO_UDP) {
      unsigned rmem = 0, wmem = 0;

#if HAVE_IP_RECVERR
      if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
	int const one = 1;
	if (setsockopt(s, SOL_IP, IP_RECVERR, &one, sizeof(one)) < 0) {
	  if (ai->ai_family == AF_INET)
	    return TPORT_LISTEN_ERROR(su_errno(), IP_RECVERR);
	}
	events |= SU_WAIT_ERR;
      }
#endif
#if HAVE_IPV6_RECVERR
      if (ai->ai_family == AF_INET6) {
	int const one = 1;
	if (setsockopt(s, SOL_IPV6, IPV6_RECVERR, &one, sizeof(one)) < 0)
	  return TPORT_LISTEN_ERROR(su_errno(), IPV6_RECVERR);
	events |= SU_WAIT_ERR;
      }
#endif

      tl_gets(tags, 
	      TPTAG_UDP_RMEM_REF(rmem),
	      TPTAG_UDP_WMEM_REF(wmem),
	      TAG_END());

      if (rmem != 0 && 
1238 1239
	  setsockopt(s, SOL_SOCKET,
		     SO_RCVBUF, (void *)&rmem, sizeof rmem) < 0) {
Pekka Pessi's avatar
Pekka Pessi committed
1240 1241 1242 1243 1244
	SU_DEBUG_3(("setsockopt(SO_RCVBUF): %s\n", 
		    su_strerror(su_errno())));
      }

      if (wmem != 0 && 
1245 1246
	  setsockopt(s, SOL_SOCKET,
		     SO_SNDBUF, (void *)&wmem, sizeof wmem) < 0) {
Pekka Pessi's avatar
Pekka Pessi committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 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 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 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 1498 1499 1500 1501 1502 1503 1504 1505
	SU_DEBUG_3(("setsockopt(SO_SNDBUF): %s\n", 
		    su_strerror(su_errno())));
      }
    }
  }

  if (su_wait_create(wait, s, events) == -1)
    return TPORT_LISTEN_ERROR(su_errno(), su_wait_create);

  /* Register receiving or accepting function with events specified above */
  index = su_root_register(mr->mr_root, wait, wakeup, pri->pri_primary, 0);
   if (index == -1)
     return TPORT_LISTEN_ERROR(su_errno(), su_root_register);
  if (tport_setname(pri->pri_primary, protoname, su, canon) == -1) 
    return TPORT_LISTEN_ERROR(su_errno(), tport_setname);

  pri->pri_primary->tp_socket   = s;
  pri->pri_primary->tp_index    = index;
  pri->pri_primary->tp_events   = events;
  pri->pri_primary->tp_connected = 0;
  pri->pri_primary->tp_conn_orient = ai->ai_socktype != SOCK_DGRAM;
  pri->pri_primary->tp_addr[0] = su[0];
  pri->pri_primary->tp_addrlen = sulen;
  
  if (nat_bound) {
    /* XXX - should set also the IP address in tp_addr? */
    pri->pri_natted = 1;
    tport_nat_set_canon(pri->pri_primary, mr->mr_nat);
  }

  SU_DEBUG_5(("%s(%p): %s " TPN_FORMAT "\n", 
	      __func__, pri, "listening at",
	      TPN_ARGS(pri->pri_primary->tp_name)));

  return pri;
}

/** Destroy a primary transport and its secondary transports. @internal */
static 
void tport_zap_primary(tport_primary_t *pri)
{
  tport_primary_t **prip;

  if (pri == NULL)
    return;

  assert(tport_is_primary(pri->pri_primary));

  if (pri->pri_threadpool) {
    tport_kill_threadpool(pri);
    SU_DEBUG_3(("%s(%p): zapped threadpool\n", __func__, pri));
  }

  while (pri->pri_secondary)
    tport_zap_secondary(pri->pri_secondary);

  tport_nat_finish(pri);

  /* We have just a single-linked list for primary transports */
  for (prip = &pri->pri_master->mr_primaries;
       *prip != pri;
       prip = &(*prip)->pri_next)
    assert(*prip);

  *prip = pri->pri_next;

  tport_zap_secondary(pri->pri_primary);
}


/**Allocate a secondary transport. @internal
 *
 * The function tport_alloc_secondary() creates a secondary transport
 * object. The new transport initally shares parameters structure with the
 * original transport.
 *
 * @param dad primary transport
 *
 * @return
 * The function tport_alloc_seconary() returns a pointer to the newly
 * created transport, or NULL upon an error.
 */
static
tport_t *tport_alloc_secondary(tport_primary_t *pri)
{
  tport_master_t *mr = pri->pri_master;
  tport_t *self;

  self = su_home_clone(mr->mr_home, sizeof *self);

  if (self) {
    SU_DEBUG_7(("%s(%p): new secondary tport %p\n", __func__, pri, self));

    self->tp_refs = -1;			/* Freshly allocated  */
    self->tp_master = mr;
    self->tp_pri = pri;
    self->tp_params = pri->pri_params;
    self->tp_reusable = pri->pri_primary->tp_reusable;

    self->tp_magic = pri->pri_primary->tp_magic;
  }

  return self;
}

/** Create a connected transport object with socket.
 *
 * The function tport_connect() creates a secondary transport with a
 * connected socket. It registers the socket with suitable events to the
 * root.
 *
 * @param pri   primary transport object
 * @param ai    pointer to addrinfo structure
 * @param canon canonical name of node
 * @param protoname name od the protocol
 */
static
tport_t *tport_connect(tport_primary_t *pri, 
		       su_addrinfo_t *ai,
		       tp_name_t const *tpn)
{
  tport_master_t *mr = pri->pri_master;
  tport_t *self = NULL;

  su_socket_t s = SOCKET_ERROR;
  int index = 0, err;
  su_wait_t wait[1] = { SU_WAIT_INIT };

  int errlevel = 3;
  char buf[TPORT_HOSTPORTSIZE];

  if (ai == NULL || ai->ai_addrlen > sizeof (self->tp_addr))
    return NULL;
  
  /* Log an error, return error */
#define TPORT_CONNECT_ERROR(errno, what)  \
  return							     \
    ((void)(err = errno, s != SOCKET_ERROR ? su_close(s) : 0,	     \
	    su_wait_destroy(wait),				     \
	    (SU_LOG_LEVEL >= errlevel ?				     \
	     su_llog(tport_log, errlevel,			     \
		     "%s(%p): %s(pf=%d %s/%s): %s\n",		     \
		     __func__, pri, #what, ai->ai_family,	     \
		     tpn->tpn_proto,				     \
		       tport_hostport(buf, sizeof(buf),		     \
				      (void *)ai->ai_addr, 2),	     \
		     su_strerror(err)) : (void)0),		     \
	    tport_zap_secondary(self),				     \
	    su_seterrno(err)),					     \
     (void *)NULL)

  if ((self = tport_alloc_secondary(pri)) == NULL)
    TPORT_CONNECT_ERROR(errno, tport_alloc_secondary);

  s = su_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);

  if (s == SOCKET_ERROR) {
    if (ai->ai_family == AF_INET6 && su_errno() == EAFNOSUPPORT)
      errlevel = 7;
    TPORT_CONNECT_ERROR(su_errno(), socket);
  }

  if (pri->pri_primary->tp_socket != SOCKET_ERROR) {
    su_sockaddr_t susa;
    socklen_t susalen = sizeof(susa);
    int pri_s = pri->pri_primary->tp_socket;

    if (getsockname(pri_s, &susa.su_sa, &susalen) < 0) {
      SU_DEBUG_3(("tport_connect: getsockname(): %s\n", 
		  su_strerror(su_errno())));
    }
    else {
      susa.su_port = 0;
      if (bind(s, &susa.su_sa, susalen) < 0) {
	SU_DEBUG_3(("tport_connect: bind(local-ip): %s\n", 
		    su_strerror(su_errno())));
      }
    }
  }

  if (/* !do_tls && */ su_setblocking(s, 0) < 0) /* asynchronous connect() */
    TPORT_CONNECT_ERROR(su_errno(), su_setblocking);

  if (ai->ai_socktype == SOCK_STREAM) {
    int one = 1;
    if (setsockopt(s, SOL_TCP, TCP_NODELAY, &one, sizeof one) == -1)
      TPORT_CONNECT_ERROR(su_errno(), setsockopt(TCP_NODELAY));
  }

  if (connect(s, ai->ai_addr, ai->ai_addrlen) == SOCKET_ERROR) {
    err = su_errno();
    if (err != EINPROGRESS && err != EAGAIN)
      TPORT_CONNECT_ERROR(err, connect);
  }

  if (su_wait_create(wait, s, SU_WAIT_IN | SU_WAIT_HUP) == -1)
    TPORT_CONNECT_ERROR(su_errno(), su_wait_create);

  /* Register receiving function with events specified above */
  if ((index = su_root_register(mr->mr_root, wait, tport_recv, self, 0)) == -1)
    TPORT_CONNECT_ERROR(su_errno(), su_root_register);

  /* */
  if (tport_setname(self, tpn->tpn_proto, 
		    (void *)ai->ai_addr, tpn->tpn_canon) == -1) 
    TPORT_CONNECT_ERROR(su_errno(), tport_setname);

  self->tp_socket   = s;
  self->tp_index    = index;
  self->tp_events   = SU_WAIT_IN | SU_WAIT_HUP;
  self->tp_connected = ai->ai_socktype != SOCK_DGRAM;
  self->tp_conn_orient = 1;

#if HAVE_SIGCOMP
  if (tpn->tpn_comp == pri->pri_primary->tp_name->tpn_comp)
    self->tp_name->tpn_comp = pri->pri_primary->tp_name->tpn_comp;
  if (!pri->pri_primary->tp_name->tpn_comp)
    self->tp_sigcomp->sc_infmt = format_is_noncomp;
#endif

#if HAVE_TLS
  if (pri->pri_primary->tp_tls) {
    self->tp_tls = tls_init_client(pri->pri_primary->tp_tls, s);
    if (!self->tp_tls)
      TPORT_CONNECT_ERROR(errno, tls_init_client);
  }
#endif

  memcpy(self->tp_addr, ai->ai_addr, self->tp_addrlen = ai->ai_addrlen);
  
  SU_DEBUG_5(("%s(%p): %s " TPN_FORMAT "\n", 
	      __func__, self, "connecting to",
	      TPN_ARGS(self->tp_name)));

  tprb_append(&pri->pri_secondary, self);

  return self;
}

/** Destroy a secondary transport. @internal */
static 
void tport_zap_secondary(tport_t *self)
{
  tport_master_t *mr;

  if (self == NULL)
    return;

  /* Remove from rbtree */
  tprb_remove(&self->tp_pri->pri_secondary, self);

  if (self->tp_msg) {
    msg_destroy(self->tp_msg), self->tp_msg = NULL;
    SU_DEBUG_3(("%s(%p): zapped partially received message\n", 
		__func__, self));
  }

  if (self->tp_queue && self->tp_queue[self->tp_qhead]) {
    size_t n = 0, i, N = self->tp_params->tpp_qsize;
Pekka Pessi's avatar
Pekka Pessi committed
1506
    for (i = self->tp_qhead; self->tp_queue[i]; i = (i + 1) % N) {
Pekka Pessi's avatar
Pekka Pessi committed
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
      msg_destroy(self->tp_queue[i]), self->tp_queue[i] = NULL;
      n++;
    }
    SU_DEBUG_3(("%s(%p): zapped %lu queued messages\n", 
		__func__, self, (LU)n));
  }

  if (self->tp_pused) {
    SU_DEBUG_3(("%s(%p): zapped with pending requests\n", __func__, self));
  }

  mr = self->tp_master;

  if (self->tp_index)
    su_root_deregister(mr->mr_root, self->tp_index);
  self->tp_index = 0;
  if (self->tp_socket != -1)
    su_close(self->tp_socket);
  self->tp_socket = -1;

#if HAVE_TLS
  if (self->tp_tls)
    tls_free(self->tp_tls);
#endif

#if HAVE_SIGCOMP
  if (self->tp_sigcomp) {
    tport_sigcomp_t *sc = self->tp_sigcomp;

    if (sc->sc_udvm)
      sigcomp_udvm_free(sc->sc_udvm), sc->sc_udvm = NULL;
    if (sc->sc_compressor)
      sigcomp_compressor_free(sc->sc_compressor), sc->sc_compressor = NULL;
  }
#endif

  su_home_zap(self->tp_home);
}

/** Create a new transport reference. */
tport_t *tport_incref(tport_t *tp)
{
  if (tp) {
    if (tp->tp_refs >= 0)
      tp->tp_refs++;
    else if (tp->tp_refs == -1)
      tp->tp_refs = 1;
  }
  return tp;
}

/** Destroy a transport reference. */
void tport_decref(tport_t **ttp)
{
  assert(ttp);

  if (*ttp) {
    if ((*ttp)->tp_refs > 0)
      if (--(*ttp)->tp_refs == 0 && (*ttp)->tp_params->tpp_idle == 0)
	if (!tport_is_closed(*ttp))
	  tport_close(*ttp);
    *ttp = NULL;
  }
}

/** Get transport parameters.
 *
 * @param self          pointer to a transport object
 * @param tag,value,... list of tags
 */
int tport_get_params(tport_t const *self,
		     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  int n;
  tport_params_t const *tpp;

  if (self == NULL)
1585
    return su_seterrno(EINVAL);
Pekka Pessi's avatar
Pekka Pessi committed
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624

  tpp = self->tp_params;
  ta_start(ta, tag, value);

  n = tl_tgets(ta_args(ta),
	       TPTAG_MTU(tpp->tpp_mtu),
	       TPTAG_REUSE(self->tp_reusable),
	       TPTAG_CONNECT(tpp->tpp_conn_orient),
	       TPTAG_QUEUESIZE(tpp->tpp_qsize),
	       TPTAG_IDLE(tpp->tpp_idle),
	       TPTAG_TIMEOUT(tpp->tpp_timeout),
	       TPTAG_SDWN_ERROR(tpp->tpp_sdwn_error),
	       TPTAG_DEBUG_DROP(tpp->tpp_drop),
	       TPTAG_THRPSIZE(tpp->tpp_thrpsize),
	       TPTAG_THRPRQSIZE(tpp->tpp_thrprqsize),
	       TAG_END());

  ta_end(ta);

  return n;
}

/** Set transport parameters.
 *
 * @param self          pointer to a transport object
 * @param tag,value,... list of tags
 */
int tport_set_params(tport_t *self,
		     tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  int n;
  tport_params_t tpp[1], *tpp0;

  int connect, sdwn_error, reusable;

  struct sigcomp_compartment *cc = NONE;

  if (self == NULL)
1625
    return su_seterrno(EINVAL);
Pekka Pessi's avatar
Pekka Pessi committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

  memcpy(tpp, tpp0 = self->tp_params, sizeof *tpp);

  connect = tpp->tpp_conn_orient;
  sdwn_error = tpp->tpp_sdwn_error;
  reusable = self->tp_reusable;

  ta_start(ta, tag, value);

  n = tl_gets(ta_args(ta),
	      TPTAG_MTU_REF(tpp->tpp_mtu),
	      TAG_IF(!self->tp_queue, TPTAG_QUEUESIZE_REF(tpp->tpp_qsize)),
	      TPTAG_IDLE_REF(tpp->tpp_idle),
	      TPTAG_TIMEOUT_REF(tpp->tpp_timeout),
	      TPTAG_DEBUG_DROP_REF(tpp->tpp_drop),
	      TPTAG_THRPSIZE_REF(tpp->tpp_thrpsize),
	      TPTAG_THRPRQSIZE_REF(tpp->tpp_thrprqsize),
	      TPTAG_SIGCOMP_LIFETIME_REF(tpp->tpp_sigcomp_lifetime),
	      TPTAG_CONNECT_REF(connect),
	      TPTAG_SDWN_ERROR_REF(sdwn_error),
	      TPTAG_REUSE_REF(reusable),
	      TPTAG_COMPARTMENT_REF(cc),
	      TAG_END());

  ta_end(ta);

  if (n == 0)
    return 0;

  if (tpp->tpp_idle > 0 && tpp->tpp_idle < 2000)
    tpp->tpp_idle = 2000;
  if (tpp->tpp_timeout < 1000)
    tpp->tpp_timeout = 1000;
  if (tpp->tpp_drop > 1000)
    tpp->tpp_drop = 1000;
  if (tpp->tpp_thrprqsize > 0)
    tpp->tpp_thrprqsize = tpp0->tpp_thrprqsize;
  if (tpp->tpp_sigcomp_lifetime != 0 && tpp->tpp_sigcomp_lifetime < 30)
    tpp->tpp_sigcomp_lifetime = 30;
  if (tpp->tpp_qsize >= 1000)
    tpp->tpp_qsize = 1000;

  tpp->tpp_sdwn_error = sdwn_error;

  self->tp_reusable = reusable;

  /* Currently only primary UDP transport can *not* be connection oriented */ 
  tpp->tpp_conn_orient = connect 
    || !tport_is_primary(self) || !tport_is_dgram(self);

  if (tport_is_secondary(self) && 
      self->tp_params == self->tp_pri->pri_primary->tp_params) {
    tpp0 = su_zalloc(self->tp_home, sizeof *tpp0); if (!tpp0) return -1;
  }

#if HAVE_SIGCOMP
  if (cc != NONE && self == self->tp_master->mr_master) {
    if (self->tp_master->mr_compartment)
      sigcomp_compartment_unref(self->tp_master->mr_compartment);
    self->tp_master->mr_compartment = sigcomp_compartment_ref(cc);
  }
#endif

  memcpy(tpp0, tpp, sizeof *tpp);

  return n;
}

/** Bind transport objects. 
 *
 * @deprecated 
 * Use tport_tbind().
 */
int tport_bind(tport_t *self,
	       tp_name_t const *tpn,
	       char const * const transports[],
	       int flags)
{
  return tport_tbind(self, tpn, transports, TAG_END());
}

/** Bind transport objects.
 *
 * @param self        pointer to a transport object
 * @param tpn         desired transport address
 * @param transports  list of protocol names supported by stack
 * @param tag,value,... tagged argument list
 */
int tport_tbind(tport_t *self,
		tp_name_t const *tpn,
		char const * const transports[],
		tag_type_t tag, tag_value_t value, ...)
{
  ta_list ta;
  int server = 1, retval;
  tp_name_t mytpn[1];
  tport_master_t *mr;

  if (self == NULL || tport_is_secondary(self) ||
      tpn == NULL || transports == NULL) {
    su_seterrno(EINVAL);
    return -1;
  }

  *mytpn = *tpn;

  if (mytpn->tpn_ident == NULL)
    mytpn->tpn_ident = self->tp_ident;

  ta_start(ta, tag, value);

  tl_gets(ta_args(ta),
	  TPTAG_SERVER_REF(server),
	  TPTAG_IDENT_REF(mytpn->tpn_ident),
	  TAG_END());

  mr = self->tp_master; assert(mr);

  if (server)
    retval = tport_bind_server(mr, mytpn, transports, ta_args(ta));
  else
    retval = tport_bind_client(mr, mytpn, transports, ta_args(ta));


  ta_end(ta);

  return retval;
}

/** Bind primary transport objects used by a client-only application.
 * @internal
 */
int tport_bind_client(tport_master_t *mr,
                      tp_name_t const *tpn,
                      char const * const transports[],
		      tagi_t *tags)
{
  int i;
  tport_primary_t *pri = NULL, **tbf;
  tport_t *tp;

  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, mr, TPN_ARGS(tpn)));

  for (tbf = &mr->mr_primaries; *tbf; tbf = &(*tbf)->pri_next)
    ;

  for (i = 0; transports[i]; i++) {
    su_addrinfo_t hints[1];
    char const *proto = transports[i];
    
    if (strcmp(proto, tpn->tpn_proto) != 0 && 
        strcmp(tpn->tpn_proto, tpn_any) != 0)
      continue;

    /* Resolve protocol, skip unknown transport protocols */
    if (getprotohints(hints, proto, AI_PASSIVE) < 0)
      continue;

    if (!(pri = tport_alloc_primary(mr)))
      break;

    tp = pri->pri_primary;
    
#if HAVE_TLS
    if (strcasecmp(proto, "tls") == 0) {
      tp->tp_tls = tport_init_tls(tags);
      if (tp->tp_tls == NULL)
	break;
    }
#endif

    pri->pri_family   = hints->ai_family;
    pri->pri_socktype = hints->ai_socktype;
    pri->pri_protocol = hints->ai_protocol;

    tp->tp_name->tpn_proto = proto;
    tp->tp_name->tpn_host = "*";
    tp->tp_name->tpn_port = "*";
    tp->tp_name->tpn_canon = "*";
    tp->tp_name->tpn_ident = su_strdup(tp->tp_home, tpn->tpn_ident);

    tport_init_compression(pri, tpn->tpn_comp, tags);
  }

  if (!pri)
    tport_zap_primary(*tbf);

  return pri ? 0 : -1;
}

/** Bind primary transport objects used by a server application. */
int tport_bind_server(tport_master_t *mr,
                      tp_name_t const *tpn,
                      char const * const transports[],
		      tagi_t *tags)
{
  char hostname[256];
  char const *proto, *canon, *host, *port;
  char port0[16];
  int ephemeral_port;
  int i, error = 0, not_supported, family = 0;
  tport_primary_t *pri = NULL, **tbf;
  su_localinfo_t *li = NULL;
  unsigned p;

  struct tport_nat_s *nat;

#if SU_HAVE_IN6
  if (!mr->mr_boundserver) {
    /* Check if we can bind to IPv6 separately */
    su_sockaddr_t su[1], su4[1];
    socklen_t sulen, su4len;
    int s6, s4;

    s4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    s6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);

    memset(su, 0, sizeof *su);
    su->su_len = sulen = (sizeof su->su_sin6);
    su->su_family = AF_INET6;

    memset(su4, 0, sizeof *su4);
    su4->su_len = su4len = (sizeof su->su_sin);
    su4->su_family = AF_INET;

    if (bind(s6, &su->su_sa, sulen) < 0)
      ;
    else if (getsockname(s6, &su->su_sa, &sulen) < 0)
      ;
    else if ((su4->su_port = su->su_port) != 0 && 
	     bind(s4, &su4->su_sa, su4len) == 0)
      mr->mr_bindv6only = 1;

    close(s6), close(s4);

    mr->mr_boundserver = 1;
  }
#endif

  for (tbf = &mr->mr_primaries; *tbf; tbf = &(*tbf)->pri_next)
    ;

  SU_DEBUG_5(("%s(%p) to " TPN_FORMAT "\n", __func__, mr, TPN_ARGS(tpn)));

1870
  nat = tport_nat_initialize_nat_traversal(mr, tpn, &transports, tags);
Pekka Pessi's avatar
Pekka Pessi committed
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
  if (!nat) 
    SU_DEBUG_1(("%s: %s\n", __func__, strerror(errno)));

  if (tpn->tpn_host == NULL || strcmp(tpn->tpn_host, tpn_any) == 0) {
    /* Use a local IP address */
    host = NULL;
  }
  else if (tpn->tpn_host && tpn->tpn_host[0] == '[') {
    /* Remove [] around IPv6 addresses. */
    host = strcpy(hostname, tpn->tpn_host + 1);
    hostname[strlen(hostname) - 1] = '\0';
  }
  else
    host = tpn->tpn_host; 

  if (tpn->tpn_port != NULL && strlen(tpn->tpn_port) > 0 &&
      strcmp(tpn->tpn_port, tpn_any) != 0)
    port = tpn->tpn_port, ephemeral_port = 0;
  else 
    port = "", ephemeral_port = -1;			/* XXX */

  if (host && (strcmp(host, "0.0.0.0") == 0 || strcmp(host, "0") == 0))
    host = NULL, family = AF_INET;
  else if (host && strcmp(host, "::") == 0)
    host = NULL, family = AF_INET6;

  if (tpn->tpn_canon && strcmp(tpn->tpn_canon, tpn_any) &&
      (host || tpn->tpn_canon != tpn->tpn_host))
    canon = tpn->tpn_canon;
1900
  else if (nat) {
Pekka Pessi's avatar
Pekka Pessi committed
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 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 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
    /* NULL if UPnP not present */
    canon = tport_nat_get_external_ip_address(nat);
  }

  if (host == NULL) {
    su_localinfo_t hints[1] = {{ 0 }};
    
    hints->li_flags = 0;
    hints->li_family = family;
    hints->li_scope = LI_SCOPE_GLOBAL | LI_SCOPE_SITE | LI_SCOPE_HOST;

    error = su_getlocalinfo(hints, &li);
    if (error) {
      SU_DEBUG_3(("%s(%p): su_getlocalinfo() for %s address: %s\n", 
		  __func__, mr, 
		  family == AF_INET6 ? "ip6" 
		  : family == AF_INET ? "ip4" : "ip",
		  su_gli_strerror(error)));
      su_seterrno(ENOENT);
      return -1;
    }
  }

  /* 
   * Loop until we can bind all the transports requested by the protocol to
   * the same port. 
   */
  do {
    not_supported = 1;		/* Make sure we don't loop for ever */
    pri = NULL;
    
    for (i = 0; transports[i]; i++) {
      su_addrinfo_t *ai, *res, hints[1];

      proto = transports[i];
      error = EPROTONOSUPPORT;

      if (strcasecmp(proto, tpn->tpn_proto) != 0 && 
          strcmp(tpn->tpn_proto, tpn_any) != 0)
        continue;

      /* Resolve protocol, skip unknown transport protocols. */
      if (getprotohints(hints, proto, AI_PASSIVE) < 0)
        continue;

      hints->ai_family = family;

      if (host == NULL)
	hints->ai_flags |= AI_NUMERICHOST;

      pri = NULL;

      if (host)
	error = su_getaddrinfo(host, port, hints, &res);
      else
	error = tport_get_local_addrinfo(mr, li, port, hints, &res);

      if (error || !res) {
	if (error == EAI_SOCKTYPE)
	  SU_DEBUG_7(("%s(%p): su_getaddrinfo(%s, %s) for %s: %s\n", 
		      __func__, mr, host ? host : "\"\"", port, proto,
		      su_gai_strerror(error)));
	else
	  SU_DEBUG_3(("%s(%p): su_getaddrinfo(%s, %s) for %s: %s\n", 
		      __func__, mr, host ? host : "\"\"", port, proto,
		      su_gai_strerror(error)));
	error = ENOENT;
        continue;
      }

      p = ntohs(((su_sockaddr_t *)res->ai_addr)->su_port);

      for (ai = res; ai; ai = ai->ai_next) {
        /* Skip non-internet (AF_LOCAL) addresses */
        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
          continue;

        SU_DEBUG_9(("%s(%p): calling tport_socket\n", __func__, mr));

	ai->ai_socktype = hints->ai_socktype;
	ai->ai_protocol = hints->ai_protocol;

        pri = tport_listen(mr, ai, canon, proto, p, tags);

        if (pri) {
	  pri->pri_primary->tp_ident = su_strdup(pri->pri_home, tpn->tpn_ident);
	  tport_init_compression(pri, tpn->tpn_comp, tags);

#if HAVE_TLS
	  if (strcasecmp(tpn->tpn_proto, "tls") == 0) {
	    pri->pri_primary->tp_tls = tport_init_tls(tags);
	    if (!pri->pri_primary->tp_tls)
1993
	      goto error;
Pekka Pessi's avatar
Pekka Pessi committed
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 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
	  }
#endif
	  not_supported = 0;
          if (ephemeral_port)
            port = strcpy(port0, pri->pri_primary->tp_port);
          if (ephemeral_port == -1) {
            ephemeral_port = ntohs(pri->pri_primary->tp_addr->su_port);
	    assert(ephemeral_port != 0);
	    if (p == 0)
	      p = ephemeral_port;
	  }
        }
	else {
	  error = su_errno();
	  if (error == EADDRINUSE)
	    not_supported = 0;
	}
      }

      if (host)
	su_freeaddrinfo(res);
      else
	tport_freeaddrinfo(mr, res);

      if (!pri) {
        while (*tbf)
	  tport_zap_primary(*tbf);

        if (ephemeral_port != 0 && ephemeral_port != -1) {
          if (++p >= 65536) p = 1024;
          if (p == ephemeral_port)
            ephemeral_port = 0;
          SU_DEBUG_3(("%s(%p): cannot bind all transports to port %s, "
		      "trying %u\n", 
		      __func__, mr, port, p));
          snprintf(port0, sizeof(port0), "%u", p);
          port = port0;
        }
        break;
      }
    }
  }
  while (!pri && ephemeral_port && !not_supported);

2038 2039 2040
  if (li)
    su_freelocalinfo(li);

Pekka Pessi's avatar
Pekka Pessi committed
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
  if (not_supported)
    error = EPROTONOSUPPORT;

  if (!pri) {
    su_seterrno(error);
    return -1;
  }

  for (pri = *tbf; pri; pri = pri->pri_next) {
    tport_launch_threadpool(pri);
  }

  return 0;
2054 2055 2056 2057 2058

 error:
  if (li)
    su_freelocalinfo(li);
  return -1;
Pekka Pessi's avatar
Pekka Pessi committed
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 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 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 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777
}


/** Convert localinfo into addrinfo */
static
int
tport_get_local_addrinfo(tport_master_t *mr, 
			 su_localinfo_t *li,
			 char const *port,
			 su_addrinfo_t const *hints,
			 su_addrinfo_t **return_ai)
{
  su_addrinfo_t *ai, **prev;
  su_sockaddr_t *su;
  unsigned long lport = 0;
  char *rest;

  if (port) {
    lport = strtoul(port, &rest, 10);
    if (lport >= 65536) {
      su_seterrno(EINVAL);
      return EAI_NONAME;
    }
  }

  prev = return_ai;

  for (; li; li = li->li_next) {
    if (hints->ai_family && hints->ai_family != li->li_family)
      continue;

    ai = calloc(1, sizeof *ai + li->li_addrlen);
    if (ai == NULL) {
      tport_freeaddrinfo(mr, *return_ai);
      return EAI_MEMORY;
    }
    
    *prev = ai, prev = &ai->ai_next;

    ai->ai_flags = AI_PASSIVE | TP_AI_ANY;
    ai->ai_family = li->li_family;
    ai->ai_socktype = hints->ai_socktype;
    ai->ai_protocol = hints->ai_protocol;
    ai->ai_addr = memcpy(ai + 1, li->li_addr, ai->ai_addrlen = li->li_addrlen);
    su = (void *)ai->ai_addr;
    su->su_port = htons(lport);
  }

  return 0;
}

static
void tport_freeaddrinfo(tport_master_t *mr, 
			su_addrinfo_t *ai)
{
  su_addrinfo_t *ai_next;

  while (ai) {
    ai_next = ai->ai_next;
    free(ai);
    ai = ai_next;
  }
}


#if HAVE_TLS
tls_t *
tport_init_tls(tagi_t *tags)
{
  char *homedir = getenv("HOME");
  char *tbf = NULL;
  char const *path = NULL;
  tls_t *tls = NULL;
  su_home_t *home = su_home_clone(NULL, sizeof *home);
  unsigned version = 1;

  if (getenv("TPORT_SSL"))
    version = 0;

  tl_gets(tags,
	  TPTAG_CERTIFICATE_REF(path),
	  TPTAG_TLS_VERSION_REF(version),
	  TAG_END());

  if (!homedir)
    homedir = "";
	   
  if (!path)
    path = tbf = su_sprintf(home, "%s/.sip/auth", homedir);
  
  if (path) {
    tls_issues_t ti = {0};
    ti.verify_depth = 2;
    ti.configured = path != tbf;
    ti.randFile = su_sprintf(home, "%s/%s", path, "tls_seed.dat");
    ti.key = su_sprintf(home, "%s/%s", path, "agent.pem");
    ti.cert = ti.key;
    ti.CAfile = su_sprintf(home, "%s/%s", path, "cafile.pem");
    ti.version = version;

    SU_DEBUG_9(("%s(%p): tls key = %s\n", __func__, home, ti.key));

    if (ti.key && ti.CAfile && ti.randFile) {
      tls = tls_init_master(&ti);
      if (tls == NULL)
	SU_DEBUG_3(("tls_init_master: %s\n", strerror(errno)));
    }
  }

  su_home_zap(home); 

  return tls;
}
#endif

static 
int tport_init_compression(tport_primary_t *pri, 
			   char const *compression, 
			   tagi_t *tl)
{
#if HAVE_SIGCOMP
  tport_master_t *mr = pri->pri_master;

  if (compression == NULL || 
      strcasecmp(compression, "sigcomp"))
    return 0;

  if (pri->pri_protocol != IPPROTO_TCP &&
      pri->pri_protocol != IPPROTO_UDP) {
    SU_DEBUG_3(("tport: no sigcomp for %s\n", pri->pri_primary->tp_protoname));
    return 0;
  }

  if (mr->mr_compartment) {
    pri->pri_primary->tp_name->tpn_comp = tport_sigcomp_name;
  }
#endif

  return 0;
}

/** Close a transport. 
 * 
 * The function tport_close() closes a socket associated with a transport
 * object.
 */
void tport_close(tport_t *self)
{
  int i;

  SU_DEBUG_5(("%s(%p): " TPN_FORMAT "\n", __func__, self,
	      TPN_ARGS(self->tp_name)));

  self->tp_closed = 1;
  self->tp_send_close = 1;
  self->tp_recv_close = 1;

#if HAVE_TLS
  if (self->tp_tls != NULL) {
    /* if (tport_is_primary(self)) */
      tls_free(self->tp_tls);
      /* XXX - PPe: does the tls_shutdown zap everything but socket? */
    self->tp_tls = NULL;
    su_free(self->tp_home, self->tp_tls_buffer);
  }
  else 
#endif
  if (self->tp_socket != -1)
    shutdown(self->tp_socket, 2);

  if (self->tp_index)
    su_root_deregister(self->tp_master->mr_root, self->tp_index);
  self->tp_index = 0;
  if (self->tp_socket != -1)
    su_close(self->tp_socket);
  self->tp_socket = -1;

  if (self->tp_params->tpp_sdwn_error && self->tp_pused)
    tport_error_report(self, -1, NULL);

#if HAVE_SIGCOMP
  if (self->tp_sigcomp->sc_cc) {
    sigcomp_compartment_unref(self->tp_sigcomp->sc_cc);
    self->tp_sigcomp->sc_cc = NULL;
  }  
#endif

  /* Zap the queued messages */
  if (self->tp_queue) {
    int N = self->tp_params->tpp_qsize;
    for (i = 0; i < N; i++) {
      if (self->tp_queue[i])
	msg_ref_destroy(self->tp_queue[i]), self->tp_queue[i] = NULL;
    }
  }

  self->tp_index = 0;
  self->tp_events = 0;
}

/** Shutdown a transport.
 *
 * The tport_shutdown() shuts down a full-duplex transport connection
 * partially or completely. If @a how is 0, the further incoming data is
 * shut down. If @a how is 1, further outgoing data is shut down. If @a how
 * is 2, both incoming and outgoing traffic is shut down.
 *
 */
int tport_shutdown(tport_t *self, int how)
{
  if (self == NULL || tport_is_primary(self))
    return -1;

  SU_DEBUG_7(("%s(%p, %d)\n", __func__, self, how));

  if (!tport_is_tcp(self) ||
      how < 0 || 
      (how == 0 && self->tp_send_close) ||
      (how == 1 && self->tp_recv_close) || 
      how >= 2) {
    tport_close(self);
    return 1;
  }

#if HAVE_TLS
  if (self->tp_tls != NULL) {
    /* XXX - send alert */
    return 0;
  }
#endif

  shutdown(self->tp_socket, how);

  if (how == 0) {
    self->tp_recv_close = 1;
    self->tp_events &= ~SU_WAIT_IN;
    if (self->tp_params->tpp_sdwn_error && self->tp_pused)
      tport_error_report(self, -1, NULL);
  }
  else if (how == 1) {
    self->tp_send_close = 2;
    self->tp_events &= ~SU_WAIT_OUT;

    if (self->tp_queue && self->tp_queue[self->tp_qhead]) {
      int i, N = self->tp_params->tpp_qsize;
      for (i = 0; i < N; i++) {
	if (self->tp_queue[i]) {
	  tport_pending_errmsg(self, self->tp_queue[i], EPIPE);
	  msg_ref_destroy(self->tp_queue[i]), self->tp_queue[i] = NULL;
	}
      }
    }
  }

  tport_events(self);

  return 0;
}

static inline
unsigned long tport_now(void)
{
  return su_now().tv_sec;
}

/** Transport timer function. */
static
void tport_tick(su_root_magic_t *magic, su_timer_t *t, tport_master_t *mr)
{
  tport_primary_t *dad;
  tport_t *tp, *tp_next;
  su_time_t now = su_now();
  int ts = su_time_ms(now);

  /* Go through all primary transports */
  for (dad = mr->mr_primaries; dad; dad = dad->pri_next) {
    if (dad->pri_protocol == IPPROTO_SCTP) {
      /* Go through all SCTP connections */

      tp = dad->pri_secondary;

      for (tp = tprb_first(tp); tp; tp = tp_next) {
	tp_next = tprb_succ(tp);
	if (tp->tp_queue && tp->tp_queue[tp->tp_qhead]) {
	  SU_DEBUG_9(("tport_tick(%p) - trying to send to %s/%s:%s\n", 
		      tp, tp->tp_protoname, tp->tp_host, tp->tp_port));
	  tport_send_queue(tp);
	}
      }      
    }

    /* Go through all secondary transports with incomplete messages */
    for (tp = tprb_first(dad->pri_secondary); tp; tp = tp_next) {
      msg_t *msg = tp->tp_msg;
      int closed;

      if (msg &&
	  tp->tp_params->tpp_timeout != UINT_MAX && 
	  tp->tp_params->tpp_timeout < ts - (int)tp->tp_time &&
	  !msg_is_streaming(msg)) {
	SU_DEBUG_5(("tport_tick(%p): incomplete message idle for %d ms\n",
		    tp, ts - (int)tp->tp_time));
	msg_set_streaming(msg, 0);
	msg_set_flags(msg, MSG_FLG_ERROR | MSG_FLG_TRUNC | MSG_FLG_TIMEOUT);
	tport_deliver(tp, msg, NULL, NULL, now);
	tp->tp_msg = NULL;
      }

      tp_next = tprb_succ(tp);

      if (tp->tp_refs)
	continue;

      closed = tport_is_closed(tp);

      if (!closed &&
	  !(tp->tp_params->tpp_idle > 0 
	    && tp->tp_params->tpp_idle < ts - (int)tp->tp_time)) {
	continue;
      }

      if (closed) {
	SU_DEBUG_5(("tport_tick(%p): closed, zapping\n", tp));
      } else {
	SU_DEBUG_5(("tport_tick(%p): unused for %d ms, closing and zapping\n",
		    tp, ts - (int)tp->tp_time));
	if (!tport_is_closed(tp))
	  tport_close(tp);
      }

      tport_zap_secondary(tp);
    }
  }

  su_timer_set(t, tport_tick, mr);
}

/** Flush idle connections. */
int tport_flush(tport_t *tp)
{
  tport_t *tp_next;

  if (tp == NULL)
    return -1;

  /* Go through all secondary transports, zap idle ones */
  for (tp = tprb_first(tp->tp_pri->pri_secondary); tp; tp = tp_next) {
    tp_next = tprb_succ(tp);

    if (tp->tp_refs != 0)
      continue;

    SU_DEBUG_1(("tport_flush(%p): %szapping\n",
		tp, tport_is_closed(tp) ? "" : "closing and "));
    if (!tport_is_closed(tp))
      tport_close(tp);
    tport_zap_secondary(tp);
  }

  return 0;
}

/**Convert sockaddr_t to a transport name.
 *
 * @retval 0 when successful
 * @retval -1 upon an error
 */
int tport_convert_addr(su_home_t *home,
		       tp_name_t *tpn,
		       char const *protoname,
		       char const *canon,
		       su_sockaddr_t const *su)
{
  tp_name_t name[1] = {{ NULL }};
  char const *host;
  char buf[TPORT_HOSTPORTSIZE];
  char port[8];
  int canonlen = canon ? strlen(canon) : 0;

  if (!SU_SOCKADDR_INADDR_ANY(su))
    host = tport_hostport(buf, sizeof(buf), su, 0);
  else if (canonlen && su->su_family == AF_INET && 
	   strspn(canon, "0123456789.") == canonlen)
    host = canon;
  else if (canonlen && su->su_family == AF_INET6 && 
	   strspn(canon, "0123456789abcdefABCDEF:.") == canonlen)
    host = canon;
  else
    host = localipname(su->su_family, buf, sizeof(buf));

  if (host == NULL)
    return -1;

  snprintf(port, sizeof(port), "%u", ntohs(su->su_port));
  
  name->tpn_proto = protoname;
  name->tpn_host = host;
  name->tpn_canon = canon ? canon : host;
  name->tpn_port = port;

  return tport_name_dup(home, tpn, name);
}

/** Set transport object name. @internal
 */
static
int tport_setname(tport_t *self,
		  char const *protoname,
		  su_sockaddr_t const *su,
		  char const *canon)
{
  if (tport_convert_addr(self->tp_home, self->tp_name, 
			 protoname, canon, su) < 0)
    return -1;

  if (tport_is_secondary(self))
    self->tp_ident = self->tp_pri->pri_primary->tp_ident;

  return 0;
}

/**Resolve protocol name.
 *
 * Convert a protocol name to IP protocol number and socket type used by
 * su_getaddrinfo().
 *
 * @param hints hints with the protocol number and socktype [OUT]
 * @param proto protocol name [IN]
 * @param flags hint flags      
 */
static
int getprotohints(su_addrinfo_t *hints, 
		  char const *proto,
		  int flags)
{
  memset(hints, 0, sizeof *hints);

  hints->ai_flags = flags;

#if HAVE_TLS
  if (strcasecmp(proto, "tls") == 0)
    proto = "tcp";
#endif

#if HAVE_SCTP  
  if (strcasecmp(proto, "sctp") == 0) {
    hints->ai_protocol = IPPROTO_SCTP;
    hints->ai_socktype = SOCK_STREAM;
    return 0;
  }
#endif

  if (strcasecmp(proto, "udp") == 0) {
    hints->ai_protocol = IPPROTO_UDP;
    hints->ai_socktype = SOCK_DGRAM;
    return 0;
  }
  
  if (strcasecmp(proto, "tcp") == 0) {
    hints->ai_protocol = IPPROTO_TCP;
    hints->ai_socktype = SOCK_STREAM;
    return 0;
  }

  return -1;
}

/** Get local IP.
 *
 * Get primary local IP address in URI format (IPv6 address will be
 * []-quoted).
 */
static
char *localipname(int pf, char *buf, int bufsiz)
{
  su_localinfo_t *li = NULL, hints[1] = {{ LI_NUMERIC | LI_CANONNAME }};
  int n, error;

  hints->li_family = pf;

  if (pf == AF_INET6) {
    /* Link-local addresses are not usable on IPv6 */
    hints->li_scope = LI_SCOPE_GLOBAL | LI_SCOPE_SITE /* | LI_SCOPE_HOST */;
  }

  if ((error = su_getlocalinfo(hints, &li))) {
    if (error == ELI_NOADDRESS && pf == AF_INET6) {
      hints->li_family = AF_INET;
      error = su_getlocalinfo(hints, &li);
      if (error == ELI_NOADDRESS) {
	hints->li_family = AF_INET6; hints->li_scope |= LI_SCOPE_HOST;
	error = su_getlocalinfo(hints, &li);
      }
      if (error == ELI_NOADDRESS) {
	hints->li_family = AF_INET;
	error = su_getlocalinfo(hints, &li);
      }
    }
    if (error) {
      SU_DEBUG_1(("tport: su_getlocalinfo: %s\n", su_gli_strerror(error)));
      return NULL;
    }
  }

  assert(li); assert(li->li_canonname);

  n = strlen(li->li_canonname);

  if (li->li_family == AF_INET) {
    if (n >= bufsiz)
      return NULL;
    
    memcpy(buf, li->li_canonname, n + 1);
  }
  else {
    if (n + 2 >= bufsiz)
      return NULL;

    memcpy(buf + 1, li->li_canonname, n);
    buf[0] = '['; buf[++n] = ']'; buf[++n] = '\0';
  }
      
  su_freelocalinfo(li);
  
  return buf;
}

/** Process errors from transport. */
static void tport_error_report(tport_t *self, int errcode, 
			       su_sockaddr_t const *addr)
{
  char const *errmsg;

  if (errcode == 0)
    return;
  else if (errcode > 0)
    errmsg = su_strerror(errcode);
  else
    errcode = 0, errmsg = "stream closed";

  if (addr && addr->su_family == AF_UNSPEC)
    addr = NULL;

  /* Mark this connection as unusable */
  if (errcode > 0 && tport_is_connected(self))
    self->tp_send_close = 2, self->tp_recv_close = 1;

  if (addr == NULL && tport_is_connection_oriented(self))
    addr = self->tp_addr;

  /* Report error */
  if (addr && tport_pending_error(self, addr, errcode))
    ;
  else if (self->tp_master->mr_tpac->tpac_error) {
    char *dstname = NULL;
    char hp[TPORT_HOSTPORTSIZE];

    if (addr)
      dstname = tport_hostport(hp, sizeof hp, addr, 1);

    STACK_ERROR(self, errcode, dstname);
  }
  else {
    if (tport_is_primary(self))
      SU_DEBUG_3(("%s(%p): %s (with %s)\n", __func__, self, 
		  errmsg, self->tp_protoname));
    else
      SU_DEBUG_3(("%s(%p): %s (with %s/%s:%s)\n", __func__, self, 
		  errmsg, self->tp_protoname, self->tp_host, self->tp_port));
  }

  /* Close connection */
  if (!self->tp_closed && errcode > 0 && tport_is_connected(self))
    tport_close(self);
}

/** Accept a new connection.
 * 
 * The function tport_accept() accepts a new connection and creates a
 * secondary transport object for the new socket.
 */
static 
int tport_accept(su_root_magic_t *m, su_wait_t *w, tport_t *_pri)
{
  tport_primary_t *pri = _pri->tp_pri;
  tport_t *self;
  su_sockaddr_t su[1]; 
  socklen_t sulen = sizeof(su);
  su_socket_t s = SOCKET_ERROR, l = pri->pri_primary->tp_socket;
  int events = su_wait_events(w, l);
  int one = 1;

  assert(pri == _pri->tp_pri);

  if (events & SU_WAIT_ERR)
    tport_error_event(pri->pri_primary, events);

  if (!(events & SU_WAIT_ACCEPT))
    return 0;

  s = accept(l, &su->su_sa, &sulen);

  if (s < 0) {
    tport_error_report(pri->pri_primary, su_errno(), NULL);
    return 0;
  }

  setsockopt(s, SOL_TCP, TCP_NODELAY, &one, sizeof one);

  SU_CANONIZE_SOCKADDR(su);

  /* Alloc a new transport object, then register socket events with it */ 
  self = tport_alloc_secondary(pri);

  if (self) {
    int i;
    su_wakeup_f wakeup = tport_recv;
    int events = SU_WAIT_IN|SU_WAIT_ERR|SU_WAIT_HUP;
    su_wait_t wait[1] = { SU_WAIT_INIT };
    
    self->tp_socket = s;

    if (pri->pri_socktype == SOCK_STREAM)
      su_setblocking(s, 0);

#if HAVE_TLS
    if (pri->pri_primary->tp_tls)
      self->tp_tls = tls_init_slave(pri->pri_primary->tp_tls, s);
#endif

    if (
#if HAVE_TLS
	!pri->pri_primary->tp_tls == !self->tp_tls &&
#endif
	/* Create wait object with appropriate events. */
	su_wait_create(wait, s, events) != -1 
	/* Register socket to root */
	&&
	(i = su_root_register(self->tp_master->mr_root, wait, wakeup, self, 0)) != -1) {

      self->tp_index     = i;
      self->tp_connected = 1;
      self->tp_events   = events;
      self->tp_addr[0]  = su[0];
      self->tp_addrlen  = sulen;

#if HAVE_TLS
      if (self->tp_tls && events != tls_events(self->tp_tls, events))
	tport_events(self);
#endif

      if (tport_setname(self, pri->pri_protoname, su, NULL) != -1) {
#if HAVE_SIGCOMP
	if (!pri->pri_primary->tp_name->tpn_comp)
	  self->tp_sigcomp->sc_infmt = format_is_noncomp;
#endif
	SU_DEBUG_5(("%s(%p): new connection from " TPN_FORMAT "\n", 
		    __func__,  self, TPN_ARGS(self->tp_name)));

	tprb_append(&pri->pri_secondary, self);

	/* Return succesfully */
	return 0;
      }
    }
    else
      su_wait_destroy(wait);

    /* Failure: shutdown socket,  */
    tport_close(self);
    tport_zap_secondary(self);
  }
  else {
    su_close(s);
  }

  /* XXX - report error ? */

  return 0;
}

/** Allocate a new message object */
msg_t *tport_msg_alloc(tport_t const *self, unsigned size)
{
  if (self) {
    tport_master_t *mr = self->tp_master;
    msg_t *msg = mr->mr_tpac->tpac_alloc(mr->mr_stack, mr->mr_msg_flags,
				  NULL, size, self, NULL);
    if (msg) {
      msg_addrinfo(msg)->ai_family =   self->tp_pri->pri_family;
      msg_addrinfo(msg)->ai_protocol = self->tp_pri->pri_protocol;
      msg_addrinfo(msg)->ai_socktype = self->tp_pri->pri_socktype;
    }

    return msg;
  }
  else {
    return NULL;
  }
}

/** Process events for connected socket
 */
static int tport_recv(su_root_magic_t *magic, su_wait_t *w, tport_t *self)
{
  int events = su_wait_events(w, self->tp_socket);
#if HAVE_TLS
  int old_mask = 0, new_mask;
  
  if (self->tp_tls)
    old_mask = tls_events(self->tp_tls, self->tp_events);
#endif

  SU_DEBUG_7(("tport_recv(%p): events%s%s%s%s\n", self,
	      events & SU_WAIT_IN ? " IN" : "",
	      events & SU_WAIT_HUP ? " HUP" : "",
	      events & SU_WAIT_OUT ? " OUT" : "",
	      events & SU_WAIT_ERR ? " ERR" : ""));

2778
#if HAVE_POLL
Pekka Pessi's avatar
Pekka Pessi committed
2779
  assert(w->fd == self->tp_socket);
2780
#endif
Pekka Pessi's avatar
Pekka Pessi committed
2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195

  if (events & SU_WAIT_ERR)
    tport_error_event(self, events);

#if HAVE_TLS
  if (self->tp_tls)
    events = tport_tls_event(self, events);
#endif

  if ((events & SU_WAIT_OUT) && !self->tp_closed)
    tport_send_event(self, events);

  if ((events & SU_WAIT_IN) && !self->tp_closed)
    tport_recv_event(self, events);
  
  if ((events & SU_WAIT_HUP) && !self->tp_closed)
    tport_hup_event(self, events);

#if HAVE_TLS
  if (self->tp_tls && !self->tp_closed) {
    new_mask = tls_events(self->tp_tls, self->tp_events);

    if (old_mask ^ new_mask)
      tport_events(self);
  }
#endif

  return 0;
}

#if HAVE_TLS
/** Handle TLS events */
int tport_tls_event(tport_t *self, int events)
{
  int ret, fake_events = 0;
  
  if ((self->tp_events & SU_WAIT_IN) && !self->tp_closed) {
    ret = tls_want_read(self->tp_tls, events);
    if (ret > 0)
      fake_events |= SU_WAIT_IN;
    else if (ret < 0)
      tport_error_report(self, errno, NULL);
  }
  
  if ((self->tp_events & SU_WAIT_OUT) && !self->tp_closed) {
    ret = tls_want_write(self->tp_tls, events);
    if (ret > 0)
      fake_events |= SU_WAIT_OUT;
    else if (ret < 0)
      tport_error_report(self, errno, NULL);
  }
  
  events &= ~(SU_WAIT_IN | SU_WAIT_OUT);
  events |= fake_events;

  return events;
}
#endif

/** Stop reading from socket until tport_continue() is called. */
int tport_stall(tport_t *self)
{
  if (self == NULL)
    return -1;

  self->tp_events &= ~SU_WAIT_IN;

  return tport_events(self);
}

/** Continue reading from socket. */
int tport_continue(tport_t *self)
{
  if (self == NULL || self->tp_recv_close)
    return -1;

  self->tp_events |= SU_WAIT_IN;

  return tport_events(self);
}

/** Process "hangup" event.
 *
 */
static void tport_hup_event(tport_t *self, int events)
{
  SU_DEBUG_7(("%s(%p)\n", __func__, self));

  if (self->tp_msg) {
    su_time_t now = su_now();
    msg_recv_commit(self->tp_msg, 0, 1);
    tport_parse(self, 1, now);
  }

  /* End of stream */
  tport_shutdown(self, 0);
}

static int tport_recv_data(tport_t *self);

/** Process "re