PageRenderTime 116ms CodeModel.GetById 21ms app.highlight 80ms RepoModel.GetById 1ms app.codeStats 1ms

/src/openvpn/socket.c

https://github.com/Papafox/openvpn
C | 3368 lines | 2764 code | 359 blank | 245 comment | 509 complexity | 14e5c0419f15fac569f68b62947d6310 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/*
   2 *  OpenVPN -- An application to securely tunnel IP networks
   3 *             over a single TCP/UDP port, with support for SSL/TLS-based
   4 *             session authentication and key exchange,
   5 *             packet encryption, packet authentication, and
   6 *             packet compression.
   7 *
   8 *  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
   9 *
  10 *  This program is free software; you can redistribute it and/or modify
  11 *  it under the terms of the GNU General Public License version 2
  12 *  as published by the Free Software Foundation.
  13 *
  14 *  This program is distributed in the hope that it will be useful,
  15 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17 *  GNU General Public License for more details.
  18 *
  19 *  You should have received a copy of the GNU General Public License
  20 *  along with this program (see the file COPYING included with this
  21 *  distribution); if not, write to the Free Software Foundation, Inc.,
  22 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  23 */
  24
  25#ifdef HAVE_CONFIG_H
  26#include "config.h"
  27#elif defined(_MSC_VER)
  28#include "config-msvc.h"
  29#endif
  30
  31#include "syshead.h"
  32
  33#include "socket.h"
  34#include "fdmisc.h"
  35#include "misc.h"
  36#include "gremlin.h"
  37#include "plugin.h"
  38#include "ps.h"
  39#include "manage.h"
  40#include "misc.h"
  41#include "manage.h"
  42
  43#include "memdbg.h"
  44
  45const int proto_overhead[] = { /* indexed by PROTO_x */
  46  0,
  47  IPv4_UDP_HEADER_SIZE, /* IPv4 */
  48  IPv4_TCP_HEADER_SIZE,
  49  IPv4_TCP_HEADER_SIZE,
  50  IPv6_UDP_HEADER_SIZE, /* IPv6 */
  51  IPv6_TCP_HEADER_SIZE,
  52  IPv6_TCP_HEADER_SIZE,
  53  IPv6_TCP_HEADER_SIZE,
  54};
  55
  56/*
  57 * Convert sockflags/getaddr_flags into getaddr_flags
  58 */
  59static unsigned int
  60sf2gaf(const unsigned int getaddr_flags,
  61       const unsigned int sockflags)
  62{
  63  if (sockflags & SF_HOST_RANDOMIZE)
  64    return getaddr_flags | GETADDR_RANDOMIZE;
  65  else
  66    return getaddr_flags;
  67}
  68
  69/*
  70 * Functions related to the translation of DNS names to IP addresses.
  71 */
  72
  73static const char*
  74h_errno_msg(int h_errno_err)
  75{
  76  switch (h_errno_err)
  77    {
  78    case HOST_NOT_FOUND:
  79      return "[HOST_NOT_FOUND] The specified host is unknown.";
  80    case NO_DATA:
  81      return "[NO_DATA] The requested name is valid but does not have an IP address.";
  82    case NO_RECOVERY:
  83      return "[NO_RECOVERY] A non-recoverable name server error occurred.";
  84    case TRY_AGAIN:
  85      return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
  86    }
  87  return "[unknown h_errno value]";
  88}
  89
  90/*
  91 * Translate IP addr or hostname to in_addr_t.
  92 * If resolve error, try again for
  93 * resolve_retry_seconds seconds.
  94 */
  95in_addr_t
  96getaddr (unsigned int flags,
  97         const char *hostname,
  98         int resolve_retry_seconds,
  99         bool *succeeded,
 100         volatile int *signal_received)
 101{
 102  struct addrinfo *ai;
 103  int status;
 104  status = openvpn_getaddrinfo(flags, hostname, resolve_retry_seconds,
 105							   signal_received, AF_INET, &ai);
 106  if(status==0) {
 107    struct in_addr ia;
 108    if(succeeded)
 109      *succeeded=true;
 110    ia = ((struct sockaddr_in*)ai->ai_addr)->sin_addr;
 111    freeaddrinfo(ai);
 112    return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
 113  } else {
 114    if(succeeded)
 115      *succeeded =false;
 116    return 0;
 117  }
 118}
 119
 120
 121/*
 122 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
 123 * If resolve error, try again for resolve_retry_seconds seconds.
 124 */
 125int
 126openvpn_getaddrinfo (unsigned int flags,
 127                     const char *hostname,
 128                     int resolve_retry_seconds,
 129                     volatile int *signal_received,
 130                     int ai_family,
 131                     struct addrinfo **res)
 132{
 133  struct addrinfo hints;
 134  int status;
 135  int sigrec = 0;
 136  int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
 137  struct gc_arena gc = gc_new ();
 138
 139  ASSERT(res);
 140
 141#if defined(HAVE_RES_INIT)
 142  res_init ();
 143#endif
 144
 145  if (!hostname)
 146    hostname = "::";
 147
 148  if (flags & GETADDR_RANDOMIZE)
 149    hostname = hostname_randomize(hostname, &gc);
 150
 151  if (flags & GETADDR_MSG_VIRT_OUT)
 152    msglevel |= M_MSG_VIRT_OUT;
 153
 154  if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
 155      && !signal_received)
 156    signal_received = &sigrec;
 157
 158  /* try numeric ipv6 addr first */
 159  CLEAR(hints);
 160  hints.ai_family = ai_family;
 161  hints.ai_flags = AI_NUMERICHOST;
 162  hints.ai_socktype = SOCK_STREAM;
 163
 164  status = getaddrinfo(hostname, NULL, &hints, res);
 165
 166  if (status != 0) /* parse as numeric address failed? */
 167    {
 168      const int fail_wait_interval = 5; /* seconds */
 169      int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
 170      const char *fmt;
 171      int level = 0;
 172
 173      fmt = "RESOLVE: Cannot resolve host address: %s: %s";
 174      if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
 175          && !resolve_retry_seconds)
 176        fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
 177
 178      if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
 179        {
 180          msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
 181          goto done;
 182        }
 183
 184#ifdef ENABLE_MANAGEMENT
 185      if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
 186        {
 187          if (management)
 188            management_set_state (management,
 189                                  OPENVPN_STATE_RESOLVE,
 190                                  NULL,
 191                                  (in_addr_t)0,
 192                                  (in_addr_t)0);
 193        }
 194#endif
 195
 196      /*
 197       * Resolve hostname
 198       */
 199      while (true)
 200        {
 201          /* try hostname lookup */
 202          hints.ai_flags = 0;
 203          dmsg (D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
 204                flags, hints.ai_family, hints.ai_socktype);
 205          status = getaddrinfo(hostname, NULL, &hints, res);
 206
 207          if (signal_received)
 208            {
 209              get_signal (signal_received);
 210              if (*signal_received) /* were we interrupted by a signal? */
 211                {
 212                  if (0 == status) {
 213                    ASSERT(res);
 214                    freeaddrinfo(*res);
 215                    res = NULL;
 216                  }
 217                  if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
 218                    {
 219                      msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
 220                      *signal_received = 0;
 221                    }
 222                  else
 223                    goto done;
 224                }
 225            }
 226
 227          /* success? */
 228          if (0 == status)
 229            break;
 230
 231          /* resolve lookup failed, should we
 232             continue or fail? */
 233          level = msglevel;
 234          if (resolve_retries > 0)
 235            level = D_RESOLVE_ERRORS;
 236
 237          msg (level,
 238               fmt,
 239               hostname,
 240               gai_strerror(status));
 241
 242          if (--resolve_retries <= 0)
 243            goto done;
 244
 245          openvpn_sleep (fail_wait_interval);
 246        }
 247
 248      ASSERT(res);
 249
 250      /* hostname resolve succeeded */
 251
 252      /* Do not chose an IP Addresse by random or change the order *
 253       * of IP addresses, doing so will break RFC 3484 address selection *
 254       */
 255    }
 256  else
 257    {
 258      /* IP address parse succeeded */
 259    }
 260
 261 done:
 262  if (signal_received && *signal_received)
 263    {
 264      int level = 0;
 265      if (flags & GETADDR_FATAL_ON_SIGNAL)
 266        level = M_FATAL;
 267      else if (flags & GETADDR_WARN_ON_SIGNAL)
 268        level = M_WARN;
 269      msg (level, "RESOLVE: signal received during DNS resolution attempt");
 270    }
 271
 272  gc_free (&gc);
 273  return status;
 274}
 275
 276/*
 277 * We do our own inet_aton because the glibc function
 278 * isn't very good about error checking.
 279 */
 280int
 281openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
 282{
 283  unsigned int a, b, c, d;
 284
 285  CLEAR (*addr);
 286  if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
 287    {
 288      if (a < 256 && b < 256 && c < 256 && d < 256)
 289	{
 290	  addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
 291	  return OIA_IP; /* good dotted quad */
 292	}
 293    }
 294  if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
 295    return OIA_ERROR;    /* probably a badly formatted dotted quad */
 296  else
 297    return OIA_HOSTNAME; /* probably a hostname */
 298}
 299
 300bool
 301ip_addr_dotted_quad_safe (const char *dotted_quad)
 302{
 303  /* verify non-NULL */
 304  if (!dotted_quad)
 305    return false;
 306
 307  /* verify length is within limits */
 308  if (strlen (dotted_quad) > 15)
 309    return false;
 310
 311  /* verify that all chars are either numeric or '.' and that no numeric
 312     substring is greater than 3 chars */
 313  {
 314    int nnum = 0;
 315    const char *p = dotted_quad;
 316    int c;
 317
 318    while ((c = *p++))
 319      {
 320	if (c >= '0' && c <= '9')
 321	  {
 322	    ++nnum;
 323	    if (nnum > 3)
 324	      return false;
 325	  }
 326	else if (c == '.')
 327	  {
 328	    nnum = 0;
 329	  }
 330	else
 331	  return false;
 332      }
 333  }
 334
 335  /* verify that string will convert to IP address */
 336  {
 337    struct in_addr a;
 338    return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
 339  }
 340}
 341
 342bool
 343ipv6_addr_safe (const char *ipv6_text_addr)
 344{
 345  /* verify non-NULL */
 346  if (!ipv6_text_addr)
 347    return false;
 348
 349  /* verify length is within limits */
 350  if (strlen (ipv6_text_addr) > INET6_ADDRSTRLEN )
 351    return false;
 352
 353  /* verify that string will convert to IPv6 address */
 354  {
 355    struct in6_addr a6;
 356    return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
 357  }
 358}
 359
 360static bool
 361dns_addr_safe (const char *addr)
 362{
 363  if (addr)
 364    {
 365      const size_t len = strlen (addr);
 366      return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
 367    }
 368  else
 369    return false;
 370}
 371
 372bool
 373ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
 374{
 375  if (ip_addr_dotted_quad_safe (addr))
 376    return true;
 377  else if (allow_fqdn)
 378    return dns_addr_safe (addr);
 379  else
 380    return false;
 381}
 382
 383bool
 384mac_addr_safe (const char *mac_addr)
 385{
 386  /* verify non-NULL */
 387  if (!mac_addr)
 388    return false;
 389
 390  /* verify length is within limits */
 391  if (strlen (mac_addr) > 17)
 392    return false;
 393
 394  /* verify that all chars are either alphanumeric or ':' and that no
 395     alphanumeric substring is greater than 2 chars */
 396  {
 397    int nnum = 0;
 398    const char *p = mac_addr;
 399    int c;
 400
 401    while ((c = *p++))
 402      {
 403	if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
 404	  {
 405	    ++nnum;
 406	    if (nnum > 2)
 407	      return false;
 408	  }
 409	else if (c == ':')
 410	  {
 411	    nnum = 0;
 412	  }
 413	else
 414	  return false;
 415      }
 416  }
 417
 418  /* error-checking is left to script invoked in lladdr.c */
 419  return true;
 420}
 421
 422static void
 423update_remote (const char* host,
 424	       struct openvpn_sockaddr *addr,
 425	       bool *changed,
 426	       const unsigned int sockflags)
 427{
 428  switch(addr->addr.sa.sa_family)
 429    {
 430    case AF_INET:
 431      if (host && addr)
 432	{
 433	  const in_addr_t new_addr = getaddr (
 434					      sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
 435					      host,
 436					      1,
 437					      NULL,
 438					      NULL);
 439	  if (new_addr && addr->addr.in4.sin_addr.s_addr != new_addr)
 440	    {
 441	      addr->addr.in4.sin_addr.s_addr = new_addr;
 442	      *changed = true;
 443	    }
 444	}
 445      break;
 446    case AF_INET6:
 447      if (host && addr)
 448        {
 449          int status;
 450          struct addrinfo* ai;
 451
 452		  status = openvpn_getaddrinfo(sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags), host, 1, NULL, AF_INET6, &ai);
 453
 454          if ( status ==0 )
 455            {
 456			  struct sockaddr_in6 sin6;
 457			  CLEAR(sin6);
 458			  sin6 = *((struct sockaddr_in6*)ai->ai_addr);
 459              if (!IN6_ARE_ADDR_EQUAL(&sin6.sin6_addr, &addr->addr.in6.sin6_addr))
 460              {
 461                int port = addr->addr.in6.sin6_port;
 462                /* ipv6 requires also eg. sin6_scope_id => easier to fully copy and override port */
 463                addr->addr.in6 = sin6; 
 464                addr->addr.in6.sin6_port = port;
 465              }
 466			  freeaddrinfo(ai);
 467            }
 468        }
 469      break;
 470    default:
 471        ASSERT(0);
 472  }
 473}
 474
 475static int
 476socket_get_sndbuf (int sd)
 477{
 478#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
 479  int val;
 480  socklen_t len;
 481
 482  len = sizeof (val);
 483  if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
 484      && len == sizeof (val))
 485    return val;
 486#endif
 487  return 0;
 488}
 489
 490static void
 491socket_set_sndbuf (int sd, int size)
 492{
 493#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
 494  if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
 495    {
 496      if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
 497	{
 498	  msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
 499	}
 500    }
 501#endif
 502}
 503
 504static int
 505socket_get_rcvbuf (int sd)
 506{
 507#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
 508  int val;
 509  socklen_t len;
 510
 511  len = sizeof (val);
 512  if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
 513      && len == sizeof (val))
 514    return val;
 515#endif
 516  return 0;
 517}
 518
 519static bool
 520socket_set_rcvbuf (int sd, int size)
 521{
 522#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
 523  if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
 524    {
 525      if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
 526	{
 527	  msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
 528	  return false;
 529	}
 530    }
 531  return true;
 532#endif
 533}
 534
 535static void
 536socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
 537{
 538  if (sbs)
 539    {
 540      const int sndbuf_old = socket_get_sndbuf (fd);
 541      const int rcvbuf_old = socket_get_rcvbuf (fd);
 542
 543      if (sbs->sndbuf)
 544	socket_set_sndbuf (fd, sbs->sndbuf);
 545
 546      if (sbs->rcvbuf)
 547	socket_set_rcvbuf (fd, sbs->rcvbuf);
 548       
 549      msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
 550	   rcvbuf_old,
 551	   socket_get_rcvbuf (fd),
 552	   sndbuf_old,
 553	   socket_get_sndbuf (fd));
 554    }
 555}
 556
 557/*
 558 * Set other socket options
 559 */
 560
 561static bool
 562socket_set_tcp_nodelay (int sd, int state)
 563{
 564#if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
 565  if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
 566    {
 567      msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
 568      return false;
 569    }
 570  else
 571    {
 572      dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
 573      return true;
 574    }
 575#else
 576  msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
 577  return false;
 578#endif
 579}
 580
 581static inline void
 582socket_set_mark (int sd, int mark)
 583{
 584#if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
 585  if (mark && setsockopt (sd, SOL_SOCKET, SO_MARK, &mark, sizeof (mark)) != 0)
 586    msg (M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
 587#endif
 588}
 589
 590static bool
 591socket_set_flags (int sd, unsigned int sockflags)
 592{
 593  if (sockflags & SF_TCP_NODELAY)
 594    return socket_set_tcp_nodelay (sd, 1);
 595  else
 596    return true;
 597}
 598
 599bool
 600link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
 601{
 602  if (ls && socket_defined (ls->sd))
 603    return socket_set_flags (ls->sd, ls->sockflags = sockflags);
 604  else
 605    return false;
 606}
 607
 608void
 609link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
 610{
 611  if (ls && socket_defined (ls->sd))
 612    {
 613      ls->socket_buffer_sizes.sndbuf = sndbuf;
 614      ls->socket_buffer_sizes.rcvbuf = rcvbuf;
 615      socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
 616    }
 617}
 618
 619/*
 620 * SOCKET INITALIZATION CODE.
 621 * Create a TCP/UDP socket
 622 */
 623
 624socket_descriptor_t
 625create_socket_tcp (int af)
 626{
 627  socket_descriptor_t sd;
 628
 629  if ((sd = socket (af, SOCK_STREAM, IPPROTO_TCP)) < 0)
 630    msg (M_ERR, "Cannot create TCP socket");
 631
 632#ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
 633  /* set SO_REUSEADDR on socket */
 634  {
 635    int on = 1;
 636    if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
 637		    (void *) &on, sizeof (on)) < 0)
 638      msg (M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
 639  }
 640#endif
 641
 642  return sd;
 643}
 644
 645static socket_descriptor_t
 646create_socket_udp (const unsigned int flags)
 647{
 648  socket_descriptor_t sd;
 649
 650  if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
 651    msg (M_ERR, "UDP: Cannot create UDP socket");
 652#if ENABLE_IP_PKTINFO
 653  else if (flags & SF_USE_IP_PKTINFO)
 654    {
 655      int pad = 1;
 656#ifdef IP_PKTINFO
 657      if (setsockopt (sd, SOL_IP, IP_PKTINFO,
 658		      (void*)&pad, sizeof(pad)) < 0)
 659        msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
 660#elif defined(IP_RECVDSTADDR)
 661      if (setsockopt (sd, IPPROTO_IP, IP_RECVDSTADDR,
 662		      (void*)&pad, sizeof(pad)) < 0)
 663        msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
 664#else
 665#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 666#endif
 667    }
 668#endif
 669  return sd;
 670}
 671
 672static socket_descriptor_t
 673create_socket_udp6 (const unsigned int flags)
 674{
 675  socket_descriptor_t sd;
 676
 677  if ((sd = socket (PF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
 678    msg (M_ERR, "UDP: Cannot create UDP6 socket");
 679#if ENABLE_IP_PKTINFO
 680  else if (flags & SF_USE_IP_PKTINFO)
 681    {
 682      int pad = 1;
 683#ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
 684      if (setsockopt (sd, IPPROTO_IPV6, IPV6_PKTINFO,
 685		      (void*)&pad, sizeof(pad)) < 0)
 686#else
 687      if (setsockopt (sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
 688		      (void*)&pad, sizeof(pad)) < 0)
 689#endif
 690	msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
 691    }
 692#endif
 693  return sd;
 694}
 695
 696static void
 697create_socket (struct link_socket *sock)
 698{
 699  /* create socket */
 700  if (sock->info.proto == PROTO_UDPv4)
 701    {
 702      sock->sd = create_socket_udp (sock->sockflags);
 703      sock->sockflags |= SF_GETADDRINFO_DGRAM;
 704
 705#ifdef ENABLE_SOCKS
 706      if (sock->socks_proxy)
 707	sock->ctrl_sd = create_socket_tcp (AF_INET);
 708#endif
 709    }
 710  else if (sock->info.proto == PROTO_TCPv4_SERVER
 711	   || sock->info.proto == PROTO_TCPv4_CLIENT)
 712    {
 713      sock->sd = create_socket_tcp (AF_INET);
 714    }
 715  else if (sock->info.proto == PROTO_TCPv6_SERVER
 716	   || sock->info.proto == PROTO_TCPv6_CLIENT)
 717    {
 718      sock->sd = create_socket_tcp (AF_INET6);
 719    }
 720  else if (sock->info.proto == PROTO_UDPv6)
 721    {
 722      sock->sd = create_socket_udp6 (sock->sockflags);
 723      sock->sockflags |= SF_GETADDRINFO_DGRAM;
 724    }
 725  else
 726    {
 727      ASSERT (0);
 728    }
 729#ifdef TARGET_ANDROID
 730  /* pass socket FD to management interface to pass on to VPNService API
 731   * as "protected socket" (exempt from being routed into tunnel)
 732   */
 733
 734  management->connection.fdtosend = sock->sd;
 735  management_android_control (management, "PROTECTFD", __func__);
 736#endif
 737
 738}
 739
 740/*
 741 * Functions used for establishing a TCP stream connection.
 742 */
 743
 744static void
 745socket_do_listen (socket_descriptor_t sd,
 746		  const struct openvpn_sockaddr *local,
 747		  bool do_listen,
 748		  bool do_set_nonblock)
 749{
 750  struct gc_arena gc = gc_new ();
 751  if (do_listen)
 752    {
 753      msg (M_INFO, "Listening for incoming TCP connection on %s", 
 754	   print_sockaddr (local, &gc));
 755      if (listen (sd, 1))
 756	msg (M_ERR, "TCP: listen() failed");
 757    }
 758
 759  /* set socket to non-blocking mode */
 760  if (do_set_nonblock)
 761    set_nonblock (sd);
 762
 763  gc_free (&gc);
 764}
 765
 766socket_descriptor_t
 767socket_do_accept (socket_descriptor_t sd,
 768		  struct link_socket_actual *act,
 769		  const bool nowait)
 770{
 771  /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
 772   * are compiled because act is empty here.
 773   * could use getsockname() to support later remote_len check
 774   */
 775  socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
 776  socklen_t remote_len = sizeof(act->dest.addr);
 777  socket_descriptor_t new_sd = SOCKET_UNDEFINED;
 778
 779  CLEAR (*act);
 780
 781#ifdef HAVE_GETPEERNAME
 782  if (nowait)
 783    {
 784      new_sd = getpeername (sd, &act->dest.addr.sa, &remote_len);
 785
 786      if (!socket_defined (new_sd))
 787	msg (D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
 788      else
 789	new_sd = sd;
 790    }
 791#else
 792  if (nowait)
 793    msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
 794#endif
 795  else
 796    {
 797      new_sd = accept (sd, &act->dest.addr.sa, &remote_len);
 798    }
 799
 800#if 0 /* For debugging only, test the effect of accept() failures */
 801 {
 802   static int foo = 0;
 803   ++foo;
 804   if (foo & 1)
 805     new_sd = -1;
 806 }
 807#endif
 808
 809  if (!socket_defined (new_sd))
 810    {
 811      msg (D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", sd);
 812    }
 813  /* only valid if we have remote_len_af!=0 */
 814  else if (remote_len_af && remote_len != remote_len_af)
 815    {
 816      msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
 817      openvpn_close_socket (new_sd);
 818      new_sd = SOCKET_UNDEFINED;
 819    }
 820  return new_sd;
 821}
 822
 823static void
 824tcp_connection_established (const struct link_socket_actual *act)
 825{
 826  struct gc_arena gc = gc_new ();
 827  msg (M_INFO, "TCP connection established with %s", 
 828       print_link_socket_actual (act, &gc));
 829  gc_free (&gc);
 830}
 831
 832static int
 833socket_listen_accept (socket_descriptor_t sd,
 834		      struct link_socket_actual *act,
 835		      const char *remote_dynamic,
 836		      bool *remote_changed,
 837		      const struct openvpn_sockaddr *local,
 838		      bool do_listen,
 839		      bool nowait,
 840		      volatile int *signal_received)
 841{
 842  struct gc_arena gc = gc_new ();
 843  /* struct openvpn_sockaddr *remote = &act->dest; */
 844  struct openvpn_sockaddr remote_verify = act->dest;
 845  int new_sd = SOCKET_UNDEFINED;
 846
 847  CLEAR (*act);
 848  socket_do_listen (sd, local, do_listen, true);
 849
 850  while (true)
 851    {
 852      int status;
 853      fd_set reads;
 854      struct timeval tv;
 855
 856      FD_ZERO (&reads);
 857      FD_SET (sd, &reads);
 858      tv.tv_sec = 0;
 859      tv.tv_usec = 0;
 860
 861      status = select (sd + 1, &reads, NULL, NULL, &tv);
 862
 863      get_signal (signal_received);
 864      if (*signal_received)
 865	{
 866	  gc_free (&gc);
 867	  return sd;
 868	}
 869
 870      if (status < 0)
 871	msg (D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
 872
 873      if (status <= 0)
 874	{
 875	  openvpn_sleep (1);
 876	  continue;
 877	}
 878
 879      new_sd = socket_do_accept (sd, act, nowait);
 880
 881      if (socket_defined (new_sd))
 882	{
 883	  update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
 884	  if (addr_defined (&remote_verify)
 885	      && !addr_match (&remote_verify, &act->dest))
 886	    {
 887	      msg (M_WARN,
 888		   "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
 889		   print_link_socket_actual (act, &gc));
 890	      if (openvpn_close_socket (new_sd))
 891		msg (M_ERR, "TCP: close socket failed (new_sd)");
 892	    }
 893	  else
 894	    break;
 895	}
 896      openvpn_sleep (1);
 897    }
 898
 899  if (!nowait && openvpn_close_socket (sd))
 900    msg (M_ERR, "TCP: close socket failed (sd)");
 901
 902  tcp_connection_established (act);
 903
 904  gc_free (&gc);
 905  return new_sd;
 906}
 907
 908void
 909socket_bind (socket_descriptor_t sd,
 910             struct openvpn_sockaddr *local,
 911	     const char *prefix)
 912{
 913  struct gc_arena gc = gc_new ();
 914
 915  if (bind (sd, &local->addr.sa, af_addr_size(local->addr.sa.sa_family)))
 916    {
 917      const int errnum = openvpn_errno ();
 918      msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
 919	   prefix,
 920           print_sockaddr (local, &gc),
 921           strerror_ts (errnum, &gc));
 922    }
 923  gc_free (&gc);
 924}
 925
 926int
 927openvpn_connect (socket_descriptor_t sd,
 928		 struct openvpn_sockaddr *remote,
 929		 int connect_timeout,
 930		 volatile int *signal_received)
 931{
 932  int status = 0;
 933
 934#ifdef CONNECT_NONBLOCK
 935  set_nonblock (sd);
 936  status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
 937  if (status)
 938    status = openvpn_errno ();
 939  if (
 940#ifdef WIN32
 941    status == WSAEWOULDBLOCK
 942#else
 943    status == EINPROGRESS
 944#endif
 945  )
 946    {
 947      while (true)
 948	{
 949	  fd_set writes;
 950	  struct timeval tv;
 951
 952	  FD_ZERO (&writes);
 953	  FD_SET (sd, &writes);
 954	  tv.tv_sec = 0;
 955	  tv.tv_usec = 0;
 956
 957	  status = select (sd + 1, NULL, &writes, NULL, &tv);
 958
 959	  if (signal_received)
 960	    {
 961	      get_signal (signal_received);
 962	      if (*signal_received)
 963		{
 964		  status = 0;
 965		  break;
 966		}
 967	    }
 968	  if (status < 0)
 969	    {
 970	      status = openvpn_errno ();
 971	      break;
 972	    }
 973	  if (status <= 0)
 974	    {
 975	      if (--connect_timeout < 0)
 976		{
 977		  status = ETIMEDOUT;
 978		  break;
 979		}
 980	      openvpn_sleep (1);
 981	      continue;
 982	    }
 983
 984	  /* got it */
 985	  {
 986	    int val = 0;
 987	    socklen_t len;
 988
 989	    len = sizeof (val);
 990	    if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
 991		&& len == sizeof (val))
 992	      status = val;
 993	    else
 994	      status = openvpn_errno ();
 995	    break;
 996	  }
 997	}
 998    }
 999#else
1000  status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
1001  if (status)
1002    status = openvpn_errno ();
1003#endif
1004
1005  return status;
1006}
1007
1008void
1009socket_connect (socket_descriptor_t *sd,
1010                struct openvpn_sockaddr *local,
1011                bool bind_local,
1012		struct openvpn_sockaddr *remote,
1013		const bool connection_profiles_defined,
1014		const char *remote_dynamic,
1015		bool *remote_changed,
1016		const int connect_retry_seconds,
1017		const int connect_timeout,
1018		const int connect_retry_max,
1019		const unsigned int sockflags,
1020		volatile int *signal_received)
1021{
1022  struct gc_arena gc = gc_new ();
1023  int retry = 0;
1024
1025#ifdef CONNECT_NONBLOCK
1026  msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]", 
1027       print_sockaddr (remote, &gc));
1028#else
1029  msg (M_INFO, "Attempting to establish TCP connection with %s", 
1030       print_sockaddr (remote, &gc));
1031#endif
1032
1033  while (true)
1034    {
1035      int status;
1036
1037#ifdef ENABLE_MANAGEMENT
1038      if (management)
1039	management_set_state (management,
1040			      OPENVPN_STATE_TCP_CONNECT,
1041			      NULL,
1042			      (in_addr_t)0,
1043			      (in_addr_t)0);
1044#endif
1045
1046      status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
1047
1048      get_signal (signal_received);
1049      if (*signal_received)
1050	goto done;
1051
1052      if (!status)
1053	break;
1054
1055      msg (D_LINK_ERRORS,
1056	   "TCP: connect to %s failed, will try again in %d seconds: %s",
1057	   print_sockaddr (remote, &gc),
1058	   connect_retry_seconds,
1059	   strerror_ts (status, &gc));
1060
1061      gc_reset (&gc);
1062
1063      openvpn_close_socket (*sd);
1064      *sd = SOCKET_UNDEFINED;
1065
1066      if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
1067	{
1068	  *signal_received = SIGUSR1;
1069	  goto done;
1070	}
1071
1072      openvpn_sleep (connect_retry_seconds);
1073
1074      get_signal (signal_received);
1075      if (*signal_received)
1076	goto done;
1077
1078	*sd = create_socket_tcp (local->addr.sa.sa_family);
1079
1080      if (bind_local)
1081        socket_bind (*sd, local, "TCP Client");
1082      update_remote (remote_dynamic, remote, remote_changed, sockflags);
1083    }
1084
1085  msg (M_INFO, "TCP connection established with %s", 
1086       print_sockaddr (remote, &gc));
1087
1088 done:
1089  gc_free (&gc);
1090}
1091
1092/* For stream protocols, allocate a buffer to build up packet.
1093   Called after frame has been finalized. */
1094
1095static void
1096socket_frame_init (const struct frame *frame, struct link_socket *sock)
1097{
1098#ifdef WIN32
1099  overlapped_io_init (&sock->reads, frame, FALSE, false);
1100  overlapped_io_init (&sock->writes, frame, TRUE, false);
1101  sock->rw_handle.read = sock->reads.overlapped.hEvent;
1102  sock->rw_handle.write = sock->writes.overlapped.hEvent;
1103#endif
1104
1105  if (link_socket_connection_oriented (sock))
1106    {
1107#ifdef WIN32
1108      stream_buf_init (&sock->stream_buf,
1109		       &sock->reads.buf_init,
1110		       sock->sockflags,
1111		       sock->info.proto);
1112#else
1113      alloc_buf_sock_tun (&sock->stream_buf_data,
1114			  frame,
1115			  false,
1116			  FRAME_HEADROOM_MARKER_READ_STREAM);
1117
1118      stream_buf_init (&sock->stream_buf,
1119		       &sock->stream_buf_data,
1120		       sock->sockflags,
1121		       sock->info.proto);
1122#endif
1123    }
1124}
1125
1126/*
1127 * Adjust frame structure based on a Path MTU value given
1128 * to us by the OS.
1129 */
1130void
1131frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
1132{
1133  frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
1134}
1135
1136static void
1137resolve_bind_local (struct link_socket *sock)
1138{
1139  struct gc_arena gc = gc_new ();
1140
1141  /* resolve local address if undefined */
1142  if (!addr_defined (&sock->info.lsa->local))
1143    {
1144      /* may return AF_{INET|INET6} guessed from local_host */
1145      switch(addr_guess_family(sock->info.proto, sock->local_host))
1146	{
1147	case AF_INET:
1148	  sock->info.lsa->local.addr.in4.sin_family = AF_INET;
1149	  sock->info.lsa->local.addr.in4.sin_addr.s_addr =
1150	    (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1151					 sock->local_host,
1152					 0,
1153					 NULL,
1154					 NULL)
1155	     : htonl (INADDR_ANY));
1156	  sock->info.lsa->local.addr.in4.sin_port = htons (sock->local_port);
1157	  break;
1158	case AF_INET6:
1159	    {
1160	      int status;
1161	      int err;
1162	      CLEAR(sock->info.lsa->local.addr.in6);
1163	      if (sock->local_host)
1164		{
1165		  struct addrinfo *ai;
1166
1167		  status = openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1168									   sock->local_host, 0, NULL, AF_INET6, &ai);
1169		  if(status ==0) {
1170			  sock->info.lsa->local.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
1171			  freeaddrinfo(ai);
1172		  }
1173		}
1174	      else
1175		{
1176		  sock->info.lsa->local.addr.in6.sin6_family = AF_INET6;
1177		  sock->info.lsa->local.addr.in6.sin6_addr = in6addr_any;
1178		  status = 0;
1179		}
1180	      if (!status == 0)
1181		{
1182		  msg (M_FATAL, "getaddr6() failed for local \"%s\": %s",
1183		       sock->local_host,
1184		       gai_strerror(err));
1185		}
1186	      sock->info.lsa->local.addr.in6.sin6_port = htons (sock->local_port);
1187	    }
1188	  break;
1189	}
1190    }
1191  
1192  /* bind to local address/port */
1193  if (sock->bind_local)
1194    {
1195#ifdef ENABLE_SOCKS
1196      if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
1197          socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
1198      else
1199#endif
1200          socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
1201    }
1202  gc_free (&gc);
1203}
1204
1205static void
1206resolve_remote (struct link_socket *sock,
1207		int phase,
1208		const char **remote_dynamic,
1209		volatile int *signal_received)
1210{
1211  struct gc_arena gc = gc_new ();
1212  int af;
1213
1214  if (!sock->did_resolve_remote)
1215    {
1216      /* resolve remote address if undefined */
1217      if (!addr_defined (&sock->info.lsa->remote))
1218	{
1219          af = addr_guess_family(sock->info.proto, sock->remote_host);
1220          switch(af)
1221            {
1222              case AF_INET:
1223                sock->info.lsa->remote.addr.in4.sin_family = AF_INET;
1224                sock->info.lsa->remote.addr.in4.sin_addr.s_addr = 0;
1225                break;
1226              case AF_INET6:
1227                CLEAR(sock->info.lsa->remote.addr.in6);
1228                sock->info.lsa->remote.addr.in6.sin6_family = AF_INET6;
1229                sock->info.lsa->remote.addr.in6.sin6_addr = in6addr_any;
1230                break;
1231            }
1232
1233	  if (sock->remote_host)
1234	    {
1235	      unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
1236	      int retry = 0;
1237	      int status = -1;
1238
1239	      if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1240		{
1241		  if (phase == 2)
1242		    flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1243		  retry = 0;
1244		}
1245	      else if (phase == 1)
1246		{
1247		  if (sock->resolve_retry_seconds)
1248		    {
1249		      retry = 0;
1250		    }
1251		  else
1252		    {
1253		      flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1254		      retry = 0;
1255		    }
1256		}
1257	      else if (phase == 2)
1258		{
1259		  if (sock->resolve_retry_seconds)
1260		    {
1261		      flags |= GETADDR_FATAL;
1262		      retry = sock->resolve_retry_seconds;
1263		    }
1264		  else
1265		    {
1266		      ASSERT (0);
1267		    }
1268		}
1269	      else
1270		{
1271		  ASSERT (0);
1272		}
1273
1274		  struct addrinfo* ai;
1275		  /* Temporary fix, this need to be changed for dual stack */
1276		  status = openvpn_getaddrinfo(flags, sock->remote_host, retry,
1277											  signal_received, af, &ai);
1278		  if(status == 0) {
1279			  sock->info.lsa->remote.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
1280			  freeaddrinfo(ai);
1281
1282			  dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1283					flags,
1284					phase,
1285					retry,
1286					signal_received ? *signal_received : -1,
1287					status);
1288		  }
1289	      if (signal_received)
1290		{
1291		  if (*signal_received)
1292		    goto done;
1293		}
1294	      if (status!=0)
1295		{
1296		  if (signal_received)
1297		    *signal_received = SIGUSR1;
1298		  goto done;
1299		}
1300	    }
1301          switch(af)
1302            {
1303              case AF_INET:
1304                sock->info.lsa->remote.addr.in4.sin_port = htons (sock->remote_port);
1305                break;
1306              case AF_INET6:
1307                sock->info.lsa->remote.addr.in6.sin6_port = htons (sock->remote_port);
1308                break;
1309            }
1310	}
1311  
1312      /* should we re-use previous active remote address? */
1313      if (link_socket_actual_defined (&sock->info.lsa->actual))
1314	{
1315	  msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1316	       print_link_socket_actual (&sock->info.lsa->actual, &gc));
1317	  if (remote_dynamic)
1318	    *remote_dynamic = NULL;
1319	}
1320      else
1321	{
1322	  CLEAR (sock->info.lsa->actual);
1323	  sock->info.lsa->actual.dest = sock->info.lsa->remote;
1324	}
1325
1326      /* remember that we finished */
1327      sock->did_resolve_remote = true;
1328    }
1329
1330 done:
1331  gc_free (&gc);
1332}
1333
1334struct link_socket *
1335link_socket_new (void)
1336{
1337  struct link_socket *sock;
1338
1339  ALLOC_OBJ_CLEAR (sock, struct link_socket);
1340  sock->sd = SOCKET_UNDEFINED;
1341#ifdef ENABLE_SOCKS
1342  sock->ctrl_sd = SOCKET_UNDEFINED;
1343#endif
1344  return sock;
1345}
1346
1347/* bind socket if necessary */
1348void
1349link_socket_init_phase1 (struct link_socket *sock,
1350			 const bool connection_profiles_defined,
1351			 const char *local_host,
1352			 int local_port,
1353			 const char *remote_host,
1354			 int remote_port,
1355			 int proto,
1356			 int mode,
1357			 const struct link_socket *accept_from,
1358#ifdef ENABLE_HTTP_PROXY
1359			 struct http_proxy_info *http_proxy,
1360#endif
1361#ifdef ENABLE_SOCKS
1362			 struct socks_proxy_info *socks_proxy,
1363#endif
1364#ifdef ENABLE_DEBUG
1365			 int gremlin,
1366#endif
1367			 bool bind_local,
1368			 bool remote_float,
1369			 int inetd,
1370			 struct link_socket_addr *lsa,
1371			 const char *ipchange_command,
1372			 const struct plugin_list *plugins,
1373			 int resolve_retry_seconds,
1374			 int connect_retry_seconds,
1375			 int connect_timeout,
1376			 int connect_retry_max,
1377			 int mtu_discover_type,
1378			 int rcvbuf,
1379			 int sndbuf,
1380			 int mark,
1381			 unsigned int sockflags)
1382{
1383  ASSERT (sock);
1384
1385  sock->connection_profiles_defined = connection_profiles_defined;
1386
1387  sock->local_host = local_host;
1388  sock->local_port = local_port;
1389  sock->remote_host = remote_host;
1390  sock->remote_port = remote_port;
1391
1392#ifdef ENABLE_HTTP_PROXY
1393  sock->http_proxy = http_proxy;
1394#endif
1395
1396#ifdef ENABLE_SOCKS
1397  sock->socks_proxy = socks_proxy;
1398#endif
1399
1400  sock->bind_local = bind_local;
1401  sock->inetd = inetd;
1402  sock->resolve_retry_seconds = resolve_retry_seconds;
1403  sock->connect_retry_seconds = connect_retry_seconds;
1404  sock->connect_timeout = connect_timeout;
1405  sock->connect_retry_max = connect_retry_max;
1406  sock->mtu_discover_type = mtu_discover_type;
1407
1408#ifdef ENABLE_DEBUG
1409  sock->gremlin = gremlin;
1410#endif
1411
1412  sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1413  sock->socket_buffer_sizes.sndbuf = sndbuf;
1414
1415  sock->sockflags = sockflags;
1416
1417  sock->info.proto = proto;
1418  sock->info.remote_float = remote_float;
1419  sock->info.lsa = lsa;
1420  sock->info.ipchange_command = ipchange_command;
1421  sock->info.plugins = plugins;
1422
1423  sock->mode = mode;
1424  if (mode == LS_MODE_TCP_ACCEPT_FROM)
1425    {
1426      ASSERT (accept_from);
1427      ASSERT (sock->info.proto == PROTO_TCPv4_SERVER
1428	      || sock->info.proto == PROTO_TCPv6_SERVER
1429	     );
1430      ASSERT (!sock->inetd);
1431      sock->sd = accept_from->sd;
1432    }
1433
1434  if (false)
1435    ;
1436#ifdef ENABLE_HTTP_PROXY
1437  /* are we running in HTTP proxy mode? */
1438  else if (sock->http_proxy)
1439    {
1440      ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
1441      ASSERT (!sock->inetd);
1442
1443      /* the proxy server */
1444      sock->remote_host = http_proxy->options.server;
1445      sock->remote_port = http_proxy->options.port;
1446
1447      /* the OpenVPN server we will use the proxy to connect to */
1448      sock->proxy_dest_host = remote_host;
1449      sock->proxy_dest_port = remote_port;
1450    }
1451#endif
1452#ifdef ENABLE_SOCKS
1453  /* or in Socks proxy mode? */
1454  else if (sock->socks_proxy)
1455    {
1456      ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
1457      ASSERT (!sock->inetd);
1458
1459      /* the proxy server */
1460      sock->remote_host = socks_proxy->server;
1461      sock->remote_port = socks_proxy->port;
1462
1463      /* the OpenVPN server we will use the proxy to connect to */
1464      sock->proxy_dest_host = remote_host;
1465      sock->proxy_dest_port = remote_port;
1466    }
1467#endif
1468  else
1469    {
1470      sock->remote_host = remote_host;
1471      sock->remote_port = remote_port;
1472    }
1473
1474  /* bind behavior for TCP server vs. client */
1475  if (sock->info.proto == PROTO_TCPv4_SERVER)
1476    {
1477      if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1478	sock->bind_local = false;
1479      else
1480	sock->bind_local = true;
1481    }
1482
1483  /* were we started by inetd or xinetd? */
1484  if (sock->inetd)
1485    {
1486      ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT
1487	      && sock->info.proto != PROTO_TCPv6_CLIENT);
1488      ASSERT (socket_defined (inetd_socket_descriptor));
1489      sock->sd = inetd_socket_descriptor;
1490    }
1491  else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1492    {
1493      create_socket (sock);
1494
1495      /* set socket buffers based on --sndbuf and --rcvbuf options */
1496      socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
1497
1498      /* set socket to --mark packets with given value */
1499      socket_set_mark (sock->sd, mark);
1500
1501      resolve_bind_local (sock);
1502      resolve_remote (sock, 1, NULL, NULL);
1503    }
1504}
1505
1506/* finalize socket initialization */
1507void
1508link_socket_init_phase2 (struct link_socket *sock,
1509			 const struct frame *frame,
1510			 volatile int *signal_received)
1511{
1512  struct gc_arena gc = gc_new ();
1513  const char *remote_dynamic = NULL;
1514  bool remote_changed = false;
1515  int sig_save = 0;
1516
1517  ASSERT (sock);
1518
1519  if (signal_received && *signal_received)
1520    {
1521      sig_save = *signal_received;
1522      *signal_received = 0;
1523    }
1524
1525  /* initialize buffers */
1526  socket_frame_init (frame, sock);
1527
1528  /*
1529   * Pass a remote name to connect/accept so that
1530   * they can test for dynamic IP address changes
1531   * and throw a SIGUSR1 if appropriate.
1532   */
1533  if (sock->resolve_retry_seconds)
1534    remote_dynamic = sock->remote_host;
1535
1536  /* were we started by inetd or xinetd? */
1537  if (sock->inetd)
1538    {
1539      if (sock->info.proto == PROTO_TCPv4_SERVER
1540	  || sock->info.proto == PROTO_TCPv6_SERVER) {
1541	/* AF_INET as default (and fallback) for inetd */
1542	sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
1543#ifdef HAVE_GETSOCKNAME
1544	  {
1545	    /* inetd: hint family type for dest = local's */
1546	    struct openvpn_sockaddr local_addr;
1547	    socklen_t addrlen = sizeof(local_addr);
1548	    if (getsockname (sock->sd, (struct sockaddr *)&local_addr, &addrlen) == 0) {
1549	      sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
1550	      dmsg (D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
1551		    proto2ascii(sock->info.proto, false), local_addr.addr.sa.sa_family,
1552		    sock->sd);
1553	    } else
1554	      msg (M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
1555		   proto2ascii(sock->info.proto, false), sock->sd);
1556	  }
1557#else
1558	msg (M_WARN, "inetd(%s): this OS does not provide the getsockname() "
1559	     "function, using AF_INET",
1560	     proto2ascii(sock->info.proto, false));
1561#endif
1562	sock->sd =
1563	  socket_listen_accept (sock->sd,
1564				&sock->info.lsa->actual,
1565				remote_dynamic,
1566				&remote_changed,
1567				&sock->info.lsa->local,
1568				false,
1569				sock->inetd == INETD_NOWAIT,
1570				signal_received);
1571      }
1572      ASSERT (!remote_changed);
1573      if (*signal_received)
1574	goto done;
1575    }
1576  else
1577    {
1578      resolve_remote (sock, 2, &remote_dynamic, signal_received);
1579
1580      if (*signal_received)
1581	goto done;
1582
1583      /* TCP client/server */
1584      if (sock->info.proto == PROTO_TCPv4_SERVER
1585	  ||sock->info.proto == PROTO_TCPv6_SERVER)
1586	{
1587	  switch (sock->mode)
1588	    {
1589	    case LS_MODE_DEFAULT:
1590	      sock->sd = socket_listen_accept (sock->sd,
1591					       &sock->info.lsa->actual,
1592					       remote_dynamic,
1593					       &remote_changed,
1594					       &sock->info.lsa->local,
1595					       true,
1596					       false,
1597					       signal_received);
1598	      break;
1599	    case LS_MODE_TCP_LISTEN:
1600	      socket_do_listen (sock->sd,
1601				&sock->info.lsa->local,
1602				true,
1603				false);
1604	      break;
1605	    case LS_MODE_TCP_ACCEPT_FROM:
1606	      sock->sd = socket_do_accept (sock->sd,
1607					   &sock->info.lsa->actual,
1608					   false);
1609	      if (!socket_defined (sock->sd))
1610		{
1611		  *signal_received = SIGTERM;
1612		  goto done;
1613		}
1614	      tcp_connection_established (&sock->info.lsa->actual);
1615	      break;
1616	    default:
1617	      ASSERT (0);
1618	    }
1619	}
1620      else if (sock->info.proto == PROTO_TCPv4_CLIENT
1621	       ||sock->info.proto == PROTO_TCPv6_CLIENT)
1622	{
1623
1624#ifdef GENERAL_PROXY_SUPPORT
1625	  bool proxy_retry = false;
1626#else
1627	  const bool proxy_retry = false;
1628#endif
1629	  do {
1630	    socket_connect (&sock->sd,
1631			    &sock->info.lsa->local,
1632			    sock->bind_local,
1633			    &sock->info.lsa->actual.dest,
1634			    sock->connection_profiles_defined,
1635			    remote_dynamic,
1636			    &remote_changed,
1637			    sock->connect_retry_seconds,
1638			    sock->connect_timeout,
1639			    sock->connect_retry_max,
1640			    sock->sockflags,
1641			    signal_received);
1642
1643	    if (*signal_received)
1644	      goto done;
1645
1646	    if (false)
1647	      ;
1648#ifdef ENABLE_HTTP_PROXY
1649	    else if (sock->http_proxy)
1650	      {
1651		proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1652							     sock->sd,
1653							     sock->proxy_dest_host,
1654							     sock->proxy_dest_port,
1655							     &sock->stream_buf.residual,
1656							     signal_received);
1657	      }
1658#endif
1659#ifdef ENABLE_SOCKS
1660	    else if (sock->socks_proxy)
1661	      {
1662		establish_socks_proxy_passthru (sock->socks_proxy,
1663						sock->sd,
1664						sock->proxy_dest_host,
1665						sock->proxy_dest_port,
1666						signal_received);
1667	      }
1668#endif
1669	    if (proxy_retry)
1670	      {
1671		openvpn_close_socket (sock->sd);
1672		sock->sd = create_socket_tcp (AF_INET);
1673	      }
1674	  } while (proxy_retry);
1675	}
1676#ifdef ENABLE_SOCKS
1677      else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1678	{
1679	  socket_connect (&sock->ctrl_sd,
1680                          &sock->info.lsa->local,
1681                          sock->bind_local,
1682			  &sock->info.lsa->actual.dest,
1683			  sock->connection_profiles_defined,
1684			  remote_dynamic,
1685			  &remote_changed,
1686			  sock->connect_retry_seconds,
1687			  sock->connect_timeout,
1688			  sock->connect_retry_max,
1689			  sock->sockflags,
1690			  signal_received);
1691
1692	  if (*signal_received)
1693	    goto done;
1694
1695	  establish_socks_proxy_udpassoc (sock->socks_proxy,
1696					  sock->ctrl_sd,
1697					  sock->sd,
1698					  &sock->socks_relay.dest,
1699					  signal_received);
1700
1701	  if (*signal_received)
1702	    goto done;
1703
1704	  sock->remote_host = sock->proxy_dest_host;
1705	  sock->remote_port = sock->proxy_dest_port;
1706	  sock->did_resolve_remote = false;
1707
1708	  addr_zero_host(&sock->info.lsa->actual.dest);
1709	  addr_zero_host(&sock->info.lsa->remote);
1710
1711	  resolve_remote (sock, 1, NULL, signal_received);
1712
1713	  if (*signal_received)
1714	    goto done;
1715	}
1716#endif
1717
1718      if (*signal_received)
1719	goto done;
1720
1721      if (remote_changed)
1722	{
1723	  msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1724	  addr_copy_host(&sock->info.lsa->remote, &sock->info.lsa->actual.dest);
1725	}
1726    }
1727
1728  /* set misc socket parameters */
1729  socket_set_flags (sock->sd, sock->sockflags);
1730
1731  /* set socket to non-blocking mode */
1732  set_nonblock (sock->sd);
1733
1734  /* set socket file descriptor to not pass across execs, so that
1735     scripts don't have access to it */
1736  set_cloexec (sock->sd);
1737
1738#ifdef ENABLE_SOCKS
1739  if (socket_defined (sock->ctrl_sd))
1740    set_cloexec (sock->ctrl_sd);
1741#endif
1742
1743  /* set Path MTU discovery options on the socket */
1744  set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1745
1746#if EXTENDED_SOCKET_ERROR_CAPABILITY
1747  /* if the OS supports it, enable extended error passing on the socket */
1748  set_sock_extended_error_passing (sock->sd);
1749#endif
1750
1751  /* print local address */
1752  {
1753    const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
1754
1755    if (sock->inetd)
1756      msg (msglevel, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1757    else
1758      msg (msglevel, "%s link local%s: %s",
1759	   proto2ascii (sock->info.proto, true),
1760	   (sock->bind_local ? " (bound)" : ""),
1761	   print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
1762
1763    /* print active remote address */
1764    msg (msglevel, "%s link remote: %s",
1765	 proto2ascii (sock->info.proto, true),
1766	 print_link_socket_actual_ex (&sock->info.lsa->actual,
1767				      ":",
1768				      PS_SHOW_PORT_IF_DEFINED,
1769				      &gc));
1770  }
1771
1772 done:
1773  if (sig_save && signal_received)
1774    {
1775      if (!*signal_received)
1776	*signal_received = sig_save;
1777    }
1778  gc_free (&gc);
1779}
1780
1781void
1782link_socket_close (struct link_socket *sock)
1783{
1784  if (sock)
1785    {
1786#ifdef ENABLE_DEBUG
1787      const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1788#else
1789      const int gremlin = 0;
1790#endif
1791
1792      if (socket_defined (sock->sd))
1793	{
1794#ifdef WIN32
1795	  close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1796#endif
1797	  if (!gremlin)
1798	    {
1799	      msg (D_LOW, "TCP/UDP: Closing socket");
1800	      if (openvpn_close_socket (sock->sd))
1801		msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
1802	    }
1803	  sock->sd = SOCKET_UNDEFINED;
1804#ifdef WIN32
1805	  if (!gremlin)
1806	    {
1807	      overlapped_io_close (&sock->reads);
1808	      overlapped_io_close (&sock->writes);
1809	    }
1810#endif
1811	}
1812
1813#ifdef ENABLE_SOCKS
1814      if (socket_defined (sock->ctrl_sd))
1815	{
1816	  if (openvpn_close_socket (sock->ctrl_sd))
1817	    msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
1818	  sock->ctrl_sd = SOCKET_UNDEFINED;
1819	}
1820#endif
1821
1822      stream_buf_close (&sock->stream_buf);
1823      free_buf (&sock->stream_buf_data);
1824      if (!gremlin)
1825	free (sock);
1826    }
1827}
1828
1829/* for stream protocols, allow for packet length prefix */
1830void
1831socket_adjust_frame_parameters (struct frame *frame, int proto)
1832{
1833  if (link_socket_proto_connection_oriented (proto))
1834    frame_add_to_extra_frame (frame, sizeof (packet_size_type));
1835}
1836
1837void
1838setenv_trusted (struct env_set *es, const struct link_socket_info *info)
1839{
1840  setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
1841}
1842
1843static void
1844ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
1845{
1846  const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
1847  const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
1848  if (include_cmd)
1849    argv_printf (argv, "%sc %s %s",
1850		 info->ipchange_command,
1851		 ip,
1852		 port);
1853  else
1854    argv_printf (argv, "%s %s",
1855		 ip,
1856		 port);
1857}
1858
1859void
1860link_socket_connection_initiated (const struct buffer *buf,
1861				  struct link_socket_info *info,
1862				  const struct link_socket_actual *act,
1863				  const char *common_name,
1864				  struct env_set *es)
1865{
1866  struct gc_arena gc = gc_new ();
1867  
1868  info->lsa->actual = *act; /* Note: skip this line for --force-dest */
1869  setenv_trusted (es, info);
1870  info->connection_established = true;
1871
1872  /* Print connection initiated message, with common name if available */
1873  {
1874    struct buffer out = alloc_buf_gc (256, &gc);
1875    if (common_name)
1876      buf_printf (&out, "[%s] ", common_name);
1877    buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
1878    msg (M_INFO, "%s", BSTR (&out));
1879  }
1880
1881  /* set environmental vars */
1882  setenv_str (es, "common_name", common_name);
1883
1884  /* Process --ipchange plugin */
1885  if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1886    {
1887      struct argv argv = argv_new ();
1888      ipchange_fmt (false, &argv, info, &gc);
1889      if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1890	msg (M_WARN, "WARNING: ipchange plugin call failed");
1891      argv_reset (&argv);
1892    }
1893
1894  /* Process --ipchange option */
1895  if (info->ipchange_command)
1896    {
1897      struct argv argv = argv_new ();
1898      setenv_str (es, "script_type", "ipchange");
1899      ipchange_fmt (true, &argv, info, &gc);
1900      openvpn_run_script (&argv, es, 0, "--ipchange");
1901      argv_reset (&argv);
1902    }
1903
1904  gc_free (&gc);
1905}
1906
1907void
1908link_socket_bad_incoming_addr (struct buffer *buf,
1909			       const struct link_socket_info *info,
1910			       const struct link_socket_actual *from_addr)
1911{
1912  struct gc_arena gc = gc_new ();
1913
1914  switch(from_addr->dest.addr.sa.sa_family)
1915    {
1916    case AF_INET:
1917    case AF_INET6:
1918      msg (D_LINK_ERRORS,
1919	   "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1920	   print_link_socket_actual (from_addr, &gc),
1921	   (int)from_addr->dest.addr.sa.sa_family,
1922	   print_sockaddr (&info->lsa->remote, &gc));
1923      break;
1924    }
1925  buf->len = 0;
1926  gc_free (&gc);
1927}
1928
1929void
1930link_socket_bad_outgoing_addr (void)
1931{
1932  dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1933}
1934
1935in_addr_t
1936link_socket_current_remote (const struct link_socket_info *info)
1937{
1938  const struct link_socket_addr *lsa = info->lsa;
1939
1940/* 
1941 * This logic supports "redirect-gateway" semantic, which 
1942 * makes sense only for PF_INET routes over PF_INET endpoints
1943 *
1944 * Maybe in the future consider PF_INET6 endpoints also ...
1945 * by now just ignore it
1946 *
1947 */
1948  if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
1949    return IPV4_INVALID_ADDR;
1950
1951  if (link_socket_actual_defined (&lsa->actual))
1952    return ntohl (lsa->actual.dest.addr.in4.sin_addr.s_addr);
1953  else if (addr_defined (&lsa->remote))
1954    return ntohl (lsa->remote.addr.in4.sin_addr.s_addr);
1955  else
1956    return 0;
1957}
1958
1959/*
1960 * Return a status string describing socket state.
1961 */
1962const char *
1963socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1964{
1965  struct buffer out = alloc_buf_gc (64, gc);
1966  if (s)
1967    {
1968      if (rwflags & EVENT_READ)
1969	{
1970	  buf_printf (&out, "S%s",
1971		      (s->rwflags_debug & EVENT_READ) ? "R" : "r");
1972#ifdef WIN32
1973	  buf_printf (&out, "%s",
1974		      overlapped_io_state_ascii (&s->reads));
1975#endif
1976	}
1977      if (rwflags & EVENT_WRITE)
1978	{
1979	  buf_printf (&out, "S%s",
1980		      (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1981#ifdef WIN32
1982	  buf_printf (&out, "%s",
1983		      overl

Large files files are truncated, but you can click here to view the full file