~ubuntu-branches/ubuntu/saucy/openvpn/saucy-proposed

« back to all changes in this revision

Viewing changes to .pc/close_socket_before_scripts.patch/src/openvpn/socket.c

  • Committer: Package Import Robot
  • Author(s): Stéphane Graber
  • Date: 2013-05-24 17:42:45 UTC
  • mfrom: (1.1.19) (10.2.22 sid)
  • Revision ID: package-import@ubuntu.com-20130524174245-g9y6wlforycufqy5
Tags: 2.3.1-2ubuntu1
* Merge from Debian unstable. Remaining changes:
  - debian/openvpn.init.d:
    + Do not use start-stop-daemon and </dev/null to avoid blocking boot.
    + Show per-VPN result messages.
    + Add "--script-security 2" by default for backwards compatabliity.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
42
#include "memdbg.h"
 
43
 
 
44
const int proto_overhead[] = { /* indexed by PROTO_x */
 
45
  0,
 
46
  IPv4_UDP_HEADER_SIZE, /* IPv4 */
 
47
  IPv4_TCP_HEADER_SIZE,
 
48
  IPv4_TCP_HEADER_SIZE,
 
49
  IPv6_UDP_HEADER_SIZE, /* IPv6 */
 
50
  IPv6_TCP_HEADER_SIZE,
 
51
  IPv6_TCP_HEADER_SIZE,
 
52
  IPv6_TCP_HEADER_SIZE,
 
53
};
 
54
 
 
55
/*
 
56
 * Convert sockflags/getaddr_flags into getaddr_flags
 
57
 */
 
58
static unsigned int
 
59
sf2gaf(const unsigned int getaddr_flags,
 
60
       const unsigned int sockflags)
 
61
{
 
62
  if (sockflags & SF_HOST_RANDOMIZE)
 
63
    return getaddr_flags | GETADDR_RANDOMIZE;
 
64
  else
 
65
    return getaddr_flags;
 
66
}
 
67
 
 
68
/*
 
69
 * Functions related to the translation of DNS names to IP addresses.
 
70
 */
 
71
 
 
72
static const char*
 
73
h_errno_msg(int h_errno_err)
 
74
{
 
75
  switch (h_errno_err)
 
76
    {
 
77
    case HOST_NOT_FOUND:
 
78
      return "[HOST_NOT_FOUND] The specified host is unknown.";
 
79
    case NO_DATA:
 
80
      return "[NO_DATA] The requested name is valid but does not have an IP address.";
 
81
    case NO_RECOVERY:
 
82
      return "[NO_RECOVERY] A non-recoverable name server error occurred.";
 
83
    case TRY_AGAIN:
 
84
      return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
 
85
    }
 
86
  return "[unknown h_errno value]";
 
87
}
 
88
 
 
89
/*
 
90
 * Translate IP addr or hostname to in_addr_t.
 
91
 * If resolve error, try again for
 
92
 * resolve_retry_seconds seconds.
 
93
 */
 
94
in_addr_t
 
95
getaddr (unsigned int flags,
 
96
         const char *hostname,
 
97
         int resolve_retry_seconds,
 
98
         bool *succeeded,
 
99
         volatile int *signal_received)
 
100
{
 
101
  struct addrinfo *ai;
 
102
  int status;
 
103
  status = openvpn_getaddrinfo(flags, hostname, resolve_retry_seconds,
 
104
                                                           signal_received, AF_INET, &ai);
 
105
  if(status==0) {
 
106
    struct in_addr ia;
 
107
    if(succeeded)
 
108
      *succeeded=true;
 
109
    ia = ((struct sockaddr_in*)ai->ai_addr)->sin_addr;
 
110
    freeaddrinfo(ai);
 
111
    return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
 
112
  } else {
 
113
    if(succeeded)
 
114
      *succeeded =false;
 
115
    return 0;
 
116
  }
 
117
}
 
118
 
 
119
 
 
120
/*
 
121
 * Translate IPv4/IPv6 addr or hostname into struct addrinfo
 
122
 * If resolve error, try again for resolve_retry_seconds seconds.
 
123
 */
 
124
int
 
125
openvpn_getaddrinfo (unsigned int flags,
 
126
                     const char *hostname,
 
127
                     int resolve_retry_seconds,
 
128
                     volatile int *signal_received,
 
129
                     int ai_family,
 
130
                     struct addrinfo **res)
 
131
{
 
132
  struct addrinfo hints;
 
133
  int status;
 
134
  int sigrec = 0;
 
135
  int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
 
136
  struct gc_arena gc = gc_new ();
 
137
 
 
138
  ASSERT(res);
 
139
 
 
140
#if defined(HAVE_RES_INIT)
 
141
  res_init ();
 
142
#endif
 
143
 
 
144
  if (!hostname)
 
145
    hostname = "::";
 
146
 
 
147
  if (flags & GETADDR_RANDOMIZE)
 
148
    hostname = hostname_randomize(hostname, &gc);
 
149
 
 
150
  if (flags & GETADDR_MSG_VIRT_OUT)
 
151
    msglevel |= M_MSG_VIRT_OUT;
 
152
 
 
153
  if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
 
154
      && !signal_received)
 
155
    signal_received = &sigrec;
 
156
 
 
157
  /* try numeric ipv6 addr first */
 
158
  CLEAR(hints);
 
159
  hints.ai_family = ai_family;
 
160
  hints.ai_flags = AI_NUMERICHOST;
 
161
  hints.ai_socktype = SOCK_STREAM;
 
162
 
 
163
  status = getaddrinfo(hostname, NULL, &hints, res);
 
164
 
 
165
  if (status != 0) /* parse as numeric address failed? */
 
166
    {
 
167
      const int fail_wait_interval = 5; /* seconds */
 
168
      int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
 
169
      const char *fmt;
 
170
      int level = 0;
 
171
 
 
172
      fmt = "RESOLVE: Cannot resolve host address: %s: %s";
 
173
      if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
 
174
          && !resolve_retry_seconds)
 
175
        fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
 
176
 
 
177
      if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
 
178
        {
 
179
          msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
 
180
          goto done;
 
181
        }
 
182
 
 
183
#ifdef ENABLE_MANAGEMENT
 
184
      if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
 
185
        {
 
186
          if (management)
 
187
            management_set_state (management,
 
188
                                  OPENVPN_STATE_RESOLVE,
 
189
                                  NULL,
 
190
                                  (in_addr_t)0,
 
191
                                  (in_addr_t)0);
 
192
        }
 
193
#endif
 
194
 
 
195
      /*
 
196
       * Resolve hostname
 
197
       */
 
198
      while (true)
 
199
        {
 
200
          /* try hostname lookup */
 
201
          hints.ai_flags = 0;
 
202
          dmsg (D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
 
203
                flags, hints.ai_family, hints.ai_socktype);
 
204
          status = getaddrinfo(hostname, NULL, &hints, res);
 
205
 
 
206
          if (signal_received)
 
207
            {
 
208
              get_signal (signal_received);
 
209
              if (*signal_received) /* were we interrupted by a signal? */
 
210
                {
 
211
                  if (0 == status) {
 
212
                    ASSERT(res);
 
213
                    freeaddrinfo(*res);
 
214
                    res = NULL;
 
215
                  }
 
216
                  if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
 
217
                    {
 
218
                      msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
 
219
                      *signal_received = 0;
 
220
                    }
 
221
                  else
 
222
                    goto done;
 
223
                }
 
224
            }
 
225
 
 
226
          /* success? */
 
227
          if (0 == status)
 
228
            break;
 
229
 
 
230
          /* resolve lookup failed, should we
 
231
             continue or fail? */
 
232
          level = msglevel;
 
233
          if (resolve_retries > 0)
 
234
            level = D_RESOLVE_ERRORS;
 
235
 
 
236
          msg (level,
 
237
               fmt,
 
238
               hostname,
 
239
               gai_strerror(status));
 
240
 
 
241
          if (--resolve_retries <= 0)
 
242
            goto done;
 
243
 
 
244
          openvpn_sleep (fail_wait_interval);
 
245
        }
 
246
 
 
247
      ASSERT(res);
 
248
 
 
249
      /* hostname resolve succeeded */
 
250
 
 
251
      /* Do not chose an IP Addresse by random or change the order *
 
252
       * of IP addresses, doing so will break RFC 3484 address selection *
 
253
       */
 
254
    }
 
255
  else
 
256
    {
 
257
      /* IP address parse succeeded */
 
258
    }
 
259
 
 
260
 done:
 
261
  if (signal_received && *signal_received)
 
262
    {
 
263
      int level = 0;
 
264
      if (flags & GETADDR_FATAL_ON_SIGNAL)
 
265
        level = M_FATAL;
 
266
      else if (flags & GETADDR_WARN_ON_SIGNAL)
 
267
        level = M_WARN;
 
268
      msg (level, "RESOLVE: signal received during DNS resolution attempt");
 
269
    }
 
270
 
 
271
  gc_free (&gc);
 
272
  return status;
 
273
}
 
274
 
 
275
/*
 
276
 * We do our own inet_aton because the glibc function
 
277
 * isn't very good about error checking.
 
278
 */
 
279
int
 
280
openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
 
281
{
 
282
  unsigned int a, b, c, d;
 
283
 
 
284
  CLEAR (*addr);
 
285
  if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
 
286
    {
 
287
      if (a < 256 && b < 256 && c < 256 && d < 256)
 
288
        {
 
289
          addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
 
290
          return OIA_IP; /* good dotted quad */
 
291
        }
 
292
    }
 
293
  if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
 
294
    return OIA_ERROR;    /* probably a badly formatted dotted quad */
 
295
  else
 
296
    return OIA_HOSTNAME; /* probably a hostname */
 
297
}
 
298
 
 
299
bool
 
300
ip_addr_dotted_quad_safe (const char *dotted_quad)
 
301
{
 
302
  /* verify non-NULL */
 
303
  if (!dotted_quad)
 
304
    return false;
 
305
 
 
306
  /* verify length is within limits */
 
307
  if (strlen (dotted_quad) > 15)
 
308
    return false;
 
309
 
 
310
  /* verify that all chars are either numeric or '.' and that no numeric
 
311
     substring is greater than 3 chars */
 
312
  {
 
313
    int nnum = 0;
 
314
    const char *p = dotted_quad;
 
315
    int c;
 
316
 
 
317
    while ((c = *p++))
 
318
      {
 
319
        if (c >= '0' && c <= '9')
 
320
          {
 
321
            ++nnum;
 
322
            if (nnum > 3)
 
323
              return false;
 
324
          }
 
325
        else if (c == '.')
 
326
          {
 
327
            nnum = 0;
 
328
          }
 
329
        else
 
330
          return false;
 
331
      }
 
332
  }
 
333
 
 
334
  /* verify that string will convert to IP address */
 
335
  {
 
336
    struct in_addr a;
 
337
    return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
 
338
  }
 
339
}
 
340
 
 
341
bool
 
342
ipv6_addr_safe (const char *ipv6_text_addr)
 
343
{
 
344
  /* verify non-NULL */
 
345
  if (!ipv6_text_addr)
 
346
    return false;
 
347
 
 
348
  /* verify length is within limits */
 
349
  if (strlen (ipv6_text_addr) > INET6_ADDRSTRLEN )
 
350
    return false;
 
351
 
 
352
  /* verify that string will convert to IPv6 address */
 
353
  {
 
354
    struct in6_addr a6;
 
355
    return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
 
356
  }
 
357
}
 
358
 
 
359
static bool
 
360
dns_addr_safe (const char *addr)
 
361
{
 
362
  if (addr)
 
363
    {
 
364
      const size_t len = strlen (addr);
 
365
      return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
 
366
    }
 
367
  else
 
368
    return false;
 
369
}
 
370
 
 
371
bool
 
372
ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
 
373
{
 
374
  if (ip_addr_dotted_quad_safe (addr))
 
375
    return true;
 
376
  else if (allow_fqdn)
 
377
    return dns_addr_safe (addr);
 
378
  else
 
379
    return false;
 
380
}
 
381
 
 
382
bool
 
383
mac_addr_safe (const char *mac_addr)
 
384
{
 
385
  /* verify non-NULL */
 
386
  if (!mac_addr)
 
387
    return false;
 
388
 
 
389
  /* verify length is within limits */
 
390
  if (strlen (mac_addr) > 17)
 
391
    return false;
 
392
 
 
393
  /* verify that all chars are either alphanumeric or ':' and that no
 
394
     alphanumeric substring is greater than 2 chars */
 
395
  {
 
396
    int nnum = 0;
 
397
    const char *p = mac_addr;
 
398
    int c;
 
399
 
 
400
    while ((c = *p++))
 
401
      {
 
402
        if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
 
403
          {
 
404
            ++nnum;
 
405
            if (nnum > 2)
 
406
              return false;
 
407
          }
 
408
        else if (c == ':')
 
409
          {
 
410
            nnum = 0;
 
411
          }
 
412
        else
 
413
          return false;
 
414
      }
 
415
  }
 
416
 
 
417
  /* error-checking is left to script invoked in lladdr.c */
 
418
  return true;
 
419
}
 
420
 
 
421
static void
 
422
update_remote (const char* host,
 
423
               struct openvpn_sockaddr *addr,
 
424
               bool *changed,
 
425
               const unsigned int sockflags)
 
426
{
 
427
  switch(addr->addr.sa.sa_family)
 
428
    {
 
429
    case AF_INET:
 
430
      if (host && addr)
 
431
        {
 
432
          const in_addr_t new_addr = getaddr (
 
433
                                              sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
 
434
                                              host,
 
435
                                              1,
 
436
                                              NULL,
 
437
                                              NULL);
 
438
          if (new_addr && addr->addr.in4.sin_addr.s_addr != new_addr)
 
439
            {
 
440
              addr->addr.in4.sin_addr.s_addr = new_addr;
 
441
              *changed = true;
 
442
            }
 
443
        }
 
444
      break;
 
445
    case AF_INET6:
 
446
      if (host && addr)
 
447
        {
 
448
          int status;
 
449
          struct addrinfo* ai;
 
450
 
 
451
                  status = openvpn_getaddrinfo(sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags), host, 1, NULL, AF_INET6, &ai);
 
452
 
 
453
          if ( status ==0 )
 
454
            {
 
455
                          struct sockaddr_in6 sin6;
 
456
                          CLEAR(sin6);
 
457
                          sin6 = *((struct sockaddr_in6*)ai->ai_addr);
 
458
              if (!IN6_ARE_ADDR_EQUAL(&sin6.sin6_addr, &addr->addr.in6.sin6_addr))
 
459
              {
 
460
                int port = addr->addr.in6.sin6_port;
 
461
                /* ipv6 requires also eg. sin6_scope_id => easier to fully copy and override port */
 
462
                addr->addr.in6 = sin6; 
 
463
                addr->addr.in6.sin6_port = port;
 
464
              }
 
465
                          freeaddrinfo(ai);
 
466
            }
 
467
        }
 
468
      break;
 
469
    default:
 
470
        ASSERT(0);
 
471
  }
 
472
}
 
473
 
 
474
static int
 
475
socket_get_sndbuf (int sd)
 
476
{
 
477
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
 
478
  int val;
 
479
  socklen_t len;
 
480
 
 
481
  len = sizeof (val);
 
482
  if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
 
483
      && len == sizeof (val))
 
