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

« back to all changes in this revision

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