~smoser/ubuntu/oneiric/openvpn/lp-794916

« back to all changes in this revision

Viewing changes to .pc/jjo-ipv6-support.patch/socket.c

  • Committer: Bazaar Package Importer
  • Author(s): Chuck Short
  • Date: 2010-05-05 03:06:19 UTC
  • mfrom: (10.2.6 sid)
  • Revision ID: james.westby@ubuntu.com-20100505030619-cwre0snhgx1mql53
Tags: 2.1.0-2ubuntu1
* Merge from debian unstable.  Remaining changes:
  + debian/openvpn.init.d:
    - Do not use start-stop-daemon and use </dev/null to avoid blocking boot
    - Show per-VPN result messages
    - Add "--script-security 2" by default for backwards compatablitiy
   + debian/control: Add lsb-base >= 3.2-14 to allow status_of_proc() 

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