484
    return val;
 
485
#endif
 
486
  return 0;
 
487
}
 
488
 
 
489
static void
 
490
socket_set_sndbuf (int sd, int size)
 
491
{
 
492
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
 
493
  if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
 
494
    {
 
495
      if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
 
496
        {
 
497
          msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
 
498
        }
 
499
    }
 
500
#endif
 
501
}
 
502
 
 
503
static int
 
504
socket_get_rcvbuf (int sd)
 
505
{
 
506
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
 
507
  int val;
 
508
  socklen_t len;
 
509
 
 
510
  len = sizeof (val);
 
511
  if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
 
512
      && len == sizeof (val))
 
513
    return val;
 
514
#endif
 
515
  return 0;
 
516
}
 
517
 
 
518
static bool
 
519
socket_set_rcvbuf (int sd, int size)
 
520
{
 
521
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
 
522
  if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
 
523
    {
 
524
      if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
 
525
        {
 
526
          msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
 
527
          return false;
 
528
        }
 
529
    }
 
530
  return true;
 
531
#endif
 
532
}
 
533
 
 
534
static void
 
535
socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
 
536
{
 
537
  if (sbs)
 
538
    {
 
539
      const int sndbuf_old = socket_get_sndbuf (fd);
 
540
      const int rcvbuf_old = socket_get_rcvbuf (fd);
 
541
 
 
542
      if (sbs->sndbuf)
 
543
        socket_set_sndbuf (fd, sbs->sndbuf);
 
544
 
 
545
      if (sbs->rcvbuf)
 
546
        socket_set_rcvbuf (fd, sbs->rcvbuf);
 
547
       
 
548
      msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
 
549
           rcvbuf_old,
 
550
           socket_get_rcvbuf (fd),
 
551
           sndbuf_old,
 
552
           socket_get_sndbuf (fd));
 
553
    }
 
554
}
 
555
 
 
556
/*
 
557
 * Set other socket options
 
558
 */
 
559
 
 
560
static bool
 
561
socket_set_tcp_nodelay (int sd, int state)
 
562
{
 
563
#if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
 
564
  if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
 
565
    {
 
566
      msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
 
567
      return false;
 
568
    }
 
569
  else
 
570
    {
 
571
      dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
 
572
      return true;
 
573
    }
 
574
#else
 
575
  msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
 
576
  return false;
 
577
#endif
 
578
}
 
579
 
 
580
static inline void
 
581
socket_set_mark (int sd, int mark)
 
582
{
 
583
#if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
 
584
  if (mark && setsockopt (sd, SOL_SOCKET, SO_MARK, &mark, sizeof (mark)) != 0)
 
585
    msg (M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
 
586
#endif
 
587
}
 
588
 
 
589
static bool
 
590
socket_set_flags (int sd, unsigned int sockflags)
 
591
{
 
592
  if (sockflags & SF_TCP_NODELAY)
 
593
    return socket_set_tcp_nodelay (sd, 1);
 
594
  else
 
595
    return true;
 
596
}
 
597
 
 
598
bool
 
599
link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
 
600
{
 
601
  if (ls && socket_defined (ls->sd))
 
602
    return socket_set_flags (ls->sd, ls->sockflags = sockflags);
 
603
  else
 
604
    return false;
 
605
}
 
606
 
 
607
void
 
608
link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
 
609
{
 
610
  if (ls && socket_defined (ls->sd))
 
611
    {
 
612
      ls->socket_buffer_sizes.sndbuf = sndbuf;
 
613
      ls->socket_buffer_sizes.rcvbuf = rcvbuf;
 
614
      socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
 
615
    }
 
616
}
 
617
 
 
618
/*
 
619
 * SOCKET INITALIZATION CODE.
 
620
 * Create a TCP/UDP socket
 
621
 */
 
622
 
 
623
socket_descriptor_t
 
624
create_socket_tcp (int af)
 
625
{
 
626
  socket_descriptor_t sd;
 
627
 
 
628
  if ((sd = socket (af, SOCK_STREAM, IPPROTO_TCP)) < 0)
 
629
    msg (M_ERR, "Cannot create TCP socket");
 
630
 
 
631
#ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
 
632
  /* set SO_REUSEADDR on socket */
 
633
  {
 
634
    int on = 1;
 
635
    if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
 
636
                    (void *) &on, sizeof (on)) < 0)
 
637
      msg (M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
 
638
  }
 
639
#endif
 
640
 
 
641
  return sd;
 
642
}
 
643
 
 
644
static socket_descriptor_t
 
645
create_socket_udp (const unsigned int flags)
 
646
{
 
647
  socket_descriptor_t sd;
 
648
 
 
649
  if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
 
650
    msg (M_ERR, "UDP: Cannot create UDP socket");
 
651
#if ENABLE_IP_PKTINFO
 
652
  else if (flags & SF_USE_IP_PKTINFO)
 
653
    {
 
654
      int pad = 1;
 
655
#ifdef IP_PKTINFO
 
656
      if (setsockopt (sd, SOL_IP, IP_PKTINFO,
 
657
                      (void*)&pad, sizeof(pad)) < 0)
 
658
        msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
 
659
#elif defined(IP_RECVDSTADDR)
 
660
      if (setsockopt (sd, IPPROTO_IP, IP_RECVDSTADDR,
 
661
                      (void*)&pad, sizeof(pad)) < 0)
 
662
        msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
 
663
#else
 
664
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 
665
#endif
 
666
    }
 
667
#endif
 
668
  return sd;
 
669
}
 
670
 
 
671
static socket_descriptor_t
 
672
create_socket_udp6 (const unsigned int flags)
 
673
{
 
674
  socket_descriptor_t sd;
 
675
 
 
676
  if ((sd = socket (PF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
 
677
    msg (M_ERR, "UDP: Cannot create UDP6 socket");
 
678
#if ENABLE_IP_PKTINFO
 
679
  else if (flags & SF_USE_IP_PKTINFO)
 
680
    {
 
681
      int pad = 1;
 
682
#ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
 
683
      if (setsockopt (sd, IPPROTO_IPV6, IPV6_PKTINFO,
 
684
                      (void*)&pad, sizeof(pad)) < 0)
 
685
#else
 
686
      if (setsockopt (sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
 
687
                      (void*)&pad, sizeof(pad)) < 0)
 
688
#endif
 
689
        msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
 
690
    }
 
691
#endif
 
692
  return sd;
 
693
}
 
694
 
 
695
static void
 
696
create_socket (struct link_socket *sock)
 
697
{
 
698
  /* create socket */
 
699
  if (sock->info.proto == PROTO_UDPv4)
 
700
    {
 
701
      sock->sd = create_socket_udp (sock->sockflags);
 
702
      sock->sockflags |= SF_GETADDRINFO_DGRAM;
 
703
 
 
704
#ifdef ENABLE_SOCKS
 
705
      if (sock->socks_proxy)
 
706
        sock->ctrl_sd = create_socket_tcp (AF_INET);
 
707
#endif
 
708
    }
 
709
  else if (sock->info.proto == PROTO_TCPv4_SERVER
 
710
           || sock->info.proto == PROTO_TCPv4_CLIENT)
 
711
    {
 
712
      sock->sd = create_socket_tcp (AF_INET);
 
713
    }
 
714
  else if (sock->info.proto == PROTO_TCPv6_SERVER
 
715
           || sock->info.proto == PROTO_TCPv6_CLIENT)
 
716
    {
 
717
      sock->sd = create_socket_tcp (AF_INET6);
 
718
    }
 
719
  else if (sock->info.proto == PROTO_UDPv6)
 
720
    {
 
721
      sock->sd = create_socket_udp6 (sock->sockflags);
 
722
      sock->sockflags |= SF_GETADDRINFO_DGRAM;
 
723
    }
 
724
  else
 
725
    {
 
726
      ASSERT (0);
 
727
    }
 
728
}
 
729
 
 
730
/*
 
731
 * Functions used for establishing a TCP stream connection.
 
732
 */
 
733
 
 
734
static void
 
735
socket_do_listen (socket_descriptor_t sd,
 
736
                  const struct openvpn_sockaddr *local,
 
737
                  bool do_listen,
 
738
                  bool do_set_nonblock)
 
739
{
 
740
  struct gc_arena gc = gc_new ();
 
741
  if (do_listen)
 
742
    {
 
743
      msg (M_INFO, "Listening for incoming TCP connection on %s", 
 
744
           print_sockaddr (local, &gc));
 
745
      if (listen (sd, 1))
 
746
        msg (M_ERR, "TCP: listen() failed");
 
747
    }
 
748
 
 
749
  /* set socket to non-blocking mode */
 
750
  if (do_set_nonblock)
 
751
    set_nonblock (sd);
 
752
 
 
753
  gc_free (&gc);
 
754
}
 
755
 
 
756
socket_descriptor_t
 
757
socket_do_accept (socket_descriptor_t sd,
 
758
                  struct link_socket_actual *act,
 
759
                  const bool nowait)
 
760
{
 
761
  /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
 
762
   * are compiled because act is empty here.
 
763
   * could use getsockname() to support later remote_len check
 
764
   */
 
765
  socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
 
766
  socklen_t remote_len = sizeof(act->dest.addr);
 
767
  socket_descriptor_t new_sd = SOCKET_UNDEFINED;
 
768
 
 
769
  CLEAR (*act);
 
770
 
 
771
#ifdef HAVE_GETPEERNAME
 
772
  if (nowait)
 
773
    {
 
774
      new_sd = getpeername (sd, &act->dest.addr.sa, &remote_len);
 
775
 
 
776
      if (!socket_defined (new_sd))
 
777
        msg (D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
 
778
      else
 
779
        new_sd = sd;
 
780
    }
 
781
#else
 
782
  if (nowait)
 
783
    msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
 
784
#endif
 
785
  else
 
786
    {
 
787
      new_sd = accept (sd, &act->dest.addr.sa, &remote_len);
 
788
    }
 
789
 
 
790
#if 0 /* For debugging only, test the effect of accept() failures */
 
791
 {
 
792
   static int foo = 0;
 
793
   ++foo;
 
794
   if (foo & 1)
 
795
     new_sd = -1;
 
796
 }
 
797
#endif
 
798
 
 
799
  if (!socket_defined (new_sd))
 
800
    {
 
801
      msg (D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", sd);
 
802
    }
 
803
  /* only valid if we have remote_len_af!=0 */
 
804
  else if (remote_len_af && remote_len != remote_len_af)
 
805
    {
 
806
      msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
 
807
      openvpn_close_socket (new_sd);
 
808
      new_sd = SOCKET_UNDEFINED;
 
809
    }
 
810
  return new_sd;
 
811
}
 
812
 
 
813
static void
 
814
tcp_connection_established (const struct link_socket_actual *act)
 
815
{
 
816
  struct gc_arena gc = gc_new ();
 
817
  msg (M_INFO, "TCP connection established with %s", 
 
818
       print_link_socket_actual (act, &gc));
 
819
  gc_free (&gc);
 
820
}
 
821
 
 
822
static int
 
823
socket_listen_accept (socket_descriptor_t sd,
 
824
                      struct link_socket_actual *act,
 
825
                      const char *remote_dynamic,
 
826
                      bool *remote_changed,
 
827
                      const struct openvpn_sockaddr *local,
 
828
                      bool do_listen,
 
829
                      bool nowait,
 
830
                      volatile int *signal_received)
 
831
{
 
832
  struct gc_arena gc = gc_new ();
 
833
  /* struct openvpn_sockaddr *remote = &act->dest; */
 
834
  struct openvpn_sockaddr remote_verify = act->dest;
 
835
  int new_sd = SOCKET_UNDEFINED;
 
836
 
 
837
  CLEAR (*act);
 
838
  socket_do_listen (sd, local, do_listen, true);
 
839
 
 
840
  while (true)
 
841
    {
 
842
      int status;
 
843
      fd_set reads;
 
844
      struct timeval tv;
 
845
 
 
846
      FD_ZERO (&reads);
 
847
      FD_SET (sd, &reads);
 
848
      tv.tv_sec = 0;
 
849
      tv.tv_usec = 0;
 
850
 
 
851
      status = select (sd + 1, &reads, NULL, NULL, &tv);
 
852
 
 
853
      get_signal (signal_received);
 
854
      if (*signal_received)
 
855
        {
 
856
          gc_free (&gc);
 
857
          return sd;
 
858
        }
 
859
 
 
860
      if (status < 0)
 
861
        msg (D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
 
862
 
 
863
      if (status <= 0)
 
864
        {
 
865
          openvpn_sleep (1);
 
866
          continue;
 
867
        }
 
868
 
 
869
      new_sd = socket_do_accept (sd, act, nowait);
 
870
 
 
871
      if (socket_defined (new_sd))
 
872
        {
 
873
          update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
 
874
          if (addr_defined (&remote_verify)
 
875
              && !addr_match (&remote_verify, &act->dest))
 
876
            {
 
877
              msg (M_WARN,
 
878
                   "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
 
879
                   print_link_socket_actual (act, &gc));
 
880
              if (openvpn_close_socket (new_sd))
 
881
                msg (M_ERR, "TCP: close socket failed (new_sd)");
 
882
            }
 
883
          else
 
884
            break;
 
885
        }
 
886
      openvpn_sleep (1);
 
887
    }
 
888
 
 
889
  if (!nowait && openvpn_close_socket (sd))
 
890
    msg (M_ERR, "TCP: close socket failed (sd)");
 
891
 
 
892
  tcp_connection_established (act);
 
893
 
 
894
  gc_free (&gc);
 
895
  return new_sd;
 
896
}
 
897
 
 
898
void
 
899
socket_bind (socket_descriptor_t sd,
 
900
             struct openvpn_sockaddr *local,
 
901
             const char *prefix)
 
902
{
 
903
  struct gc_arena gc = gc_new ();
 
904
 
 
905
  if (bind (sd, &local->addr.sa, af_addr_size(local->addr.sa.sa_family)))
 
906
    {
 
907
      const int errnum = openvpn_errno ();
 
908
      msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
 
909
           prefix,
 
910
           print_sockaddr (local, &gc),
 
911
           strerror_ts (errnum, &gc));
 
912
    }
 
913
  gc_free (&gc);
 
914
}
 
915
 
 
916
int
 
917
openvpn_connect (socket_descriptor_t sd,
 
918
                 struct openvpn_sockaddr *remote,
 
919
                 int connect_timeout,
 
920
                 volatile int *signal_received)
 
921
{
 
922
  int status = 0;
 
923
 
 
924
#ifdef CONNECT_NONBLOCK
 
925
  set_nonblock (sd);
 
926
  status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
 
927
  if (status)
 
928
    status = openvpn_errno ();
 
929
  if (
 
930
#ifdef WIN32
 
931
    status == WSAEWOULDBLOCK
 
932
#else
 
933
    status == EINPROGRESS
 
934
#endif
 
935
  )
 
936
    {
 
937
      while (true)
 
938
        {
 
939
          fd_set writes;
 
940
          struct timeval tv;
 
941
 
 
942
          FD_ZERO (&writes);
 
943
          FD_SET (sd, &writes);
 
944
          tv.tv_sec = 0;
 
945
          tv.tv_usec = 0;
 
946
 
 
947
          status = select (sd + 1, NULL, &writes, NULL, &tv);
 
948
 
 
949
          if (signal_received)
 
950
            {
 
951
              get_signal (signal_received);
 
952
              if (*signal_received)
 
953
                {
 
954
                  status = 0;
 
955
                  break;
 
956
                }
 
957
            }
 
958
          if (status < 0)
 
959
            {
 
960
              status = openvpn_errno ();
 
961
              break;
 
962
            }
 
963
          if (status <= 0)
 
964
            {
 
965
              if (--connect_timeout < 0)
 
966
                {
 
967
                  status = ETIMEDOUT;
 
968
                  break;
 
969
                }
 
970
              openvpn_sleep (1);
 
971
              continue;
 
972
            }
 
973
 
 
974
          /* got it */
 
975
          {
 
976
            int val = 0;
 
977
            socklen_t len;
 
978
 
 
979
            len = sizeof (val);
 
980
            if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
 
981
                && len == sizeof (val))
 
982
              status = val;
 
983
            else
 
984
              status = openvpn_errno ();
 
985
            break;
 
986
          }
 
987
        }
 
988
    }
 
989
#else
 
990
  status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
 
991
  if (status)
 
992
    status = openvpn_errno ();
 
993
#endif
 
994
 
 
995
  return status;
 
996
}
 
997
 
 
998
void
 
999
socket_connect (socket_descriptor_t *sd,
 
1000
                struct openvpn_sockaddr *local,
 
1001
                bool bind_local,
 
1002
                struct openvpn_sockaddr *remote,
 
1003
                const bool connection_profiles_defined,
 
1004
                const char *remote_dynamic,
 
1005
                bool *remote_changed,
 
1006
                const int connect_retry_seconds,
 
1007
                const int connect_timeout,
 
1008
                const int connect_retry_max,
 
1009
                const unsigned int sockflags,
 
1010
                volatile int *signal_received)
 
1011
{
 
1012
  struct gc_arena gc = gc_new ();
 
1013
  int retry = 0;
 
1014
 
 
1015
#ifdef CONNECT_NONBLOCK
 
1016
  msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]", 
 
1017
       print_sockaddr (remote, &gc));
 
1018
#else
 
1019
  msg (M_INFO, "Attempting to establish TCP connection with %s", 
 
1020
       print_sockaddr (remote, &gc));
 
1021
#endif
 
1022
 
 
1023
  while (true)
 
1024
    {
 
1025
      int status;
 
1026
 
 
1027
#ifdef ENABLE_MANAGEMENT
 
1028
      if (management)
 
1029
        management_set_state (management,
 
1030
                              OPENVPN_STATE_TCP_CONNECT,
 
1031
                              NULL,
 
1032
                              (in_addr_t)0,
 
1033
                              (in_addr_t)0);
 
1034
#endif
 
1035
 
 
1036
      status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
 
1037
 
 
1038
      get_signal (signal_received);
 
1039
      if (*signal_received)
 
1040
        goto done;
 
1041
 
 
1042
      if (!status)
 
1043
        break;
 
1044
 
 
1045
      msg (D_LINK_ERRORS,
 
1046
           "TCP: connect to %s failed, will try again in %d seconds: %s",
 
1047
           print_sockaddr (remote, &gc),
 
1048
           connect_retry_seconds,
 
1049
           strerror_ts (status, &gc));
 
1050
 
 
1051
      gc_reset (&gc);
 
1052
 
 
1053
      openvpn_close_socket (*sd);
 
1054
      *sd = SOCKET_UNDEFINED;
 
1055
 
 
1056
      if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
 
1057
        {
 
1058
          *signal_received = SIGUSR1;
 
1059
          goto done;
 
1060
        }
 
1061
 
 
1062
      openvpn_sleep (connect_retry_seconds);
 
1063
 
 
1064
      get_signal (signal_received);
 
1065
      if (*signal_received)
 
1066
        goto done;
 
1067
 
 
1068
        *sd = create_socket_tcp (local->addr.sa.sa_family);
 
1069
 
 
1070
      if (bind_local)
 
1071
        socket_bind (*sd, local, "TCP Client");
 
1072
      update_remote (remote_dynamic, remote, remote_changed, sockflags);
 
1073
    }
 
1074
 
 
1075
  msg (M_INFO, "TCP connection established with %s", 
 
1076
       print_sockaddr (remote, &gc));
 
1077
 
 
1078
 done:
 
1079
  gc_free (&gc);
 
1080
}
 
1081
 
 
1082
/* For stream protocols, allocate a buffer to build up packet.
 
1083
   Called after frame has been finalized. */
 
1084
 
 
1085
static void
 
1086
socket_frame_init (const struct frame *frame, struct link_socket *sock)
 
1087
{
 
1088
#ifdef WIN32
 
1089
  overlapped_io_init (&sock->reads, frame, FALSE, false);
 
1090
  overlapped_io_init (&sock->writes, frame, TRUE, false);
 
1091
  sock->rw_handle.read = sock->reads.overlapped.hEvent;
 
1092
  sock->rw_handle.write = sock->writes.overlapped.hEvent;
 
1093
#endif
 
1094
 
 
1095
  if (link_socket_connection_oriented (sock))
 
1096
    {
 
1097
#ifdef WIN32
 
1098
      stream_buf_init (&sock->stream_buf,
 
1099
                       &sock->reads.buf_init,
 
1100
                       sock->sockflags,
 
1101
                       sock->info.proto);
 
1102
#else
 
1103
      alloc_buf_sock_tun (&sock->stream_buf_data,
 
1104
                          frame,
 
1105
                          false,
 
1106
                          FRAME_HEADROOM_MARKER_READ_STREAM);
 
1107
 
 
1108
      stream_buf_init (&sock->stream_buf,
 
1109
                       &sock->stream_buf_data,
 
1110
                       sock->sockflags,
 
1111
                       sock->info.proto);
 
1112
#endif
 
1113
    }
 
1114
}
 
1115
 
 
1116
/*
 
1117
 * Adjust frame structure based on a Path MTU value given
 
1118
 * to us by the OS.
 
1119
 */
 
1120
void
 
1121
frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
 
1122
{
 
1123
  frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
 
1124
}
 
1125
 
 
1126
static void
 
1127
resolve_bind_local (struct link_socket *sock)
 
1128
{
 
1129
  struct gc_arena gc = gc_new ();
 
1130
 
 
1131
  /* resolve local address if undefined */
 
1132
  if (!addr_defined (&sock->info.lsa->local))
 
1133
    {
 
1134
      /* may return AF_{INET|INET6} guessed from local_host */
 
1135
      switch(addr_guess_family(sock->info.proto, sock->local_host))
 
1136
        {
 
1137
        case AF_INET:
 
1138
          sock->info.lsa->local.addr.in4.sin_family = AF_INET;
 
1139
          sock->info.lsa->local.addr.in4.sin_addr.s_addr =
 
1140
            (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
 
1141
                                         sock->local_host,
 
1142
                                         0,
 
1143
                                         NULL,
 
1144
                                         NULL)
 
1145
             : htonl (INADDR_ANY));
 
1146
          sock->info.lsa->local.addr.in4.sin_port = htons (sock->local_port);
 
1147
          break;
 
1148
        case AF_INET6:
 
1149
            {
 
1150
              int status;
 
1151
              int err;
 
1152
              CLEAR(sock->info.lsa->local.addr.in6);
 
1153
              if (sock->local_host)
 
1154
                {
 
1155
                  struct addrinfo *ai;
 
1156
 
 
1157
                  status = openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
 
1158
                                                                           sock->local_host, 0, NULL, AF_INET6, &ai);
 
1159
                  if(status ==0) {
 
1160
                          sock->info.lsa->local.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
 
1161
                          freeaddrinfo(ai);
 
1162
                  }
 
1163
                }
 
1164
              else
 
1165
                {
 
1166
                  sock->info.lsa->local.addr.in6.sin6_family = AF_INET6;
 
1167
                  sock->info.lsa->local.addr.in6.sin6_addr = in6addr_any;
 
1168
                  status = 0;
 
1169
                }
 
1170
              if (!status == 0)
 
1171
                {
 
1172
                  msg (M_FATAL, "getaddr6() failed for local \"%s\": %s",
 
1173
                       sock->local_host,
 
1174
                       gai_strerror(err));
 
1175
                }
 
1176
              sock->info.lsa->local.addr.in6.sin6_port = htons (sock->local_port);
 
1177
            }
 
1178
          break;
 
1179
        }
 
1180
    }
 
1181
  
 
1182
  /* bind to local address/port */
 
1183
  if (sock->bind_local)
 
1184
    {
 
1185
#ifdef ENABLE_SOCKS
 
1186
      if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
 
1187
          socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
 
1188
      else
 
1189
#endif
 
1190
          socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
 
1191
    }
 
1192
  gc_free (&gc);
 
1193
}
 
1194
 
 
1195
static void
 
1196
resolve_remote (struct link_socket *sock,
 
1197
                int phase,
 
1198
                const char **remote_dynamic,
 
1199
                volatile int *signal_received)
 
1200
{
 
1201
  struct gc_arena gc = gc_new ();
 
1202
  int af;
 
1203
 
 
1204
  if (!sock->did_resolve_remote)
 
1205
    {
 
1206
      /* resolve remote address if undefined */
 
1207
      if (!addr_defined (&sock->info.lsa->remote))
 
1208
        {
 
1209
          af = addr_guess_family(sock->info.proto, sock->remote_host);
 
1210
          switch(af)
 
1211
            {
 
1212
              case AF_INET:
 
1213
                sock->info.lsa->remote.addr.in4.sin_family = AF_INET;
 
1214
                sock->info.lsa->remote.addr.in4.sin_addr.s_addr = 0;
 
1215
                break;
 
1216
              case AF_INET6:
 
1217
                CLEAR(sock->info.lsa->remote.addr.in6);
 
1218
                sock->info.lsa->remote.addr.in6.sin6_family = AF_INET6;
 
1219
                sock->info.lsa->remote.addr.in6.sin6_addr = in6addr_any;
 
1220
                break;
 
1221
            }
 
1222
 
 
1223
          if (sock->remote_host)
 
1224
            {
 
1225
              unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
 
1226
              int retry = 0;
 
1227
              int status = -1;
 
1228
 
 
1229
              if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
 
1230
                {
 
1231
                  if (phase == 2)
 
1232
                    flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
 
1233
                  retry = 0;
 
1234
                }
 
1235
              else if (phase == 1)
 
1236
                {
 
1237
                  if (sock->resolve_retry_seconds)
 
1238
                    {
 
1239
                      retry = 0;
 
1240
                    }
 
1241
                  else
 
1242
                    {
 
1243
                      flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
 
1244
                      retry = 0;
 
1245
                    }
 
1246
                }
 
1247
              else if (phase == 2)
 
1248
                {
 
1249
                  if (sock->resolve_retry_seconds)
 
1250
                    {
 
1251
                      flags |= GETADDR_FATAL;
 
1252
                      retry = sock->resolve_retry_seconds;
 
1253
                    }
 
1254
                  else
 
1255
                    {
 
1256
                      ASSERT (0);
 
1257
                    }
 
1258
                }
 
1259
              else
 
1260
                {
 
1261
                  ASSERT (0);
 
1262
                }
 
1263
 
 
1264
                  struct addrinfo* ai;
 
1265
                  /* Temporary fix, this need to be changed for dual stack */
 
1266
                  status = openvpn_getaddrinfo(flags, sock->remote_host, retry,
 
1267
                                                                                          signal_received, af, &ai);
 
1268
                  if(status == 0) {
 
1269
                          sock->info.lsa->remote.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
 
1270
                          freeaddrinfo(ai);
 
1271
 
 
1272
                          dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
 
1273
                                        flags,
 
1274
                                        phase,
 
1275
                                        retry,
 
1276
                                        signal_received ? *signal_received : -1,
 
1277
                                        status);
 
1278
                  }
 
1279
              if (signal_received)
 
1280
                {
 
1281
                  if (*signal_received)
 
1282
                    goto done;
 
1283
                }
 
1284
              if (status!=0)
 
1285
                {
 
1286
                  if (signal_received)
 
1287
                    *signal_received = SIGUSR1;
 
1288
                  goto done;
 
1289
                }
 
1290
            }
 
1291
          switch(af)
 
1292
            {
 
1293
              case AF_INET:
 
1294
                sock->info.lsa->remote.addr.in4.sin_port = htons (sock->remote_port);
 
1295
                break;
 
1296
              case AF_INET6:
 
1297
                sock->info.lsa->remote.addr.in6.sin6_port = htons (sock->remote_port);
 
1298
                break;
 
1299
            }
 
1300
        }
 
1301
  
 
1302
      /* should we re-use previous active remote address? */
 
1303
      if (link_socket_actual_defined (&sock->info.lsa->actual))
 
1304
        {
 
1305
          msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
 
1306
               print_link_socket_actual (&sock->info.lsa->actual, &gc));
 
1307
          if (remote_dynamic)
 
1308
            *remote_dynamic = NULL;
 
1309
        }
 
1310
      else
 
1311
        {
 
1312
          CLEAR (sock->info.lsa->actual);
 
1313
          sock->info.lsa->actual.dest = sock->info.lsa->remote;
 
1314
        }
 
1315
 
 
1316
      /* remember that we finished */
 
1317
      sock->did_resolve_remote = true;
 
1318
    }
 
1319
 
 
1320
 done:
 
1321
  gc_free (&gc);
 
1322
}
 
1323
 
 
1324
struct link_socket *
 
1325
link_socket_new (void)
 
1326
{
 
1327
  struct link_socket *sock;
 
1328
 
 
1329
  ALLOC_OBJ_CLEAR (sock, struct link_socket);
 
1330
  sock->sd = SOCKET_UNDEFINED;
 
1331
#ifdef ENABLE_SOCKS
 
1332
  sock->ctrl_sd = SOCKET_UNDEFINED;
 
1333
#endif
 
1334
  return sock;
 
1335
}
 
1336
 
 
1337
/* bind socket if necessary */
 
1338
void
 
1339
link_socket_init_phase1 (struct link_socket *sock,
 
1340
                         const bool connection_profiles_defined,
 
1341
                         const char *local_host,
 
1342
                         int local_port,
 
1343
                         const char *remote_host,
 
1344
                         int remote_port,
 
1345
                         int proto,
 
1346
                         int mode,
 
1347
                         const struct link_socket *accept_from,
 
1348
#ifdef ENABLE_HTTP_PROXY
 
1349
                         struct http_proxy_info *http_proxy,
 
1350
#endif
 
1351
#ifdef ENABLE_SOCKS
 
1352
                         struct socks_proxy_info *socks_proxy,
 
1353
#endif
 
1354
#ifdef ENABLE_DEBUG
 
1355
                         int gremlin,
 
1356
#endif
 
1357
                         bool bind_local,
 
1358
                         bool remote_float,
 
1359
                         int inetd,
 
1360
                         struct link_socket_addr *lsa,
 
1361
                         const char *ipchange_command,
 
1362
                         const struct plugin_list *plugins,
 
1363
                         int resolve_retry_seconds,
 
1364
                         int connect_retry_seconds,
 
1365
                         int connect_timeout,
 
1366
                         int connect_retry_max,
 
1367
                         int mtu_discover_type,
 
1368
                         int rcvbuf,
 
1369
                         int sndbuf,
 
1370
                         int mark,
 
1371
                         unsigned int sockflags)
 
1372
{
 
1373
  ASSERT (sock);
 
1374
 
 
1375
  sock->connection_profiles_defined = connection_profiles_defined;
 
1376
 
 
1377
  sock->local_host = local_host;
 
1378
  sock->local_port = local_port;
 
1379
  sock->remote_host = remote_host;
 
1380
  sock->remote_port = remote_port;
 
1381
 
 
1382
#ifdef ENABLE_HTTP_PROXY
 
1383
  sock->http_proxy = http_proxy;
 
1384
#endif
 
1385
 
 
1386
#ifdef ENABLE_SOCKS
 
1387
  sock->socks_proxy = socks_proxy;
 
1388
#endif
 
1389
 
 
1390
  sock->bind_local = bind_local;
 
1391
  sock->inetd = inetd;
 
1392
  sock->resolve_retry_seconds = resolve_retry_seconds;
 
1393
  sock->connect_retry_seconds = connect_retry_seconds;
 
1394
  sock->connect_timeout = connect_timeout;
 
1395
  sock->connect_retry_max = connect_retry_max;
 
1396
  sock->mtu_discover_type = mtu_discover_type;
 
1397
 
 
1398
#ifdef ENABLE_DEBUG
 
1399
  sock->gremlin = gremlin;
 
1400
#endif
 
1401
 
 
1402
  sock->socket_buffer_sizes.rcvbuf = rcvbuf;
 
1403
  sock->socket_buffer_sizes.sndbuf = sndbuf;
 
1404
 
 
1405
  sock->sockflags = sockflags;
 
1406
 
 
1407
  sock->info.proto = proto;
 
1408
  sock->info.remote_float = remote_float;
 
1409
  sock->info.lsa = lsa;
 
1410
  sock->info.ipchange_command = ipchange_command;
 
1411
  sock->info.plugins = plugins;
 
1412
 
 
1413
  sock->mode = mode;
 
1414
  if (mode == LS_MODE_TCP_ACCEPT_FROM)
 
1415
    {
 
1416
      ASSERT (accept_from);
 
1417
      ASSERT (sock->info.proto == PROTO_TCPv4_SERVER
 
1418
              || sock->info.proto == PROTO_TCPv6_SERVER
 
1419
             );
 
1420
      ASSERT (!sock->inetd);
 
1421
      sock->sd = accept_from->sd;
 
1422
    }
 
1423
 
 
1424
  if (false)
 
1425
    ;
 
1426
#ifdef ENABLE_HTTP_PROXY
 
1427
  /* are we running in HTTP proxy mode? */
 
1428
  else if (sock->http_proxy)
 
1429
    {
 
1430
      ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
 
1431
      ASSERT (!sock->inetd);
 
1432
 
 
1433
      /* the proxy server */
 
1434
      sock->remote_host = http_proxy->options.server;
 
1435
      sock->remote_port = http_proxy->options.port;
 
1436
 
 
1437
      /* the OpenVPN server we will use the proxy to connect to */
 
1438
      sock->proxy_dest_host = remote_host;
 
1439
      sock->proxy_dest_port = remote_port;
 
1440
    }
 
1441
#endif
 
1442
#ifdef ENABLE_SOCKS
 
1443
  /* or in Socks proxy mode? */
 
1444
  else if (sock->socks_proxy)
 
1445
    {
 
1446
      ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
 
1447
      ASSERT (!sock->inetd);
 
1448
 
 
1449
      /* the proxy server */
 
1450
      sock->remote_host = socks_proxy->server;
 
1451
      sock->remote_port = socks_proxy->port;
 
1452
 
 
1453
      /* the OpenVPN server we will use the proxy to connect to */
 
1454
      sock->proxy_dest_host = remote_host;
 
1455
      sock->proxy_dest_port = remote_port;
 
1456
    }
 
1457
#endif
 
1458
  else
 
1459
    {
 
1460
      sock->remote_host = remote_host;
 
1461
      sock->remote_port = remote_port;
 
1462
    }
 
1463
 
 
1464
  /* bind behavior for TCP server vs. client */
 
1465
  if (sock->info.proto == PROTO_TCPv4_SERVER)
 
1466
    {
 
1467
      if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
 
1468
        sock->bind_local = false;
 
1469
      else
 
1470
        sock->bind_local = true;
 
1471
    }
 
1472
 
 
1473
  /* were we started by inetd or xinetd? */
 
1474
  if (sock->inetd)
 
1475
    {
 
1476
      ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT
 
1477
              && sock->info.proto != PROTO_TCPv6_CLIENT);
 
1478
      ASSERT (socket_defined (inetd_socket_descriptor));
 
1479
      sock->sd = inetd_socket_descriptor;
 
1480
    }
 
1481
  else if (mode != LS_MODE_TCP_ACCEPT_FROM)
 
1482
    {
 
1483
      create_socket (sock);
 
1484
 
 
1485
      /* set socket buffers based on --sndbuf and --rcvbuf options */
 
1486
      socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
 
1487
 
 
1488
      /* set socket to --mark packets with given value */
 
1489
      socket_set_mark (sock->sd, mark);
 
1490
 
 
1491
      resolve_bind_local (sock);
 
1492
      resolve_remote (sock, 1, NULL, NULL);
 
1493
    }
 
1494
}
 
1495
 
 
1496
/* finalize socket initialization */
 
1497
void
 
1498
link_socket_init_phase2 (struct link_socket *sock,
 
1499
                         const struct frame *frame,
 
1500
                         volatile int *signal_received)
 
1501
{
 
1502
  struct gc_arena gc = gc_new ();
 
1503
  const char *remote_dynamic = NULL;
 
1504
  bool remote_changed = false;
 
1505
  int sig_save = 0;
 
1506
 
 
1507
  ASSERT (sock);
 
1508
 
 
1509
  if (signal_received && *signal_received)
 
1510
    {
 
1511
      sig_save = *signal_received;
 
1512
      *signal_received = 0;
 
1513
    }
 
1514
 
 
1515
  /* initialize buffers */
 
1516
  socket_frame_init (frame, sock);
 
1517
 
 
1518
  /*
 
1519
   * Pass a remote name to connect/accept so that
 
1520
   * they can test for dynamic IP address changes
 
1521
   * and throw a SIGUSR1 if appropriate.
 
1522
   */
 
1523
  if (sock->resolve_retry_seconds)
 
1524
    remote_dynamic = sock->remote_host;
 
1525
 
 
1526
  /* were we started by inetd or xinetd? */
 
1527
  if (sock->inetd)
 
1528
    {
 
1529
      if (sock->info.proto == PROTO_TCPv4_SERVER
 
1530
          || sock->info.proto == PROTO_TCPv6_SERVER) {
 
1531
        /* AF_INET as default (and fallback) for inetd */
 
1532
        sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
 
1533
#ifdef HAVE_GETSOCKNAME
 
1534
          {
 
1535
            /* inetd: hint family type for dest = local's */
 
1536
            struct openvpn_sockaddr local_addr;
 
1537
            socklen_t addrlen = sizeof(local_addr);
 
1538
            if (getsockname (sock->sd, (struct sockaddr *)&local_addr, &addrlen) == 0) {
 
1539
              sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
 
1540
              dmsg (D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
 
1541
                    proto2ascii(sock->info.proto, false), local_addr.addr.sa.sa_family,
 
1542
                    sock->sd);
 
1543
            } else
 
1544
              msg (M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
 
1545
                   proto2ascii(sock->info.proto, false), sock->sd);
 
1546
          }
 
1547
#else
 
1548
        msg (M_WARN, "inetd(%s): this OS does not provide the getsockname() "
 
1549
             "function, using AF_INET",
 
1550
             proto2ascii(sock->info.proto, false));
 
1551
#endif
 
1552
        sock->sd =
 
1553
          socket_listen_accept (sock->sd,
 
1554
                                &sock->info.lsa->actual,
 
1555
                                remote_dynamic,
 
1556
                                &remote_changed,
 
1557
                                &sock->info.lsa->local,
 
1558
                                false,
 
1559
                                sock->inetd == INETD_NOWAIT,
 
1560
                                signal_received);
 
1561
      }
 
1562
      ASSERT (!remote_changed);
 
1563
      if (*signal_received)
 
1564
        goto done;
 
1565
    }
 
1566
  else
 
1567
    {
 
1568
      resolve_remote (sock, 2, &remote_dynamic, signal_received);
 
1569
 
 
1570
      if (*signal_received)
 
1571
        goto done;
 
1572
 
 
1573
      /* TCP client/server */
 
1574
      if (sock->info.proto == PROTO_TCPv4_SERVER
 
1575
          ||sock->info.proto == PROTO_TCPv6_SERVER)
 
1576
        {
 
1577
          switch (sock->mode)
 
1578
            {
 
1579
            case LS_MODE_DEFAULT:
 
1580
              sock->sd = socket_listen_accept (sock->sd,
 
1581
                                               &sock->info.lsa->actual,
 
1582
                                               remote_dynamic,
 
1583
                                               &remote_changed,
 
1584
                                               &sock->info.lsa->local,
 
1585
                                               true,
 
1586
                                               false,
 
1587
                                               signal_received);
 
1588
              break;
 
1589
            case LS_MODE_TCP_LISTEN:
 
1590
              socket_do_listen (sock->sd,
 
1591
                                &sock->info.lsa->local,
 
1592
                                true,
 
1593
                                false);
 
1594
              break;
 
1595
            case LS_MODE_TCP_ACCEPT_FROM:
 
1596
              sock->sd = socket_do_accept (sock->sd,
 
1597
                                           &sock->info.lsa->actual,
 
1598
                                           false);
 
1599
              if (!socket_defined (sock->sd))
 
1600
                {
 
1601
                  *signal_received = SIGTERM;
 
1602
                  goto done;
 
1603
                }
 
1604
              tcp_connection_established (&sock->info.lsa->actual);
 
1605
              break;
 
1606
            default:
 
1607
              ASSERT (0);
 
1608
            }
 
1609
        }
 
1610
      else if (sock->info.proto == PROTO_TCPv4_CLIENT
 
1611
               ||sock->info.proto == PROTO_TCPv6_CLIENT)
 
1612
        {
 
1613
 
 
1614
#ifdef GENERAL_PROXY_SUPPORT
 
1615
          bool proxy_retry = false;
 
1616
#else
 
1617
          const bool proxy_retry = false;
 
1618
#endif
 
1619
          do {
 
1620
            socket_connect (&sock->sd,
 
1621
                            &sock->info.lsa->local,
 
1622
                            sock->bind_local,
 
1623
                            &sock->info.lsa->actual.dest,
 
1624
                            sock->connection_profiles_defined,
 
1625
                            remote_dynamic,
 
1626
                            &remote_changed,
 
1627
                            sock->connect_retry_seconds,
 
1628
                            sock->connect_timeout,
 
1629
                            sock->connect_retry_max,
 
1630
                            sock->sockflags,
 
1631
                            signal_received);
 
1632
 
 
1633
            if (*signal_received)
 
1634
              goto done;
 
1635
 
 
1636
            if (false)
 
1637
              ;
 
1638
#ifdef ENABLE_HTTP_PROXY
 
1639
            else if (sock->http_proxy)
 
1640
              {
 
1641
                proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
 
1642
                                                             sock->sd,
 
1643
                                                             sock->proxy_dest_host,
 
1644
                                                             sock->proxy_dest_port,
 
1645
                                                             &sock->stream_buf.residual,
 
1646
                                                             signal_received);
 
1647
              }
 
1648
#endif
 
1649
#ifdef ENABLE_SOCKS
 
1650
            else if (sock->socks_proxy)
 
1651
              {
 
1652
                establish_socks_proxy_passthru (sock->socks_proxy,
 
1653
                                                sock->sd,
 
1654
                                                sock->proxy_dest_host,
 
1655
                                                sock->proxy_dest_port,
 
1656
                                                signal_received);
 
1657
              }
 
1658
#endif
 
1659
            if (proxy_retry)
 
1660
              {
 
1661
                openvpn_close_socket (sock->sd);
 
1662
                sock->sd = create_socket_tcp (AF_INET);
 
1663
              }
 
1664
          } while (proxy_retry);
 
1665
        }
 
1666
#ifdef ENABLE_SOCKS
 
1667
      else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
 
1668
        {
 
1669
          socket_connect (&sock->ctrl_sd,
 
1670
                          &sock->info.lsa->local,
 
1671
                          sock->bind_local,
 
1672
                          &sock->info.lsa->actual.dest,
 
1673
                          sock->connection_profiles_defined,
 
1674
                          remote_dynamic,
 
1675
                          &remote_changed,
 
1676
                          sock->connect_retry_seconds,
 
1677
                          sock->connect_timeout,
 
1678
                          sock->connect_retry_max,
 
1679
                          sock->sockflags,
 
1680
                          signal_received);
 
1681
 
 
1682
          if (*signal_received)
 
1683
            goto done;
 
1684
 
 
1685
          establish_socks_proxy_udpassoc (sock->socks_proxy,
 
1686
                                          sock->ctrl_sd,
 
1687
                                          sock->sd,
 
1688
                                          &sock->socks_relay.dest,
 
1689
                                          signal_received);
 
1690
 
 
1691
          if (*signal_received)
 
1692
            goto done;
 
1693
 
 
1694
          sock->remote_host = sock->proxy_dest_host;
 
1695
          sock->remote_port = sock->proxy_dest_port;
 
1696
          sock->did_resolve_remote = false;
 
1697
 
 
1698
          addr_zero_host(&sock->info.lsa->actual.dest);
 
1699
          addr_zero_host(&sock->info.lsa->remote);
 
1700
 
 
1701
          resolve_remote (sock, 1, NULL, signal_received);
 
1702
 
 
1703
          if (*signal_received)
 
1704
            goto done;
 
1705
        }
 
1706
#endif
 
1707
 
 
1708
      if (*signal_received)
 
1709
        goto done;
 
1710
 
 
1711
      if (remote_changed)
 
1712
        {
 
1713
          msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
 
1714
          addr_copy_host(&sock->info.lsa->remote, &sock->info.lsa->actual.dest);
 
1715
        }
 
1716
    }
 
1717
 
 
1718
  /* set misc socket parameters */
 
1719
  socket_set_flags (sock->sd, sock->sockflags);
 
1720
 
 
1721
  /* set socket to non-blocking mode */
 
1722
  set_nonblock (sock->sd);
 
1723
 
 
1724
  /* set socket file descriptor to not pass across execs, so that
 
1725
     scripts don't have access to it */
 
1726
  set_cloexec (sock->sd);
 
1727
 
 
1728
#ifdef ENABLE_SOCKS
 
1729
  if (socket_defined (sock->ctrl_sd))
 
1730
    set_cloexec (sock->ctrl_sd);
 
1731
#endif
 
1732
 
 
1733
  /* set Path MTU discovery options on the socket */
 
1734
  set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
 
1735
 
 
1736
#if EXTENDED_SOCKET_ERROR_CAPABILITY
 
1737
  /* if the OS supports it, enable extended error passing on the socket */
 
1738
  set_sock_extended_error_passing (sock->sd);
 
1739
#endif
 
1740
 
 
1741
  /* print local address */
 
1742
  {
 
1743
    const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
 
1744
 
 
1745
    if (sock->inetd)
 
1746
      msg (msglevel, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
 
1747
    else
 
1748
      msg (msglevel, "%s link local%s: %s",
 
1749
           proto2ascii (sock->info.proto, true),
 
1750
           (sock->bind_local ? " (bound)" : ""),
 
1751
           print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
 
1752
 
 
1753
    /* print active remote address */
 
1754
    msg (msglevel, "%s link remote: %s",
 
1755
         proto2ascii (sock->info.proto, true),
 
1756
         print_link_socket_actual_ex (&sock->info.lsa->actual,
 
1757
                                      ":",
 
1758
                                      PS_SHOW_PORT_IF_DEFINED,
 
1759
                                      &gc));
 
1760
  }
 
1761
 
 
1762
 done:
 
1763
  if (sig_save && signal_received)
 
1764
    {
 
1765
      if (!*signal_received)
 
1766
        *signal_received = sig_save;
 
1767
    }
 
1768
  gc_free (&gc);
 
1769
}
 
1770
 
 
1771
void
 
1772
link_socket_close (struct link_socket *sock)
 
1773
{
 
1774
  if (sock)
 
1775
    {
 
1776
#ifdef ENABLE_DEBUG
 
1777
      const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
 
1778
#else
 
1779
      const int gremlin = 0;
 
1780
#endif
 
1781
 
 
1782
      if (socket_defined (sock->sd))
 
1783
        {
 
1784
#ifdef WIN32
 
1785
          close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
 
1786
#endif
 
1787
          if (!gremlin)
 
1788
            {
 
1789
              msg (D_LOW, "TCP/UDP: Closing socket");
 
1790
              if (openvpn_close_socket (sock->sd))
 
1791
                msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
 
1792
            }
 
1793
          sock->sd = SOCKET_UNDEFINED;
 
1794
#ifdef WIN32
 
1795
          if (!gremlin)
 
1796
            {
 
1797
              overlapped_io_close (&sock->reads);
 
1798
              overlapped_io_close (&sock->writes);
 
1799
            }
 
1800
#endif
 
1801
        }
 
1802
 
 
1803
#ifdef ENABLE_SOCKS
 
1804
      if (socket_defined (sock->ctrl_sd))
 
1805
        {
 
1806
          if (openvpn_close_socket (sock->ctrl_sd))
 
1807
            msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
 
1808
          sock->ctrl_sd = SOCKET_UNDEFINED;
 
1809
        }
 
1810
#endif
 
1811
 
 
1812
      stream_buf_close (&sock->stream_buf);
 
1813
      free_buf (&sock->stream_buf_data);
 
1814
      if (!gremlin)
 
1815
        free (sock);
 
1816
    }
 
1817
}
 
1818
 
 
1819
/* for stream protocols, allow for packet length prefix */
 
1820
void
 
1821
socket_adjust_frame_parameters (struct frame *frame, int proto)
 
1822
{
 
1823
  if (link_socket_proto_connection_oriented (proto))
 
1824
    frame_add_to_extra_frame (frame, sizeof (packet_size_type));
 
1825
}
 
1826
 
 
1827
void
 
1828
setenv_trusted (struct env_set *es, const struct link_socket_info *info)
 
1829
{
 
1830
  setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
 
1831
}
 
1832
 
 
1833
static void
 
1834
ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
 
1835
{
 
1836
  const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
 
1837
  const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
 
1838
  if (include_cmd)
 
1839
    argv_printf (argv, "%sc %s %s",
 
1840
                 info->ipchange_command,
 
1841
                 ip,
 
1842
                 port);
 
1843
  else
 
1844
    argv_printf (argv, "%s %s",
 
1845
                 ip,
 
1846
                 port);
 
1847
}
 
1848
 
 
1849
void
 
1850
link_socket_connection_initiated (const struct buffer *buf,
 
1851
                                  struct link_socket_info *info,
 
1852
                                  const struct link_socket_actual *act,
 
1853
                                  const char *common_name,
 
1854
                                  struct env_set *es)
 
1855
{
 
1856
  struct gc_arena gc = gc_new ();
 
1857
  
 
1858
  info->lsa->actual = *act; /* Note: skip this line for --force-dest */
 
1859
  setenv_trusted (es, info);
 
1860
  info->connection_established = true;
 
1861
 
 
1862
  /* Print connection initiated message, with common name if available */
 
1863
  {
 
1864
    struct buffer out = alloc_buf_gc (256, &gc);
 
1865
    if (common_name)
 
1866
      buf_printf (&out, "[%s] ", common_name);
 
1867
    buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
 
1868
    msg (M_INFO, "%s", BSTR (&out));
 
1869
  }
 
1870
 
 
1871
  /* set environmental vars */
 
1872
  setenv_str (es, "common_name", common_name);
 
1873
 
 
1874
  /* Process --ipchange plugin */
 
1875
  if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
 
1876
    {
 
1877
      struct argv argv = argv_new ();
 
1878
      ipchange_fmt (false, &argv, info, &gc);
 
1879
      if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
 
1880
        msg (M_WARN, "WARNING: ipchange plugin call failed");
 
1881
      argv_reset (&argv);
 
1882
    }
 
1883
 
 
1884
  /* Process --ipchange option */
 
1885
  if (info->ipchange_command)
 
1886
    {
 
1887
      struct argv argv = argv_new ();
 
1888
      setenv_str (es, "script_type", "ipchange");
 
1889
      ipchange_fmt (true, &argv, info, &gc);
 
1890
      openvpn_run_script (&argv, es, 0, "--ipchange");
 
1891
      argv_reset (&argv);
 
1892
    }
 
1893
 
 
1894
  gc_free (&gc);
 
1895
}
 
1896
 
 
1897
void
 
1898
link_socket_bad_incoming_addr (struct buffer *buf,
 
1899
                               const struct link_socket_info *info,
 
1900
                               const struct link_socket_actual *from_addr)
 
1901
{
 
1902
  struct gc_arena gc = gc_new ();
 
1903
 
 
1904
  switch(from_addr->dest.addr.sa.sa_family)
 
1905
    {
 
1906
    case AF_INET:
 
1907
    case AF_INET6:
 
1908
      msg (D_LINK_ERRORS,
 
1909
           "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
 
1910
           print_link_socket_actual (from_addr, &gc),
 
1911
           (int)from_addr->dest.addr.sa.sa_family,
 
1912
           print_sockaddr (&info->lsa->remote, &gc));
 
1913
      break;
 
1914
    }
 
1915
  buf->len = 0;
 
1916
  gc_free (&gc);
 
1917
}
 
1918
 
 
1919
void
 
1920
link_socket_bad_outgoing_addr (void)
 
1921
{
 
1922
  dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
 
1923
}
 
1924
 
 
1925
in_addr_t
 
1926
link_socket_current_remote (const struct link_socket_info *info)
 
1927
{
 
1928
  const struct link_socket_addr *lsa = info->lsa;
 
1929
 
 
1930
/* 
 
1931
 * This logic supports "redirect-gateway" semantic, which 
 
1932
 * makes sense only for PF_INET routes over PF_INET endpoints
 
1933
 *
 
1934
 * Maybe in the future consider PF_INET6 endpoints also ...
 
1935
 * by now just ignore it
 
1936
 *
 
1937
 */
 
1938
  if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
 
1939
    return IPV4_INVALID_ADDR;
 
1940
 
 
1941
  if (link_socket_actual_defined (&lsa->actual))
 
1942
    return ntohl (lsa->actual.dest.addr.in4.sin_addr.s_addr);
 
1943
  else if (addr_defined (&lsa->remote))
 
1944
    return ntohl (lsa->remote.addr.in4.sin_addr.s_addr);
 
1945
  else
 
1946
    return 0;
 
1947
}
 
1948
 
 
1949
/*
 
1950
 * Return a status string describing socket state.
 
1951
 */
 
1952
const char *
 
1953
socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
 
1954
{
 
1955
  struct buffer out = alloc_buf_gc (64, gc);
 
1956
  if (s)
 
1957
    {
 
1958
      if (rwflags & EVENT_READ)
 
1959
        {
 
1960
          buf_printf (&out, "S%s",
 
1961
                      (s->rwflags_debug & EVENT_READ) ? "R" : "r");
 
1962
#ifdef WIN32
 
1963
          buf_printf (&out, "%s",
 
1964
                      overlapped_io_state_ascii (&s->reads));
 
1965
#endif
 
1966
        }
 
1967
      if (rwflags & EVENT_WRITE)
 
1968
        {
 
1969
          buf_printf (&out, "S%s",
 
1970
                      (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
 
1971
#ifdef WIN32
 
1972
          buf_printf (&out, "%s",
 
1973
                      overlapped_io_state_ascii (&s->writes));
 
1974
#endif
 
1975
        }
 
1976
    }
 
1977
  else
 
1978
    {
 
1979
      buf_printf (&out, "S?");
 
1980
    }
 
1981
  return BSTR (&out);
 
1982
}
 
1983
 
 
1984
/*
 
1985
 * Stream buffer functions, used to packetize a TCP
 
1986
 * stream connection.
 
1987
 */
 
1988
 
 
1989
static inline void
 
1990
stream_buf_reset (struct stream_buf *sb)
 
1991
{
 
1992
  dmsg (D_STREAM_DEBUG, "STREAM: RESET");
 
1993
  sb->residual_fully_formed = false;
 
1994
  sb->buf = sb->buf_init;
 
1995
  buf_reset (&sb->next);
 
1996
  sb->len = -1;
 
1997
}
 
1998
 
 
1999
void
 
2000
stream_buf_init (struct stream_buf *sb,
 
2001
                 struct buffer *buf,
 
2002
                 const unsigned int sockflags,
 
2003
                 const int proto)
 
2004
{
 
2005
  sb->buf_init = *buf;
 
2006
  sb->maxlen = sb->buf_init.len;
 
2007
  sb->buf_init.len = 0;
 
2008
  sb->residual = alloc_buf (sb->maxlen);
 
2009
  sb->error = false;
 
2010
#if PORT_SHARE
 
2011
  sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
 
2012
    ? PS_ENABLED
 
2013
    : PS_DISABLED;
 
2014
#endif
 
2015
  stream_buf_reset (sb);
 
2016
 
 
2017
  dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
 
2018
}
 
2019
 
 
2020
static inline void
 
2021
stream_buf_set_next (struct stream_buf *sb)
 
2022
{
 
2023
  /* set up 'next' for next i/o read */
 
2024
  sb->next = sb->buf;
 
2025
  sb->next.offset = sb->buf.offset + sb->buf.len;
 
2026
  sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
 
2027
  dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
 
2028
       sb->buf.offset, sb->buf.len,
 
2029
       sb->next.offset, sb->next.len,
 
2030
       sb->len, sb->maxlen);
 
2031
  ASSERT (sb->next.len > 0);
 
2032
  ASSERT (buf_safe (&sb->buf, sb->next.len));
 
2033
}
 
2034
 
 
2035
static inline void
 
2036
stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
 
2037
{
 
2038
  dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
 
2039
       buf_defined (&sb->buf) ? sb->buf.len : -1);
 
2040
  ASSERT (buf_defined (&sb->buf));
 
2041
  *buf = sb->buf;
 
2042
}
 
2043
 
 
2044
static inline void
 
2045
stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
 
2046
{
 
2047
  dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
 
2048
       buf_defined (&sb->next) ? sb->next.len : -1);
 
2049
  ASSERT (buf_defined (&sb->next));
 
2050
  *buf = sb->next;
 
2051
}
 
2052
 
 
2053
bool
 
2054
stream_buf_read_setup_dowork (struct link_socket* sock)
 
2055
{
 
2056
  if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
 
2057
    {
 
2058
      ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
 
2059
      ASSERT (buf_init (&sock->stream_buf.residual, 0));
 
2060
      sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
 
2061
      dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
 
2062
           sock->stream_buf.residual_fully_formed ? "YES" : "NO",
 
2063
           sock->stream_buf.residual.len);
 
2064
    }
 
2065
 
 
2066
  if (!sock->stream_buf.residual_fully_formed)
 
2067
    stream_buf_set_next (&sock->stream_buf);
 
2068
  return !sock->stream_buf.residual_fully_formed;
 
2069
}
 
2070
 
 
2071
bool
 
2072
stream_buf_added (struct stream_buf *sb,
 
2073
                  int length_added)
 
2074
{
 
2075
  dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
 
2076
  if (length_added > 0)
 
2077
    sb->buf.len += length_added;
 
2078
 
 
2079
  /* if length unknown, see if we can get the length prefix from
 
2080
     the head of the buffer */
 
2081
  if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
 
2082
    {
 
2083
      packet_size_type net_size;
 
2084
 
 
2085
#if PORT_SHARE
 
2086
      if (sb->port_share_state == PS_ENABLED)
 
2087
        {
 
2088
          if (!is_openvpn_protocol (&sb->buf))
 
2089
            {
 
2090
              msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
 
2091
              sb->port_share_state = PS_FOREIGN;
 
2092
              sb->error = true;
 
2093
              return false;
 
2094
            }
 
2095
          else
 
2096
            sb->port_share_state = PS_DISABLED;
 
2097
        }
 
2098
#endif
 
2099
 
 
2100
      ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
 
2101
      sb->len = ntohps (net_size);
 
2102
 
 
2103
      if (sb->len < 1 || sb->len > sb->maxlen)
 
2104
        {
 
2105
          msg (M_WARN, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb->len, sb->maxlen);
 
2106
          stream_buf_reset (sb);
 
2107
          sb->error = true;
 
2108
          return false;
 
2109
        }
 
2110
    }
 
2111
 
 
2112
  /* is our incoming packet fully read? */
 
2113
  if (sb->len > 0 && sb->buf.len >= sb->len)
 
2114
    {
 
2115
      /* save any residual data that's part of the next packet */
 
2116
      ASSERT (buf_init (&sb->residual, 0));
 
2117
      if (sb->buf.len > sb->len)
 
2118
          ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
 
2119
      dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
 
2120
           BLEN (&sb->buf),
 
2121
           BLEN (&sb->residual));
 
2122
      return true;
 
2123
    }
 
2124
  else
 
2125
    {
 
2126
      dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
 
2127
      stream_buf_set_next (sb);
 
2128
      return false;
 
2129
    }
 
2130
}
 
2131
 
 
2132
void
 
2133
stream_buf_close (struct stream_buf* sb)
 
2134
{
 
2135
  free_buf (&sb->residual);
 
2136
}
 
2137
 
 
2138
/*
 
2139
 * The listen event is a special event whose sole purpose is
 
2140
 * to tell us that there's a new incoming connection on a
 
2141
 * TCP socket, for use in server mode.
 
2142
 */
 
2143
event_t
 
2144
socket_listen_event_handle (struct link_socket *s)
 
2145
{
 
2146
#ifdef WIN32
 
2147
  if (!defined_net_event_win32 (&s->listen_handle))
 
2148
    init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
 
2149
  return &s->listen_handle;
 
2150
#else
 
2151
  return s->sd;
 
2152
#endif
 
2153
}
 
2154
 
 
2155
/*
 
2156
 * Format IP addresses in ascii
 
2157
 */
 
2158
 
 
2159
const char *
 
2160
print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
 
2161
{
 
2162
  return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
 
2163
}
 
2164
 
 
2165
const char *
 
2166
print_sockaddr_ex (const struct openvpn_sockaddr *addr,
 
2167
                   const char* separator,
 
2168
                   const unsigned int flags,
 
2169
                   struct gc_arena *gc)
 
2170
{
 
2171
  struct buffer out = alloc_buf_gc (128, gc);
 
2172
  bool addr_is_defined;
 
2173
  addr_is_defined = addr_defined (addr);
 
2174
  if (!addr_is_defined) {
 
2175
    return "[undef]";
 
2176
  }
 
2177
  switch(addr->addr.sa.sa_family)
 
2178
    {
 
2179
    case AF_INET:
 
2180
        {
 
2181
          const int port= ntohs (addr->addr.in4.sin_port);
 
2182
          buf_puts (&out, "[AF_INET]");
 
2183
 
 
2184
          if (!(flags & PS_DONT_SHOW_ADDR))
 
2185
            buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->addr.in4.sin_addr) : "[undef]"));
 
2186
 
 
2187
          if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
 
2188
              && port)
 
2189
            {
 
2190
              if (separator)
 
2191
                buf_printf (&out, "%s", separator);
 
2192
 
 
2193
              buf_printf (&out, "%d", port);
 
2194
            }
 
2195
        }
 
2196
      break;
 
2197
    case AF_INET6:
 
2198
        {
 
2199
          const int port= ntohs (addr->addr.in6.sin6_port);
 
2200
          char buf[INET6_ADDRSTRLEN] = "";
 
2201
          buf_puts (&out, "[AF_INET6]");
 
2202
          if (addr_is_defined)
 
2203
            {
 
2204
              getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
 
2205
                          buf, sizeof (buf), NULL, 0, NI_NUMERICHOST);
 
2206
              buf_puts (&out, buf);
 
2207
            }
 
2208
          if (((flags & PS_SHOW_PORT) || (addr_is_defined && (flags & PS_SHOW_PORT_IF_DEFINED)))
 
2209
              && port)
 
2210
            {
 
2211
              if (separator)
 
2212
                buf_puts (&out, separator);
 
2213
 
 
2214
              buf_printf (&out, "%d", port);
 
2215
            }
 
2216
        }
 
2217
      break;
 
2218
    default:
 
2219
      ASSERT(0);
 
2220
    }
 
2221
  return BSTR (&out);
 
2222
}
 
2223
 
 
2224
const char *
 
2225
print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
 
2226
{
 
2227
  return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
 
2228
}
 
2229
 
 
2230
#ifndef IF_NAMESIZE
 
2231
#define IF_NAMESIZE 16
 
2232
#endif
 
2233
 
 
2234
const char *
 
2235
print_link_socket_actual_ex (const struct link_socket_actual *act,
 
2236
                             const char *separator,
 
2237
                             const unsigned int flags,
 
2238
                             struct gc_arena *gc)
 
2239
{
 
2240
  if (act)
 
2241
    {
 
2242
      char ifname[IF_NAMESIZE] = "[undef]";
 
2243
      struct buffer out = alloc_buf_gc (128, gc);
 
2244
      buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
 
2245
#if ENABLE_IP_PKTINFO
 
2246
      if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
 
2247
        {
 
2248
          switch(act->dest.addr.sa.sa_family)
 
2249
            {
 
2250
            case AF_INET:
 
2251
                {
 
2252
                  struct openvpn_sockaddr sa;
 
2253
                  CLEAR (sa);
 
2254
                  sa.addr.in4.sin_family = AF_INET;
 
2255
#ifdef IP_PKTINFO
 
2256
                  sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
 
2257
                  if_indextoname(act->pi.in4.ipi_ifindex, ifname);
 
2258
#elif defined(IP_RECVDSTADDR)
 
2259
                  sa.addr.in4.sin_addr = act->pi.in4;
 
2260
                  ifname[0]=0;
 
2261
#else
 
2262
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 
2263
#endif
 
2264
                  buf_printf (&out, " (via %s%%%s)",
 
2265
                              print_sockaddr_ex (&sa, separator, 0, gc),
 
2266
                              ifname);
 
2267
                }
 
2268
              break;
 
2269
            case AF_INET6:
 
2270
                {
 
2271
                  struct sockaddr_in6 sin6;
 
2272
                  char buf[INET6_ADDRSTRLEN] = "[undef]";
 
2273
                  CLEAR(sin6);
 
2274
                  sin6.sin6_family = AF_INET6;
 
2275
                  sin6.sin6_addr = act->pi.in6.ipi6_addr;
 
2276
                  if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
 
2277
                  if (getnameinfo((struct sockaddr *)&sin6, sizeof (struct sockaddr_in6),
 
2278
                                  buf, sizeof (buf), NULL, 0, NI_NUMERICHOST) == 0)
 
2279
                    buf_printf (&out, " (via %s%%%s)", buf, ifname);
 
2280
                  else
 
2281
                    buf_printf (&out, " (via [getnameinfo() err]%%%s)", ifname);
 
2282
                }
 
2283
              break;
 
2284
            }
 
2285
        }
 
2286
#endif
 
2287
      return BSTR (&out);
 
2288
    }
 
2289
  else
 
2290
    return "[NULL]";
 
2291
}
 
2292
 
 
2293
/*
 
2294
 * Convert an in_addr_t in host byte order
 
2295
 * to an ascii dotted quad.
 
2296
 */
 
2297
const char *
 
2298
print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
 
2299
{
 
2300
  struct in_addr ia;
 
2301
  struct buffer out = alloc_buf_gc (64, gc);
 
2302
 
 
2303
  if (addr || !(flags & IA_EMPTY_IF_UNDEF))
 
2304
    {
 
2305
      CLEAR (ia);
 
2306
      ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
 
2307
 
 
2308
      buf_printf (&out, "%s", inet_ntoa (ia));
 
2309
    }
 
2310
  return BSTR (&out);
 
2311
}
 
2312
 
 
2313
/*
 
2314
 * Convert an in6_addr in host byte order
 
2315
 * to an ascii representation of an IPv6 address
 
2316
 */
 
2317
const char *
 
2318
print_in6_addr (struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
 
2319
{
 
2320
  struct buffer out = alloc_buf_gc (64, gc);
 
2321
  char tmp_out_buf[64];         /* inet_ntop wants pointer to buffer */
 
2322
 
 
2323
  if ( memcmp(&a6, &in6addr_any, sizeof(a6)) != 0 || 
 
2324
       !(flags & IA_EMPTY_IF_UNDEF))
 
2325
    {
 
2326
      inet_ntop (AF_INET6, &a6, tmp_out_buf, sizeof(tmp_out_buf)-1);
 
2327
      buf_printf (&out, "%s", tmp_out_buf );
 
2328
    }
 
2329
  return BSTR (&out);
 
2330
}
 
2331
 
 
2332
#ifndef UINT8_MAX
 
2333
# define UINT8_MAX 0xff
 
2334
#endif
 
2335
 
 
2336
/* add some offset to an ipv6 address
 
2337
 * (add in steps of 8 bits, taking overflow into next round)
 
2338
 */
 
2339
struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add )
 
2340
{
 
2341
    int i;
 
2342
 
 
2343
    for( i=15; i>=0 && add > 0 ; i-- )
 
2344
    {
 
2345
        register int carry;
 
2346
        register uint32_t h;
 
2347
 
 
2348
        h = (unsigned char) base.s6_addr[i];
 
2349
        base.s6_addr[i] = (h+add) & UINT8_MAX;
 
2350
 
 
2351
        /* using explicit carry for the 8-bit additions will catch
 
2352
         * 8-bit and(!) 32-bit overruns nicely
 
2353
         */
 
2354
        carry = ((h & 0xff)  + (add & 0xff)) >> 8;
 
2355
        add = (add>>8) + carry;
 
2356
    }
 
2357
    return base;
 
2358
}
 
2359
 
 
2360
/* set environmental variables for ip/port in *addr */
 
2361
void
 
2362
setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
 
2363
{
 
2364
  char name_buf[256];
 
2365
 
 
2366
  char buf[128];
 
2367
  switch(addr->addr.sa.sa_family)
 
2368
    {
 
2369
    case AF_INET:
 
2370
      if (flags & SA_IP_PORT)
 
2371
        openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
 
2372
      else
 
2373
        openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
 
2374
 
 
2375
      setenv_str (es, name_buf, inet_ntoa (addr->addr.in4.sin_addr));
 
2376
 
 
2377
      if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
 
2378
        {
 
2379
          openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
 
2380
          setenv_int (es, name_buf, ntohs (addr->addr.in4.sin_port));
 
2381
        }
 
2382
      break;
 
2383
    case AF_INET6:
 
2384
      openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip6", name_prefix);
 
2385
      getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
 
2386
                  buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
 
2387
      setenv_str (es, name_buf, buf);
 
2388
 
 
2389
      if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
 
2390
        {
 
2391
          openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
 
2392
          setenv_int (es, name_buf, ntohs (addr->addr.in6.sin6_port));
 
2393
        }
 
2394
      break;
 
2395
    }
 
2396
}
 
2397
 
 
2398
void
 
2399
setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
 
2400
{
 
2401
  if (addr || !(flags & SA_SET_IF_NONZERO))
 
2402
    {
 
2403
      struct openvpn_sockaddr si;
 
2404
      CLEAR (si);
 
2405
      si.addr.in4.sin_family = AF_INET;
 
2406
      si.addr.in4.sin_addr.s_addr = htonl (addr);
 
2407
      setenv_sockaddr (es, name_prefix, &si, flags);
 
2408
    }
 
2409
}
 
2410
 
 
2411
void
 
2412
setenv_link_socket_actual (struct env_set *es,
 
2413
                           const char *name_prefix,
 
2414
                           const struct link_socket_actual *act,
 
2415
                           const unsigned int flags)
 
2416
{
 
2417
  setenv_sockaddr (es, name_prefix, &act->dest, flags);
 
2418
}
 
2419
 
 
2420
/*
 
2421
 * Convert protocol names between index and ascii form.
 
2422
 */
 
2423
 
 
2424
struct proto_names {
 
2425
  const char *short_form;
 
2426
  const char *display_form;
 
2427
  bool  is_dgram;
 
2428
  bool  is_net;
 
2429
  unsigned short proto_af;
 
2430
};
 
2431
 
 
2432
/* Indexed by PROTO_x */
 
2433
static const struct proto_names proto_names[PROTO_N] = {
 
2434
  {"proto-uninitialized",        "proto-NONE",0,0, AF_UNSPEC},
 
2435
  {"udp",        "UDPv4",1,1, AF_INET},
 
2436
  {"tcp-server", "TCPv4_SERVER",0,1, AF_INET},
 
2437
  {"tcp-client", "TCPv4_CLIENT",0,1, AF_INET},
 
2438
  {"tcp",        "TCPv4",0,1, AF_INET},
 
2439
  {"udp6"       ,"UDPv6",1,1, AF_INET6},
 
2440
  {"tcp6-server","TCPv6_SERVER",0,1, AF_INET6},
 
2441
  {"tcp6-client","TCPv6_CLIENT",0,1, AF_INET6},
 
2442
  {"tcp6"       ,"TCPv6",0,1, AF_INET6},
 
2443
};
 
2444
 
 
2445
bool
 
2446
proto_is_net(int proto)
 
2447
{
 
2448
  if (proto < 0 || proto >= PROTO_N)
 
2449
    ASSERT(0);
 
2450
  return proto_names[proto].is_net;
 
2451
}
 
2452
bool
 
2453
proto_is_dgram(int proto)
 
2454
{
 
2455
  if (proto < 0 || proto >= PROTO_N)
 
2456
    ASSERT(0);
 
2457
  return proto_names[proto].is_dgram;
 
2458
}
 
2459
bool
 
2460
proto_is_udp(int proto)
 
2461
{
 
2462
  if (proto < 0 || proto >= PROTO_N)
 
2463
    ASSERT(0);
 
2464
  return proto_names[proto].is_dgram&&proto_names[proto].is_net;
 
2465
}
 
2466
bool
 
2467
proto_is_tcp(int proto)
 
2468
{
 
2469
  if (proto < 0 || proto >= PROTO_N)
 
2470
    ASSERT(0);
 
2471
  return (!proto_names[proto].is_dgram)&&proto_names[proto].is_net;
 
2472
}
 
2473
 
 
2474
unsigned short 
 
2475
proto_sa_family(int proto)
 
2476
{
 
2477
  if (proto < 0 || proto >= PROTO_N)
 
2478
    ASSERT(0);
 
2479
  return proto_names[proto].proto_af;
 
2480
}
 
2481
 
 
2482
int
 
2483
ascii2proto (const char* proto_name)
 
2484
{
 
2485
  int i;
 
2486
  ASSERT (PROTO_N == SIZE (proto_names));
 
2487
  for (i = 0; i < PROTO_N; ++i)
 
2488
    if (!strcmp (proto_name, proto_names[i].short_form))
 
2489
      return i;
 
2490
  return -1;
 
2491
}
 
2492
 
 
2493
const char *
 
2494
proto2ascii (int proto, bool display_form)
 
2495
{
 
2496
  ASSERT (PROTO_N == SIZE (proto_names));
 
2497
  if (proto < 0 || proto >= PROTO_N)
 
2498
    return "[unknown protocol]";
 
2499
  else if (display_form)
 
2500
    return proto_names[proto].display_form;
 
2501
  else
 
2502
    return proto_names[proto].short_form;
 
2503
}
 
2504
 
 
2505
const char *
 
2506
proto2ascii_all (struct gc_arena *gc)
 
2507
{
 
2508
  struct buffer out = alloc_buf_gc (256, gc);
 
2509
  int i;
 
2510
 
 
2511
  ASSERT (PROTO_N == SIZE (proto_names));
 
2512
  for (i = 0; i < PROTO_N; ++i)
 
2513
    {
 
2514
      if (i)
 
2515
        buf_printf(&out, " ");
 
2516
      buf_printf(&out, "[%s]", proto2ascii(i, false));
 
2517
    }
 
2518
  return BSTR (&out);
 
2519
}
 
2520
 
 
2521
int
 
2522
addr_guess_family(int proto, const char *name) 
 
2523
{
 
2524
  unsigned short ret;
 
2525
  if (proto)
 
2526
    {
 
2527
      return proto_sa_family(proto);    /* already stamped */
 
2528
    } 
 
2529
  else
 
2530
    {
 
2531
      struct addrinfo hints , *ai;
 
2532
      int err;
 
2533
      CLEAR(hints);
 
2534
      hints.ai_flags = AI_NUMERICHOST;
 
2535
      err = getaddrinfo(name, NULL, &hints, &ai);
 
2536
      if ( 0 == err )
 
2537
        {
 
2538
          ret=ai->ai_family;
 
2539
          freeaddrinfo(ai);
 
2540
          return ret;
 
2541
        }
 
2542
    }
 
2543
  return AF_INET;       /* default */
 
2544
}
 
2545
const char *
 
2546
addr_family_name (int af) 
 
2547
{
 
2548
  switch (af)
 
2549
    {
 
2550
    case AF_INET:  return "AF_INET";
 
2551
    case AF_INET6: return "AF_INET6";
 
2552
    }
 
2553
  return "AF_UNSPEC";
 
2554
}
 
2555
 
 
2556
/*
 
2557
 * Given a local proto, return local proto
 
2558
 * if !remote, or compatible remote proto
 
2559
 * if remote.
 
2560
 *
 
2561
 * This is used for options compatibility
 
2562
 * checking.
 
2563
 *
 
2564
 * IPv6 and IPv4 protocols are comptabile but OpenVPN
 
2565
 * has always sent UDPv4, TCPv4 over the wire. Keep these
 
2566
 * strings for backward compatbility
 
2567
 */
 
2568
int
 
2569
proto_remote (int proto, bool remote)
 
2570
{
 
2571
  ASSERT (proto >= 0 && proto < PROTO_N);
 
2572
  if (remote)
 
2573
    {
 
2574
      switch (proto)
 
2575
      {
 
2576
      case PROTO_TCPv4_SERVER: return PROTO_TCPv4_CLIENT;
 
2577
      case PROTO_TCPv4_CLIENT: return PROTO_TCPv4_SERVER;
 
2578
      case PROTO_TCPv6_SERVER: return PROTO_TCPv4_CLIENT;
 
2579
      case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_SERVER;
 
2580
      case PROTO_UDPv6: return PROTO_UDPv4;
 
2581
      }
 
2582
    }
 
2583
  else
 
2584
    {
 
2585
      switch (proto)
 
2586
      {
 
2587
      case PROTO_TCPv6_SERVER: return PROTO_TCPv4_SERVER;
 
2588
      case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_CLIENT;
 
2589
      case PROTO_UDPv6: return PROTO_UDPv4;
 
2590
      }
 
2591
    }
 
2592
  return proto;
 
2593
}
 
2594
 
 
2595
/*
 
2596
 * Bad incoming address lengths that differ from what
 
2597
 * we expect are considered to be fatal errors.
 
2598
 */
 
2599
void
 
2600
bad_address_length (int actual, int expected)
 
2601
{
 
2602
  msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
 
2603
       actual,
 
2604
       expected);
 
2605
}
 
2606
 
 
2607
/*
 
2608
 * Socket Read Routines
 
2609
 */
 
2610
 
 
2611
int
 
2612
link_socket_read_tcp (struct link_socket *sock,
 
2613
                      struct buffer *buf)
 
2614
{
 
2615
  int len = 0;
 
2616
 
 
2617
  if (!sock->stream_buf.residual_fully_formed)
 
2618
    {
 
2619
#ifdef WIN32
 
2620
      len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
 
2621
#else
 
2622
      struct buffer frag;
 
2623
      stream_buf_get_next (&sock->stream_buf, &frag);
 
2624
      len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
 
2625
#endif
 
2626
 
 
2627
      if (!len)
 
2628
        sock->stream_reset = true;
 
2629
      if (len <= 0)
 
2630
        return buf->len = len;
 
2631
    }
 
2632
 
 
2633
  if (sock->stream_buf.residual_fully_formed
 
2634
      || stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
 
2635
    {
 
2636
      stream_buf_get_final (&sock->stream_buf, buf);
 
2637
      stream_buf_reset (&sock->stream_buf);
 
2638
      return buf->len;
 
2639
    }
 
2640
  else
 
2641
    return buf->len = 0; /* no error, but packet is still incomplete */
 
2642
}
 
2643
 
 
2644
#ifndef WIN32
 
2645
 
 
2646
#if ENABLE_IP_PKTINFO
 
2647
 
 
2648
#pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
 
2649
struct openvpn_in4_pktinfo
 
2650
{
 
2651
  struct cmsghdr cmsghdr;
 
2652
#ifdef HAVE_IN_PKTINFO
 
2653
  struct in_pktinfo pi4;
 
2654
#elif defined(IP_RECVDSTADDR)
 
2655
  struct in_addr pi4;
 
2656
#endif
 
2657
};
 
2658
struct openvpn_in6_pktinfo
 
2659
{
 
2660
  struct cmsghdr cmsghdr;
 
2661
  struct in6_pktinfo pi6;
 
2662
};
 
2663
 
 
2664
union openvpn_pktinfo {
 
2665
        struct openvpn_in4_pktinfo msgpi4;
 
2666
        struct openvpn_in6_pktinfo msgpi6;
 
2667
};
 
2668
#pragma pack()
 
2669
 
 
2670
static socklen_t
 
2671
link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
 
2672
                                    struct buffer *buf,
 
2673
                                    int maxsize,
 
2674
                                    struct link_socket_actual *from)
 
2675
{
 
2676
  struct iovec iov;
 
2677
  union openvpn_pktinfo opi;
 
2678
  struct msghdr mesg;
 
2679
  socklen_t fromlen = sizeof (from->dest.addr);
 
2680
 
 
2681
  iov.iov_base = BPTR (buf);
 
2682
  iov.iov_len = maxsize;
 
2683
  mesg.msg_iov = &iov;
 
2684
  mesg.msg_iovlen = 1;
 
2685
  mesg.msg_name = &from->dest.addr;
 
2686
  mesg.msg_namelen = fromlen;
 
2687
  mesg.msg_control = &opi;
 
2688
  mesg.msg_controllen = sizeof opi;
 
2689
  buf->len = recvmsg (sock->sd, &mesg, 0);
 
2690
  if (buf->len >= 0)
 
2691
    {
 
2692
      struct cmsghdr *cmsg;
 
2693
      fromlen = mesg.msg_namelen;
 
2694
      cmsg = CMSG_FIRSTHDR (&mesg);
 
2695
      if (cmsg != NULL
 
2696
          && CMSG_NXTHDR (&mesg, cmsg) == NULL
 
2697
#ifdef IP_PKTINFO
 
2698
          && cmsg->cmsg_level == SOL_IP 
 
2699
          && cmsg->cmsg_type == IP_PKTINFO
 
2700
#elif defined(IP_RECVDSTADDR)
 
2701
          && cmsg->cmsg_level == IPPROTO_IP
 
2702
          && cmsg->cmsg_type == IP_RECVDSTADDR
 
2703
#else
 
2704
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 
2705
#endif
 
2706
          && cmsg->cmsg_len >= sizeof (struct openvpn_in4_pktinfo))
 
2707
        {
 
2708
#ifdef IP_PKTINFO
 
2709
          struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
 
2710
          from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
 
2711
          from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
 
2712
#elif defined(IP_RECVDSTADDR)
 
2713
          from->pi.in4 = *(struct in_addr*) CMSG_DATA (cmsg);
 
2714
#else
 
2715
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 
2716
#endif
 
2717
        }
 
2718
      else if (cmsg != NULL
 
2719
          && CMSG_NXTHDR (&mesg, cmsg) == NULL
 
2720
          && cmsg->cmsg_level == IPPROTO_IPV6 
 
2721
          && cmsg->cmsg_type == IPV6_PKTINFO
 
2722
          && cmsg->cmsg_len >= sizeof (struct openvpn_in6_pktinfo))
 
2723
        {
 
2724
          struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
 
2725
          from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
 
2726
          from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
 
2727
        }
 
2728
    }
 
2729
  return fromlen;
 
2730
}
 
2731
#endif
 
2732
 
 
2733
int
 
2734
link_socket_read_udp_posix (struct link_socket *sock,
 
2735
                            struct buffer *buf,
 
2736
                            int maxsize,
 
2737
                            struct link_socket_actual *from)
 
2738
{
 
2739
  socklen_t fromlen = sizeof (from->dest.addr);
 
2740
  socklen_t expectedlen = af_addr_size(proto_sa_family(sock->info.proto));
 
2741
  addr_zero_host(&from->dest);
 
2742
  ASSERT (buf_safe (buf, maxsize));
 
2743
#if ENABLE_IP_PKTINFO
 
2744
  /* Both PROTO_UDPv4 and PROTO_UDPv6 */
 
2745
  if (proto_is_udp(sock->info.proto) && sock->sockflags & SF_USE_IP_PKTINFO)
 
2746
    fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
 
2747
  else
 
2748
#endif
 
2749
    buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
 
2750
                         &from->dest.addr.sa, &fromlen);
 
2751
  if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
 
2752
    bad_address_length (fromlen, expectedlen);
 
2753
  return buf->len;
 
2754
}
 
2755
 
 
2756
#endif
 
2757
 
 
2758
/*
 
2759
 * Socket Write Routines
 
2760
 */
 
2761
 
 
2762
int
 
2763
link_socket_write_tcp (struct link_socket *sock,
 
2764
                       struct buffer *buf,
 
2765
                       struct link_socket_actual *to)
 
2766
{
 
2767
  packet_size_type len = BLEN (buf);
 
2768
  dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
 
2769
  ASSERT (len <= sock->stream_buf.maxlen);
 
2770
  len = htonps (len);
 
2771
  ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
 
2772
#ifdef WIN32
 
2773
  return link_socket_write_win32 (sock, buf, to);
 
2774
#else
 
2775
  return link_socket_write_tcp_posix (sock, buf, to);  
 
2776
#endif
 
2777
}
 
2778
 
 
2779
#if ENABLE_IP_PKTINFO
 
2780
 
 
2781
int
 
2782
link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
 
2783
                                     struct buffer *buf,
 
2784
                                     struct link_socket_actual *to)
 
2785
{
 
2786
  struct iovec iov;
 
2787
  struct msghdr mesg;
 
2788
  struct cmsghdr *cmsg;
 
2789
 
 
2790
  iov.iov_base = BPTR (buf);
 
2791
  iov.iov_len = BLEN (buf);
 
2792
  mesg.msg_iov = &iov;
 
2793
  mesg.msg_iovlen = 1;
 
2794
  switch (sock->info.lsa->remote.addr.sa.sa_family)
 
2795
    {
 
2796
    case AF_INET:
 
2797
      {
 
2798
        struct openvpn_in4_pktinfo msgpi4;
 
2799
        mesg.msg_name = &to->dest.addr.sa;
 
2800
        mesg.msg_namelen = sizeof (struct sockaddr_in);
 
2801
        mesg.msg_control = &msgpi4;
 
2802
        mesg.msg_controllen = sizeof msgpi4;
 
2803
        mesg.msg_flags = 0;
 
2804
        cmsg = CMSG_FIRSTHDR (&mesg);
 
2805
        cmsg->cmsg_len = sizeof (struct openvpn_in4_pktinfo);
 
2806
#ifdef HAVE_IN_PKTINFO
 
2807
        cmsg->cmsg_level = SOL_IP;
 
2808
        cmsg->cmsg_type = IP_PKTINFO;
 
2809
        {
 
2810
        struct in_pktinfo *pkti;
 
2811
        pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
 
2812
        pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
 
2813
        pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
 
2814
        pkti->ipi_addr.s_addr = 0;
 
2815
        }
 
2816
#elif defined(IP_RECVDSTADDR)
 
2817
        cmsg->cmsg_level = IPPROTO_IP;
 
2818
        cmsg->cmsg_type = IP_RECVDSTADDR;
 
2819
        *(struct in_addr *) CMSG_DATA (cmsg) = to->pi.in4;
 
2820
#else
 
2821
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
 
2822
#endif
 
2823
        break;
 
2824
      }
 
2825
    case AF_INET6:
 
2826
      {
 
2827
        struct openvpn_in6_pktinfo msgpi6;
 
2828
        struct in6_pktinfo *pkti6;
 
2829
        mesg.msg_name = &to->dest.addr.sa;
 
2830
        mesg.msg_namelen = sizeof (struct sockaddr_in6);
 
2831
        mesg.msg_control = &msgpi6;
 
2832
        mesg.msg_controllen = sizeof msgpi6;
 
2833
        mesg.msg_flags = 0;
 
2834
        cmsg = CMSG_FIRSTHDR (&mesg);
 
2835
        cmsg->cmsg_len = sizeof (struct openvpn_in6_pktinfo);
 
2836
        cmsg->cmsg_level = IPPROTO_IPV6;
 
2837
        cmsg->cmsg_type = IPV6_PKTINFO;
 
2838
        pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
 
2839
        pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
 
2840
        pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
 
2841
        break;
 
2842
      }
 
2843
    default: ASSERT(0);
 
2844
    }
 
2845
  return sendmsg (sock->sd, &mesg, 0);
 
2846
}
 
2847
 
 
2848
#endif
 
2849
 
 
2850
/*
 
2851
 * Win32 overlapped socket I/O functions.
 
2852
 */
 
2853
 
 
2854
#ifdef WIN32
 
2855
 
 
2856
int
 
2857
socket_recv_queue (struct link_socket *sock, int maxsize)
 
2858
{
 
2859
  if (sock->reads.iostate == IOSTATE_INITIAL)
 
2860
    {
 
2861
      WSABUF wsabuf[1];
 
2862
      int status;
 
2863
 
 
2864
      /* reset buf to its initial state */
 
2865
      if (proto_is_udp(sock->info.proto))
 
2866
        {
 
2867
          sock->reads.buf = sock->reads.buf_init;
 
2868
        }
 
2869
      else if (proto_is_tcp(sock->info.proto))
 
2870
        {
 
2871
          stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
 
2872
        }
 
2873
      else
 
2874
        {
 
2875
          ASSERT (0);
 
2876
        }
 
2877
 
 
2878
      /* Win32 docs say it's okay to allocate the wsabuf on the stack */
 
2879
      wsabuf[0].buf = BPTR (&sock->reads.buf);
 
2880
      wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
 
2881
 
 
2882
      /* check for buffer overflow */
 
2883
      ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
 
2884
 
 
2885
      /* the overlapped read will signal this event on I/O completion */
 
2886
      ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
 
2887
      sock->reads.flags = 0;
 
2888
 
 
2889
      if (proto_is_udp(sock->info.proto))
 
2890
        {
 
2891
          sock->reads.addr_defined = true;
 
2892
          if (sock->info.proto == PROTO_UDPv6)
 
2893
            sock->reads.addrlen = sizeof (sock->reads.addr6);
 
2894
          else
 
2895
            sock->reads.addrlen = sizeof (sock->reads.addr);
 
2896
          status = WSARecvFrom(
 
2897
                               sock->sd,
 
2898
                               wsabuf,
 
2899
                               1,
 
2900
                               &sock->reads.size,
 
2901
                               &sock->reads.flags,
 
2902
                               (struct sockaddr *) &sock->reads.addr,
 
2903
                               &sock->reads.addrlen,
 
2904
                               &sock->reads.overlapped,
 
2905
                               NULL);
 
2906
        }
 
2907
      else if (proto_is_tcp(sock->info.proto))
 
2908
        {
 
2909
          sock->reads.addr_defined = false;
 
2910
          status = WSARecv(
 
2911
                           sock->sd,
 
2912
                           wsabuf,
 
2913
                           1,
 
2914
                           &sock->reads.size,
 
2915
                           &sock->reads.flags,
 
2916
                           &sock->reads.overlapped,
 
2917
                           NULL);
 
2918
        }
 
2919
      else
 
2920
        {
 
2921
          status = 0;
 
2922
          ASSERT (0);
 
2923
        }
 
2924
 
 
2925
      if (!status) /* operation completed immediately? */
 
2926
        {
 
2927
          int addrlen = af_addr_size(sock->info.lsa->local.addr.sa.sa_family);
 
2928
          if (sock->reads.addr_defined && sock->reads.addrlen != addrlen)
 
2929
            bad_address_length (sock->reads.addrlen, addrlen);
 
2930
          sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
 
2931
 
 
2932
          /* since we got an immediate return, we must signal the event object ourselves */
 
2933
          ASSERT (SetEvent (sock->reads.overlapped.hEvent));
 
2934
          sock->reads.status = 0;
 
2935
 
 
2936
          dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
 
2937
               (int) wsabuf[0].len,
 
2938
               (int) sock->reads.size);        
 
2939
        }
 
2940
      else
 
2941
        {
 
2942
          status = WSAGetLastError (); 
 
2943
          if (status == WSA_IO_PENDING) /* operation queued? */
 
2944
            {
 
2945
              sock->reads.iostate = IOSTATE_QUEUED;
 
2946
              sock->reads.status = status;
 
2947
              dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
 
2948
                   (int) wsabuf[0].len);
 
2949
            }
 
2950
          else /* error occurred */
 
2951
            {
 
2952
              struct gc_arena gc = gc_new ();
 
2953
              ASSERT (SetEvent (sock->reads.overlapped.hEvent));
 
2954
              sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
 
2955
              sock->reads.status = status;
 
2956
              dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
 
2957
                   (int) wsabuf[0].len,
 
2958
                   strerror_win32 (status, &gc));
 
2959
              gc_free (&gc);
 
2960
            }
 
2961
        }
 
2962
    }
 
2963
  return sock->reads.iostate;
 
2964
}
 
2965
 
 
2966
int
 
2967
socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
 
2968
{
 
2969
  if (sock->writes.iostate == IOSTATE_INITIAL)
 
2970
    {
 
2971
      WSABUF wsabuf[1];
 
2972
      int status;
 
2973
 
 
2974
      /* make a private copy of buf */
 
2975
      sock->writes.buf = sock->writes.buf_init;
 
2976
      sock->writes.buf.len = 0;
 
2977
      ASSERT (buf_copy (&sock->writes.buf, buf));
 
2978
 
 
2979
      /* Win32 docs say it's okay to allocate the wsabuf on the stack */
 
2980
      wsabuf[0].buf = BPTR (&sock->writes.buf);
 
2981
      wsabuf[0].len = BLEN (&sock->writes.buf);
 
2982
 
 
2983
      /* the overlapped write will signal this event on I/O completion */
 
2984
      ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
 
2985
      sock->writes.flags = 0;
 
2986
 
 
2987
      if (proto_is_udp(sock->info.proto))
 
2988
        {
 
2989
          /* set destination address for UDP writes */
 
2990
          sock->writes.addr_defined = true;
 
2991
          if (sock->info.proto == PROTO_UDPv6)
 
2992
            {
 
2993
              sock->writes.addr6 = to->dest.addr.in6;
 
2994
              sock->writes.addrlen = sizeof (sock->writes.addr6);
 
2995
            }
 
2996
          else
 
2997
            {
 
2998
              sock->writes.addr = to->dest.addr.in4;
 
2999
              sock->writes.addrlen = sizeof (sock->writes.addr);
 
3000
            }
 
3001
 
 
3002
          status = WSASendTo(
 
3003
                               sock->sd,
 
3004
                               wsabuf,
 
3005
                               1,
 
3006
                               &sock->writes.size,
 
3007
                               sock->writes.flags,
 
3008
                               (struct sockaddr *) &sock->writes.addr,
 
3009
                               sock->writes.addrlen,
 
3010
                               &sock->writes.overlapped,
 
3011
                               NULL);
 
3012
        }
 
3013
      else if (proto_is_tcp(sock->info.proto))
 
3014
        {
 
3015
          /* destination address for TCP writes was established on connection initiation */
 
3016
          sock->writes.addr_defined = false;
 
3017
 
 
3018
          status = WSASend(
 
3019
                           sock->sd,
 
3020
                           wsabuf,
 
3021
                           1,
 
3022
                           &sock->writes.size,
 
3023
                           sock->writes.flags,
 
3024
                           &sock->writes.overlapped,
 
3025
                           NULL);
 
3026
        }
 
3027
      else 
 
3028
        {
 
3029
          status = 0;
 
3030
          ASSERT (0);
 
3031
        }
 
3032
 
 
3033
      if (!status) /* operation completed immediately? */
 
3034
        {
 
3035
          sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
 
3036
 
 
3037
          /* since we got an immediate return, we must signal the event object ourselves */
 
3038
          ASSERT (SetEvent (sock->writes.overlapped.hEvent));
 
3039
 
 
3040
          sock->writes.status = 0;
 
3041
 
 
3042
          dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
 
3043
               (int) wsabuf[0].len,
 
3044
               (int) sock->writes.size);               
 
3045
        }
 
3046
      else
 
3047
        {
 
3048
          status = WSAGetLastError (); 
 
3049
          if (status == WSA_IO_PENDING) /* operation queued? */
 
3050
            {
 
3051
              sock->writes.iostate = IOSTATE_QUEUED;
 
3052
              sock->writes.status = status;
 
3053
              dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
 
3054
                   (int) wsabuf[0].len);
 
3055
            }
 
3056
          else /* error occurred */
 
3057
            {
 
3058
              struct gc_arena gc = gc_new ();
 
3059
              ASSERT (SetEvent (sock->writes.overlapped.hEvent));
 
3060
              sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
 
3061
              sock->writes.status = status;
 
3062
 
 
3063
              dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
 
3064
                   (int) wsabuf[0].len,
 
3065
                   strerror_win32 (status, &gc));
 
3066
 
 
3067
              gc_free (&gc);
 
3068
            }
 
3069
        }
 
3070
    }
 
3071
  return sock->writes.iostate;
 
3072
}
 
3073
 
 
3074
int
 
3075
socket_finalize (SOCKET s,
 
3076
                 struct overlapped_io *io,
 
3077
                 struct buffer *buf,
 
3078
                 struct link_socket_actual *from)
 
3079
{
 
3080
  int ret = -1;
 
3081
  BOOL status;
 
3082
 
 
3083
  switch (io->iostate)
 
3084
    {
 
3085
    case IOSTATE_QUEUED:
 
3086
      status = WSAGetOverlappedResult(
 
3087
                                      s,
 
3088
                                      &io->overlapped,
 
3089
                                      &io->size,
 
3090
                                      FALSE,
 
3091
                                      &io->flags
 
3092
                                      );
 
3093
      if (status)
 
3094
        {
 
3095
          /* successful return for a queued operation */
 
3096
          if (buf)
 
3097
            *buf = io->buf;
 
3098
          ret = io->size;
 
3099
          io->iostate = IOSTATE_INITIAL;
 
3100
          ASSERT (ResetEvent (io->overlapped.hEvent));
 
3101
 
 
3102
          dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
 
3103
        }
 
3104
      else
 
3105
        {
 
3106
          /* error during a queued operation */
 
3107
          ret = -1;
 
3108
          if (WSAGetLastError() != WSA_IO_INCOMPLETE)
 
3109
            {
 
3110
              /* if no error (i.e. just not finished yet), then DON'T execute this code */
 
3111
              io->iostate = IOSTATE_INITIAL;
 
3112
              ASSERT (ResetEvent (io->overlapped.hEvent));
 
3113
              msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion error");
 
3114
            }
 
3115
        }
 
3116
      break;
 
3117
 
 
3118
    case IOSTATE_IMMEDIATE_RETURN:
 
3119
      io->iostate = IOSTATE_INITIAL;
 
3120
      ASSERT (ResetEvent (io->overlapped.hEvent));
 
3121
      if (io->status)
 
3122
        {
 
3123
          /* error return for a non-queued operation */
 
3124
          WSASetLastError (io->status);
 
3125
          ret = -1;
 
3126
          msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion non-queued error");
 
3127
        }
 
3128
      else
 
3129
        {
 
3130
          /* successful return for a non-queued operation */
 
3131
          if (buf)
 
3132
            *buf = io->buf;
 
3133
          ret = io->size;
 
3134
          dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
 
3135
        }
 
3136
      break;
 
3137
 
 
3138
    case IOSTATE_INITIAL: /* were we called without proper queueing? */
 
3139
      WSASetLastError (WSAEINVAL);
 
3140
      ret = -1;
 
3141
      dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
 
3142
      break;
 
3143
 
 
3144
    default:
 
3145
      ASSERT (0);
 
3146
    }
 
3147
  
 
3148
  /* return from address if requested */
 
3149
  if (from)
 
3150
    {
 
3151
      if (ret >= 0 && io->addr_defined)
 
3152
        {
 
3153
          /* TODO(jjo): streamline this mess */
 
3154
          /* in this func we dont have relevant info about the PF_ of this
 
3155
           * endpoint, as link_socket_actual will be zero for the 1st received packet
 
3156
           *
 
3157
           * Test for inets PF_ possible sizes
 
3158
           */
 
3159
          switch (io->addrlen)
 
3160
            {
 
3161
            case sizeof(struct sockaddr_in):
 
3162
            case sizeof(struct sockaddr_in6):
 
3163
            /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
 
3164
             * under WIN32*/
 
3165
            case sizeof(struct sockaddr_in6)-4:
 
3166
              break;
 
3167
            default:
 
3168
              bad_address_length (io->addrlen, af_addr_size(io->addr.sin_family));
 
3169
            }
 
3170
 
 
3171
          switch (io->addr.sin_family)
 
3172
            {
 
3173
            case AF_INET:
 
3174
              from->dest.addr.in4 = io->addr;
 
3175
              break;
 
3176
            case AF_INET6:
 
3177
              from->dest.addr.in6 = io->addr6;
 
3178
              break;
 
3179
            }
 
3180
        }
 
3181
      else
 
3182
        CLEAR (from->dest.addr);
 
3183
    }
 
3184
  
 
3185
  if (buf)
 
3186
    buf->len = ret;
 
3187
  return ret;
 
3188
}
 
3189
 
 
3190
#endif /* WIN32 */
 
3191
 
 
3192
/*
 
3193
 * Socket event notification
 
3194
 */
 
3195
 
 
3196
unsigned int
 
3197
socket_set (struct link_socket *s,
 
3198
            struct event_set *es,
 
3199
            unsigned int rwflags,
 
3200
            void *arg,
 
3201
            unsigned int *persistent)
 
3202
{
 
3203
  if (s)
 
3204
    {
 
3205
      if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
 
3206
        {
 
3207
          ASSERT (!persistent);
 
3208
          rwflags &= ~EVENT_READ;
 
3209
        }
 
3210
      
 
3211
#ifdef WIN32
 
3212
      if (rwflags & EVENT_READ)
 
3213
        socket_recv_queue (s, 0);
 
3214
#endif
 
3215
 
 
3216
      /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
 
3217
      if (!persistent || *persistent != rwflags)
 
3218
        {
 
3219
          event_ctl (es, socket_event_handle (s), rwflags, arg);
 
3220
          if (persistent)
 
3221
            *persistent = rwflags;
 
3222
        }
 
3223
 
 
3224
      s->rwflags_debug = rwflags;
 
3225
    }
 
3226
  return rwflags;
 
3227
}
 
3228
 
 
3229
void
 
3230
sd_close (socket_descriptor_t *sd)
 
3231
{
 
3232
  if (sd && socket_defined (*sd))
 
3233
    {
 
3234
      openvpn_close_socket (*sd);
 
3235
      *sd = SOCKET_UNDEFINED;
 
3236
    }
 
3237
}
 
3238
 
 
3239
#if UNIX_SOCK_SUPPORT
 
3240
 
 
3241
/*
 
3242
 * code for unix domain sockets
 
3243
 */
 
3244
 
 
3245
const char *
 
3246
sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
 
3247
{
 
3248
  if (local && local->sun_family == PF_UNIX)
 
3249
    return local->sun_path;
 
3250
  else
 
3251
    return null;
 
3252
}
 
3253
 
 
3254
socket_descriptor_t
 
3255
create_socket_unix (void)
 
3256
{
 
3257
  socket_descriptor_t sd;
 
3258
 
 
3259
  if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
 
3260
    msg (M_ERR, "Cannot create unix domain socket");
 
3261
  return sd;
 
3262
}
 
3263
 
 
3264
void
 
3265
socket_bind_unix (socket_descriptor_t sd,
 
3266
                  struct sockaddr_un *local,
 
3267
                  const char *prefix)
 
3268
{
 
3269
  struct gc_arena gc = gc_new ();
 
3270
 
 
3271
#ifdef HAVE_UMASK
 
3272
  const mode_t orig_umask = umask (0);
 
3273
#endif
 
3274
 
 
3275
  if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
 
3276
    {
 
3277
      const int errnum = openvpn_errno ();
 
3278
      msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
 
3279
           prefix,
 
3280
           (int)sd,
 
3281
           sockaddr_unix_name (local, "NULL"),
 
3282
           strerror_ts (errnum, &gc));
 
3283
    }
 
3284
 
 
3285
#ifdef HAVE_UMASK
 
3286
  umask (orig_umask);
 
3287
#endif
 
3288
 
 
3289
  gc_free (&gc);
 
3290
}
 
3291
 
 
3292
socket_descriptor_t
 
3293
socket_accept_unix (socket_descriptor_t sd,
 
3294
                    struct sockaddr_un *remote)
 
3295
{
 
3296
  socklen_t remote_len = sizeof (struct sockaddr_un);
 
3297
  socket_descriptor_t ret;
 
3298
 
 
3299
  CLEAR (*remote);
 
3300
  ret = accept (sd, (struct sockaddr *) remote, &remote_len);
 
3301
  return ret;
 
3302
}
 
3303
 
 
3304
int
 
3305
socket_connect_unix (socket_descriptor_t sd,
 
3306
                     struct sockaddr_un *remote)
 
3307
{
 
3308
  int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
 
3309
  if (status)
 
3310
    status = openvpn_errno ();
 
3311
  return status;
 
3312
}
 
3313
 
 
3314
void
 
3315
sockaddr_unix_init (struct sockaddr_un *local, const char *path)
 
3316
{
 
3317
  local->sun_family = PF_UNIX;
 
3318
  strncpynt (local->sun_path, path, sizeof (local->sun_path));
 
3319
}
 
3320
 
 
3321
void
 
3322
socket_delete_unix (const struct sockaddr_un *local)
 
3323
{
 
3324
  const char *name = sockaddr_unix_name (local, NULL);
 
3325
#ifdef HAVE_UNLINK
 
3326
  if (name && strlen (name))
 
3327
    unlink (name);
 
3328
#endif
 
3329
}
 
3330
 
 
3331
bool
 
3332
unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
 
3333
{
 
3334
#ifdef HAVE_GETPEEREID
 
3335
  uid_t u;
 
3336
  gid_t g;
 
3337
  if (getpeereid (sd, &u, &g) == -1) 
 
3338
    return false;
 
3339
  if (uid)
 
3340
    *uid = u;
 
3341
  if (gid)
 
3342
    *gid = g;
 
3343
  return true;
 
3344
#elif defined(SO_PEERCRED)
 
3345
  struct ucred peercred;
 
3346
  socklen_t so_len = sizeof(peercred);
 
3347
  if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1) 
 
3348
    return false;
 
3349
  if (uid)
 
3350
    *uid = peercred.uid;
 
3351
  if (gid)
 
3352
    *gid = peercred.gid;
 
3353
  return true;
 
3354
#else
 
3355
  return false;
 
3356
#endif
 
3357
}
 
3358
 
 
3359
#endif