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

« back to all changes in this revision

Viewing changes to .pc/ipv6-payload.patch/forward.c

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 *  OpenVPN -- An application to securely tunnel IP networks
3
 
 *             over a single TCP/UDP port, with support for SSL/TLS-based
4
 
 *             session authentication and key exchange,
5
 
 *             packet encryption, packet authentication, and
6
 
 *             packet compression.
7
 
 *
8
 
 *  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9
 
 *
10
 
 *  This program is free software; you can redistribute it and/or modify
11
 
 *  it under the terms of the GNU General Public License version 2
12
 
 *  as published by the Free Software Foundation.
13
 
 *
14
 
 *  This program is distributed in the hope that it will be useful,
15
 
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 
 *  GNU General Public License for more details.
18
 
 *
19
 
 *  You should have received a copy of the GNU General Public License
20
 
 *  along with this program (see the file COPYING included with this
21
 
 *  distribution); if not, write to the Free Software Foundation, Inc.,
22
 
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 
 */
24
 
 
25
 
#include "syshead.h"
26
 
 
27
 
#include "forward.h"
28
 
#include "init.h"
29
 
#include "push.h"
30
 
#include "gremlin.h"
31
 
#include "mss.h"
32
 
#include "event.h"
33
 
#include "ps.h"
34
 
#include "dhcp.h"
35
 
#include "common.h"
36
 
 
37
 
#include "memdbg.h"
38
 
 
39
 
#include "forward-inline.h"
40
 
#include "occ-inline.h"
41
 
#include "ping-inline.h"
42
 
 
43
 
counter_type link_read_bytes_global;  /* GLOBAL */
44
 
counter_type link_write_bytes_global; /* GLOBAL */
45
 
 
46
 
/* show event wait debugging info */
47
 
 
48
 
#ifdef ENABLE_DEBUG
49
 
 
50
 
const char *
51
 
wait_status_string (struct context *c, struct gc_arena *gc)
52
 
{
53
 
  struct buffer out = alloc_buf_gc (64, gc);
54
 
  buf_printf (&out, "I/O WAIT %s|%s|%s|%s %s",
55
 
              tun_stat (c->c1.tuntap, EVENT_READ, gc),
56
 
              tun_stat (c->c1.tuntap, EVENT_WRITE, gc),
57
 
              socket_stat (c->c2.link_socket, EVENT_READ, gc),
58
 
              socket_stat (c->c2.link_socket, EVENT_WRITE, gc),
59
 
              tv_string (&c->c2.timeval, gc));
60
 
  return BSTR (&out);
61
 
}
62
 
 
63
 
void
64
 
show_wait_status (struct context *c)
65
 
{
66
 
  struct gc_arena gc = gc_new ();
67
 
  dmsg (D_EVENT_WAIT, "%s", wait_status_string (c, &gc));
68
 
  gc_free (&gc);
69
 
}
70
 
 
71
 
#endif
72
 
 
73
 
/*
74
 
 * In TLS mode, let TLS level respond to any control-channel
75
 
 * packets which were received, or prepare any packets for
76
 
 * transmission.
77
 
 *
78
 
 * tmp_int is purely an optimization that allows us to call
79
 
 * tls_multi_process less frequently when there's not much
80
 
 * traffic on the control-channel.
81
 
 *
82
 
 */
83
 
#if defined(USE_CRYPTO) && defined(USE_SSL)
84
 
void
85
 
check_tls_dowork (struct context *c)
86
 
{
87
 
  interval_t wakeup = BIG_TIMEOUT;
88
 
 
89
 
  if (interval_test (&c->c2.tmp_int))
90
 
    {
91
 
      const int tmp_status = tls_multi_process
92
 
        (c->c2.tls_multi, &c->c2.to_link, &c->c2.to_link_addr,
93
 
         get_link_socket_info (c), &wakeup);
94
 
      if (tmp_status == TLSMP_ACTIVE)
95
 
        {
96
 
          update_time ();
97
 
          interval_action (&c->c2.tmp_int);
98
 
        }
99
 
      else if (tmp_status == TLSMP_KILL)
100
 
        {
101
 
          c->sig->signal_received = SIGTERM;
102
 
          c->sig->signal_text = "auth-control-exit";
103
 
        }
104
 
 
105
 
      interval_future_trigger (&c->c2.tmp_int, wakeup);
106
 
    }
107
 
 
108
 
  interval_schedule_wakeup (&c->c2.tmp_int, &wakeup);
109
 
 
110
 
  if (wakeup)
111
 
    context_reschedule_sec (c, wakeup);
112
 
}
113
 
#endif
114
 
 
115
 
#if defined(USE_CRYPTO) && defined(USE_SSL)
116
 
 
117
 
void
118
 
check_tls_errors_co (struct context *c)
119
 
{
120
 
  msg (D_STREAM_ERRORS, "Fatal TLS error (check_tls_errors_co), restarting");
121
 
  c->sig->signal_received = c->c2.tls_exit_signal; /* SOFT-SIGUSR1 -- TLS error */
122
 
  c->sig->signal_text = "tls-error";
123
 
}
124
 
 
125
 
void
126
 
check_tls_errors_nco (struct context *c)
127
 
{
128
 
  c->sig->signal_received = c->c2.tls_exit_signal; /* SOFT-SIGUSR1 -- TLS error */
129
 
  c->sig->signal_text = "tls-error";
130
 
}
131
 
 
132
 
#endif
133
 
 
134
 
#if P2MP
135
 
 
136
 
/*
137
 
 * Handle incoming configuration
138
 
 * messages on the control channel.
139
 
 */
140
 
void
141
 
check_incoming_control_channel_dowork (struct context *c)
142
 
{
143
 
  const int len = tls_test_payload_len (c->c2.tls_multi);
144
 
  if (len)
145
 
    {
146
 
      struct gc_arena gc = gc_new ();
147
 
      struct buffer buf = alloc_buf_gc (len, &gc);
148
 
      if (tls_rec_payload (c->c2.tls_multi, &buf))
149
 
        {
150
 
          /* force null termination of message */
151
 
          buf_null_terminate (&buf);
152
 
 
153
 
          /* enforce character class restrictions */
154
 
          string_mod (BSTR (&buf), CC_PRINT, CC_CRLF, 0);
155
 
 
156
 
          if (buf_string_match_head_str (&buf, "AUTH_FAILED"))
157
 
            receive_auth_failed (c, &buf);
158
 
          else if (buf_string_match_head_str (&buf, "PUSH_"))
159
 
            incoming_push_message (c, &buf);
160
 
          else if (buf_string_match_head_str (&buf, "RESTART"))
161
 
            server_pushed_restart (c, &buf);
162
 
          else
163
 
            msg (D_PUSH_ERRORS, "WARNING: Received unknown control message: %s", BSTR (&buf));
164
 
        }
165
 
      else
166
 
        {
167
 
          msg (D_PUSH_ERRORS, "WARNING: Receive control message failed");
168
 
        }
169
 
 
170
 
      gc_free (&gc);
171
 
    }
172
 
}
173
 
 
174
 
/*
175
 
 * Periodically resend PUSH_REQUEST until PUSH message received
176
 
 */
177
 
void
178
 
check_push_request_dowork (struct context *c)
179
 
{
180
 
  send_push_request (c);
181
 
 
182
 
  /* if no response to first push_request, retry at 5 second intervals */
183
 
  event_timeout_modify_wakeup (&c->c2.push_request_interval, 5);
184
 
}
185
 
 
186
 
#endif /* P2MP */
187
 
 
188
 
/*
189
 
 * Things that need to happen immediately after connection initiation should go here.
190
 
 */
191
 
void
192
 
check_connection_established_dowork (struct context *c)
193
 
{
194
 
  if (event_timeout_trigger (&c->c2.wait_for_connect, &c->c2.timeval, ETT_DEFAULT))
195
 
    {
196
 
      if (CONNECTION_ESTABLISHED (c))
197
 
        {
198
 
#if P2MP
199
 
          /* if --pull was specified, send a push request to server */
200
 
          if (c->c2.tls_multi && c->options.pull)
201
 
            {
202
 
#ifdef ENABLE_MANAGEMENT
203
 
              if (management)
204
 
                {
205
 
                  management_set_state (management,
206
 
                                        OPENVPN_STATE_GET_CONFIG,
207
 
                                        NULL,
208
 
                                        0,
209
 
                                        0);
210
 
                }
211
 
#endif
212
 
              /* send push request in 1 sec */
213
 
              event_timeout_init (&c->c2.push_request_interval, 1, now);
214
 
              reset_coarse_timers (c);
215
 
            }
216
 
          else
217
 
#endif
218
 
            {
219
 
              do_up (c, false, 0);
220
 
            }
221
 
 
222
 
          event_timeout_clear (&c->c2.wait_for_connect);
223
 
        }
224
 
    }
225
 
}
226
 
 
227
 
/*
228
 
 * Send a string to remote over the TLS control channel.
229
 
 * Used for push/pull messages, passing username/password,
230
 
 * etc.
231
 
 */
232
 
bool
233
 
send_control_channel_string (struct context *c, const char *str, int msglevel)
234
 
{
235
 
#if defined(USE_CRYPTO) && defined(USE_SSL)
236
 
 
237
 
  if (c->c2.tls_multi) {
238
 
    bool stat;
239
 
 
240
 
    /* buffered cleartext write onto TLS control channel */
241
 
    stat = tls_send_payload (c->c2.tls_multi, (uint8_t*) str, strlen (str) + 1);
242
 
 
243
 
    /* reschedule tls_multi_process */
244
 
    interval_action (&c->c2.tmp_int);
245
 
    context_immediate_reschedule (c); /* ZERO-TIMEOUT */
246
 
 
247
 
    msg (msglevel, "SENT CONTROL [%s]: '%s' (status=%d)",
248
 
         tls_common_name (c->c2.tls_multi, false),
249
 
         str,
250
 
         (int) stat);
251
 
 
252
 
    return stat;
253
 
  }
254
 
#endif
255
 
  return true;
256
 
}
257
 
 
258
 
/*
259
 
 * Add routes.
260
 
 */
261
 
 
262
 
static void
263
 
check_add_routes_action (struct context *c, const bool errors)
264
 
{
265
 
  do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
266
 
  update_time ();
267
 
  event_timeout_clear (&c->c2.route_wakeup);
268
 
  event_timeout_clear (&c->c2.route_wakeup_expire);
269
 
  initialization_sequence_completed (c, errors ? ISC_ERRORS : 0); /* client/p2p --route-delay was defined */
270
 
}
271
 
 
272
 
void
273
 
check_add_routes_dowork (struct context *c)
274
 
{
275
 
  if (test_routes (c->c1.route_list, c->c1.tuntap))
276
 
    {
277
 
      check_add_routes_action (c, false);
278
 
    }
279
 
  else if (event_timeout_trigger (&c->c2.route_wakeup_expire, &c->c2.timeval, ETT_DEFAULT))
280
 
    {
281
 
      check_add_routes_action (c, true);
282
 
    }
283
 
  else
284
 
    {
285
 
      msg (D_ROUTE, "Route: Waiting for TUN/TAP interface to come up...");
286
 
      if (c->c1.tuntap)
287
 
        {
288
 
          if (!tun_standby (c->c1.tuntap))
289
 
            {
290
 
              c->sig->signal_received = SIGHUP;
291
 
              c->sig->signal_text = "ip-fail";
292
 
              c->persist.restart_sleep_seconds = 10;
293
 
#ifdef WIN32
294
 
              show_routes (M_INFO|M_NOPREFIX);
295
 
              show_adapters (M_INFO|M_NOPREFIX);
296
 
#endif
297
 
            }
298
 
        }
299
 
      update_time ();
300
 
      if (c->c2.route_wakeup.n != 1)
301
 
        event_timeout_init (&c->c2.route_wakeup, 1, now);
302
 
      event_timeout_reset (&c->c2.ping_rec_interval);
303
 
    }
304
 
}
305
 
 
306
 
/*
307
 
 * Should we exit due to inactivity timeout?
308
 
 */
309
 
void
310
 
check_inactivity_timeout_dowork (struct context *c)
311
 
{
312
 
  msg (M_INFO, "Inactivity timeout (--inactive), exiting");
313
 
  c->sig->signal_received = SIGTERM;
314
 
  c->sig->signal_text = "inactive";
315
 
}
316
 
 
317
 
#if P2MP
318
 
 
319
 
void
320
 
check_server_poll_timeout_dowork (struct context *c)
321
 
{
322
 
  event_timeout_reset (&c->c2.server_poll_interval);
323
 
  if (!tls_initial_packet_received (c->c2.tls_multi))
324
 
    {
325
 
      msg (M_INFO, "Server poll timeout, restarting");
326
 
      c->sig->signal_received = SIGUSR1;
327
 
      c->sig->signal_text = "server_poll";
328
 
      c->persist.restart_sleep_seconds = -1;
329
 
    }
330
 
}
331
 
 
332
 
/*
333
 
 * Schedule a signal n_seconds from now.
334
 
 */
335
 
void
336
 
schedule_exit (struct context *c, const int n_seconds, const int signal)
337
 
{
338
 
  tls_set_single_session (c->c2.tls_multi);
339
 
  update_time ();
340
 
  reset_coarse_timers (c);
341
 
  event_timeout_init (&c->c2.scheduled_exit, n_seconds, now);
342
 
  c->c2.scheduled_exit_signal = signal;
343
 
  msg (D_SCHED_EXIT, "Delayed exit in %d seconds", n_seconds);
344
 
}
345
 
 
346
 
/*
347
 
 * Scheduled exit?
348
 
 */
349
 
void
350
 
check_scheduled_exit_dowork (struct context *c)
351
 
{
352
 
  c->sig->signal_received = c->c2.scheduled_exit_signal;
353
 
  c->sig->signal_text = "delayed-exit";
354
 
}
355
 
 
356
 
#endif
357
 
 
358
 
/*
359
 
 * Should we write timer-triggered status file.
360
 
 */
361
 
void
362
 
check_status_file_dowork (struct context *c)
363
 
{
364
 
  if (c->c1.status_output)
365
 
    print_status (c, c->c1.status_output);
366
 
}
367
 
 
368
 
#ifdef ENABLE_FRAGMENT
369
 
/*
370
 
 * Should we deliver a datagram fragment to remote?
371
 
 */
372
 
void
373
 
check_fragment_dowork (struct context *c)
374
 
{
375
 
  struct link_socket_info *lsi = get_link_socket_info (c);
376
 
 
377
 
  /* OS MTU Hint? */
378
 
  if (lsi->mtu_changed && c->c2.ipv4_tun)
379
 
    {
380
 
      frame_adjust_path_mtu (&c->c2.frame_fragment, c->c2.link_socket->mtu,
381
 
                             c->options.ce.proto);
382
 
      lsi->mtu_changed = false;
383
 
    }
384
 
 
385
 
  if (fragment_outgoing_defined (c->c2.fragment))
386
 
    {
387
 
      if (!c->c2.to_link.len)
388
 
        {
389
 
          /* encrypt a fragment for output to TCP/UDP port */
390
 
          ASSERT (fragment_ready_to_send (c->c2.fragment, &c->c2.buf, &c->c2.frame_fragment));
391
 
          encrypt_sign (c, false);
392
 
        }
393
 
    }
394
 
 
395
 
  fragment_housekeeping (c->c2.fragment, &c->c2.frame_fragment, &c->c2.timeval);
396
 
}
397
 
#endif
398
 
 
399
 
/*
400
 
 * Buffer reallocation, for use with null encryption.
401
 
 */
402
 
static inline void
403
 
buffer_turnover (const uint8_t *orig_buf, struct buffer *dest_stub, struct buffer *src_stub, struct buffer *storage)
404
 
{
405
 
  if (orig_buf == src_stub->data && src_stub->data != storage->data)
406
 
    {
407
 
      buf_assign (storage, src_stub);
408
 
      *dest_stub = *storage;
409
 
    }
410
 
  else
411
 
    {
412
 
      *dest_stub = *src_stub;
413
 
    }
414
 
}
415
 
 
416
 
/*
417
 
 * Compress, fragment, encrypt and HMAC-sign an outgoing packet.
418
 
 * Input: c->c2.buf
419
 
 * Output: c->c2.to_link
420
 
 */
421
 
void
422
 
encrypt_sign (struct context *c, bool comp_frag)
423
 
{
424
 
  struct context_buffers *b = c->c2.buffers;
425
 
  const uint8_t *orig_buf = c->c2.buf.data;
426
 
 
427
 
#if P2MP_SERVER
428
 
  /*
429
 
   * Drop non-TLS outgoing packet if client-connect script/plugin
430
 
   * has not yet succeeded.
431
 
   */
432
 
  if (c->c2.context_auth != CAS_SUCCEEDED)
433
 
    c->c2.buf.len = 0;
434
 
#endif
435
 
 
436
 
  if (comp_frag)
437
 
    {
438
 
#ifdef USE_LZO
439
 
      /* Compress the packet. */
440
 
      if (lzo_defined (&c->c2.lzo_compwork))
441
 
        lzo_compress (&c->c2.buf, b->lzo_compress_buf, &c->c2.lzo_compwork, &c->c2.frame);
442
 
#endif
443
 
#ifdef ENABLE_FRAGMENT
444
 
      if (c->c2.fragment)
445
 
        fragment_outgoing (c->c2.fragment, &c->c2.buf, &c->c2.frame_fragment);
446
 
#endif
447
 
    }
448
 
 
449
 
#ifdef USE_CRYPTO
450
 
#ifdef USE_SSL
451
 
  /*
452
 
   * If TLS mode, get the key we will use to encrypt
453
 
   * the packet.
454
 
   */
455
 
  if (c->c2.tls_multi)
456
 
    {
457
 
      tls_pre_encrypt (c->c2.tls_multi, &c->c2.buf, &c->c2.crypto_options);
458
 
    }
459
 
#endif
460
 
 
461
 
  /*
462
 
   * Encrypt the packet and write an optional
463
 
   * HMAC signature.
464
 
   */
465
 
  openvpn_encrypt (&c->c2.buf, b->encrypt_buf, &c->c2.crypto_options, &c->c2.frame);
466
 
#endif
467
 
  /*
468
 
   * Get the address we will be sending the packet to.
469
 
   */
470
 
  link_socket_get_outgoing_addr (&c->c2.buf, get_link_socket_info (c),
471
 
                                 &c->c2.to_link_addr);
472
 
#ifdef USE_CRYPTO
473
 
#ifdef USE_SSL
474
 
  /*
475
 
   * In TLS mode, prepend the appropriate one-byte opcode
476
 
   * to the packet which identifies it as a data channel
477
 
   * packet and gives the low-permutation version of
478
 
   * the key-id to the recipient so it knows which
479
 
   * decrypt key to use.
480
 
   */
481
 
  if (c->c2.tls_multi)
482
 
    {
483
 
      tls_post_encrypt (c->c2.tls_multi, &c->c2.buf);
484
 
    }
485
 
#endif
486
 
#endif
487
 
 
488
 
  /* if null encryption, copy result to read_tun_buf */
489
 
  buffer_turnover (orig_buf, &c->c2.to_link, &c->c2.buf, &b->read_tun_buf);
490
 
}
491
 
 
492
 
/*
493
 
 * Coarse timers work to 1 second resolution.
494
 
 */
495
 
static void
496
 
process_coarse_timers (struct context *c)
497
 
{
498
 
#ifdef USE_CRYPTO
499
 
  /* flush current packet-id to file once per 60
500
 
     seconds if --replay-persist was specified */
501
 
  check_packet_id_persist_flush (c);
502
 
#endif
503
 
 
504
 
  /* should we update status file? */
505
 
  check_status_file (c);
506
 
 
507
 
  /* process connection establishment items */
508
 
  check_connection_established (c);
509
 
 
510
 
#if P2MP
511
 
  /* see if we should send a push_request in response to --pull */
512
 
  check_push_request (c);
513
 
#endif
514
 
 
515
 
#ifdef PLUGIN_PF
516
 
  pf_check_reload (c);
517
 
#endif
518
 
 
519
 
  /* process --route options */
520
 
  check_add_routes (c);
521
 
 
522
 
  /* possibly exit due to --inactive */
523
 
  check_inactivity_timeout (c);
524
 
  if (c->sig->signal_received)
525
 
    return;
526
 
 
527
 
  /* restart if ping not received */
528
 
  check_ping_restart (c);
529
 
  if (c->sig->signal_received)
530
 
    return;
531
 
 
532
 
#if P2MP
533
 
  check_server_poll_timeout (c);
534
 
  if (c->sig->signal_received)
535
 
    return;
536
 
 
537
 
  check_scheduled_exit (c);
538
 
  if (c->sig->signal_received)
539
 
    return;
540
 
#endif
541
 
 
542
 
#ifdef ENABLE_OCC
543
 
  /* Should we send an OCC_REQUEST message? */
544
 
  check_send_occ_req (c);
545
 
 
546
 
  /* Should we send an MTU load test? */
547
 
  check_send_occ_load_test (c);
548
 
 
549
 
  /* Should we send an OCC_EXIT message to remote? */
550
 
  if (c->c2.explicit_exit_notification_time_wait)
551
 
    process_explicit_exit_notification_timer_wakeup (c);
552
 
#endif
553
 
 
554
 
  /* Should we ping the remote? */
555
 
  check_ping_send (c);
556
 
}
557
 
 
558
 
static void
559
 
check_coarse_timers_dowork (struct context *c)
560
 
{
561
 
  const struct timeval save = c->c2.timeval;
562
 
  c->c2.timeval.tv_sec = BIG_TIMEOUT;
563
 
  c->c2.timeval.tv_usec = 0;
564
 
  process_coarse_timers (c);
565
 
  c->c2.coarse_timer_wakeup = now + c->c2.timeval.tv_sec; 
566
 
 
567
 
  dmsg (D_INTERVAL, "TIMER: coarse timer wakeup %d seconds", (int) c->c2.timeval.tv_sec);
568
 
 
569
 
  /* Is the coarse timeout NOT the earliest one? */
570
 
  if (c->c2.timeval.tv_sec > save.tv_sec)
571
 
    c->c2.timeval = save;
572
 
}
573
 
 
574
 
static inline void
575
 
check_coarse_timers (struct context *c)
576
 
{
577
 
  const time_t local_now = now;
578
 
  if (local_now >= c->c2.coarse_timer_wakeup)
579
 
    check_coarse_timers_dowork (c);
580
 
  else
581
 
    context_reschedule_sec (c, c->c2.coarse_timer_wakeup - local_now);
582
 
}
583
 
 
584
 
static void
585
 
check_timeout_random_component_dowork (struct context *c)
586
 
{
587
 
  const int update_interval = 10; /* seconds */
588
 
  c->c2.update_timeout_random_component = now + update_interval;
589
 
  c->c2.timeout_random_component.tv_usec = (time_t) get_random () & 0x0003FFFF;
590
 
  c->c2.timeout_random_component.tv_sec = 0;
591
 
 
592
 
  dmsg (D_INTERVAL, "RANDOM USEC=%d", (int) c->c2.timeout_random_component.tv_usec);
593
 
}
594
 
 
595
 
static inline void
596
 
check_timeout_random_component (struct context *c)
597
 
{
598
 
  if (now >= c->c2.update_timeout_random_component)
599
 
    check_timeout_random_component_dowork (c);
600
 
  if (c->c2.timeval.tv_sec >= 1)
601
 
    tv_add (&c->c2.timeval, &c->c2.timeout_random_component);
602
 
}
603
 
 
604
 
#ifdef ENABLE_SOCKS
605
 
 
606
 
/*
607
 
 * Handle addition and removal of the 10-byte Socks5 header
608
 
 * in UDP packets.
609
 
 */
610
 
 
611
 
static inline void
612
 
socks_postprocess_incoming_link (struct context *c)
613
 
{
614
 
  if (c->c2.link_socket->socks_proxy && c->c2.link_socket->info.proto == PROTO_UDPv4)
615
 
    socks_process_incoming_udp (&c->c2.buf, &c->c2.from);
616
 
}
617
 
 
618
 
static inline void
619
 
socks_preprocess_outgoing_link (struct context *c,
620
 
                                struct link_socket_actual **to_addr,
621
 
                                int *size_delta)
622
 
{
623
 
  if (c->c2.link_socket->socks_proxy && c->c2.link_socket->info.proto == PROTO_UDPv4)
624
 
    {
625
 
      *size_delta += socks_process_outgoing_udp (&c->c2.to_link, c->c2.to_link_addr);
626
 
      *to_addr = &c->c2.link_socket->socks_relay;
627
 
    }
628
 
}
629
 
 
630
 
/* undo effect of socks_preprocess_outgoing_link */
631
 
static inline void
632
 
link_socket_write_post_size_adjust (int *size,
633
 
                                    int size_delta,
634
 
                                    struct buffer *buf)
635
 
{
636
 
  if (size_delta > 0 && *size > size_delta)
637
 
    {
638
 
      *size -= size_delta;
639
 
      if (!buf_advance (buf, size_delta))
640
 
        *size = 0;
641
 
    }
642
 
}
643
 
#endif
644
 
 
645
 
/*
646
 
 * Output: c->c2.buf
647
 
 */
648
 
 
649
 
void
650
 
read_incoming_link (struct context *c)
651
 
{
652
 
  /*
653
 
   * Set up for recvfrom call to read datagram
654
 
   * sent to our TCP/UDP port.
655
 
   */
656
 
  int status;
657
 
 
658
 
  /*ASSERT (!c->c2.to_tun.len);*/
659
 
 
660
 
  perf_push (PERF_READ_IN_LINK);
661
 
 
662
 
  c->c2.buf = c->c2.buffers->read_link_buf;
663
 
  ASSERT (buf_init (&c->c2.buf, FRAME_HEADROOM_ADJ (&c->c2.frame, FRAME_HEADROOM_MARKER_READ_LINK)));
664
 
 
665
 
  status = link_socket_read (c->c2.link_socket,
666
 
                             &c->c2.buf,
667
 
                             MAX_RW_SIZE_LINK (&c->c2.frame),
668
 
                             &c->c2.from);
669
 
 
670
 
  if (socket_connection_reset (c->c2.link_socket, status))
671
 
    {
672
 
#if PORT_SHARE
673
 
      if (port_share && socket_foreign_protocol_detected (c->c2.link_socket))
674
 
        {
675
 
          const struct buffer *fbuf = socket_foreign_protocol_head (c->c2.link_socket);
676
 
          const int sd = socket_foreign_protocol_sd (c->c2.link_socket);
677
 
          port_share_redirect (port_share, fbuf, sd);
678
 
          c->sig->signal_received = SIGTERM;
679
 
          c->sig->signal_text = "port-share-redirect";
680
 
        }
681
 
      else
682
 
#endif
683
 
      {
684
 
        /* received a disconnect from a connection-oriented protocol */
685
 
        if (c->options.inetd)
686
 
          {
687
 
            c->sig->signal_received = SIGTERM;
688
 
            c->sig->signal_text = "connection-reset-inetd";
689
 
            msg (D_STREAM_ERRORS, "Connection reset, inetd/xinetd exit [%d]", status);
690
 
          }
691
 
        else
692
 
          {
693
 
#ifdef ENABLE_OCC
694
 
            if (event_timeout_defined(&c->c2.explicit_exit_notification_interval))
695
 
              {
696
 
                msg (D_STREAM_ERRORS, "Connection reset during exit notification period, ignoring [%d]", status);
697
 
                openvpn_sleep(1);
698
 
              }
699
 
            else
700
 
#endif
701
 
              {
702
 
                c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- TCP connection reset */
703
 
                c->sig->signal_text = "connection-reset";
704
 
                msg (D_STREAM_ERRORS, "Connection reset, restarting [%d]", status);
705
 
              }
706
 
          }
707
 
      }
708
 
      perf_pop ();
709
 
      return;
710
 
    }
711
 
 
712
 
  /* check recvfrom status */
713
 
  check_status (status, "read", c->c2.link_socket, NULL);
714
 
 
715
 
#ifdef ENABLE_SOCKS
716
 
  /* Remove socks header if applicable */
717
 
  socks_postprocess_incoming_link (c);
718
 
#endif
719
 
 
720
 
  perf_pop ();
721
 
}
722
 
 
723
 
/*
724
 
 * Input:  c->c2.buf
725
 
 * Output: c->c2.to_tun
726
 
 */
727
 
 
728
 
void
729
 
process_incoming_link (struct context *c)
730
 
{
731
 
  struct gc_arena gc = gc_new ();
732
 
  bool decrypt_status;
733
 
  struct link_socket_info *lsi = get_link_socket_info (c);
734
 
  const uint8_t *orig_buf = c->c2.buf.data;
735
 
 
736
 
  perf_push (PERF_PROC_IN_LINK);
737
 
 
738
 
  if (c->c2.buf.len > 0)
739
 
    {
740
 
      c->c2.link_read_bytes += c->c2.buf.len;
741
 
      link_read_bytes_global += c->c2.buf.len;
742
 
      c->c2.original_recv_size = c->c2.buf.len;
743
 
#ifdef ENABLE_MANAGEMENT
744
 
      if (management)
745
 
        {
746
 
          management_bytes_in (management, c->c2.buf.len);
747
 
#ifdef MANAGEMENT_DEF_AUTH
748
 
          management_bytes_server (management, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &c->c2.mda_context);
749
 
#endif
750
 
        }
751
 
#endif
752
 
    }
753
 
  else
754
 
    c->c2.original_recv_size = 0;
755
 
  
756
 
#ifdef ENABLE_DEBUG
757
 
  /* take action to corrupt packet if we are in gremlin test mode */
758
 
  if (c->options.gremlin) {
759
 
    if (!ask_gremlin (c->options.gremlin))
760
 
      c->c2.buf.len = 0;
761
 
    corrupt_gremlin (&c->c2.buf, c->options.gremlin);
762
 
  }
763
 
#endif
764
 
 
765
 
  /* log incoming packet */
766
 
#ifdef LOG_RW
767
 
  if (c->c2.log_rw && c->c2.buf.len > 0)
768
 
    fprintf (stderr, "R");
769
 
#endif
770
 
  msg (D_LINK_RW, "%s READ [%d] from %s: %s",
771
 
       proto2ascii (lsi->proto, true),
772
 
       BLEN (&c->c2.buf),
773
 
       print_link_socket_actual (&c->c2.from, &gc),
774
 
       PROTO_DUMP (&c->c2.buf, &gc));
775
 
 
776
 
  /*
777
 
   * Good, non-zero length packet received.
778
 
   * Commence multi-stage processing of packet,
779
 
   * such as authenticate, decrypt, decompress.
780
 
   * If any stage fails, it sets buf.len to 0 or -1,
781
 
   * telling downstream stages to ignore the packet.
782
 
   */
783
 
  if (c->c2.buf.len > 0)
784
 
    {
785
 
      if (!link_socket_verify_incoming_addr (&c->c2.buf, lsi, &c->c2.from))
786
 
        link_socket_bad_incoming_addr (&c->c2.buf, lsi, &c->c2.from);
787
 
 
788
 
#ifdef USE_CRYPTO
789
 
#ifdef USE_SSL
790
 
      if (c->c2.tls_multi)
791
 
        {
792
 
          /*
793
 
           * If tls_pre_decrypt returns true, it means the incoming
794
 
           * packet was a good TLS control channel packet.  If so, TLS code
795
 
           * will deal with the packet and set buf.len to 0 so downstream
796
 
           * stages ignore it.
797
 
           *
798
 
           * If the packet is a data channel packet, tls_pre_decrypt
799
 
           * will load crypto_options with the correct encryption key
800
 
           * and return false.
801
 
           */
802
 
          if (tls_pre_decrypt (c->c2.tls_multi, &c->c2.from, &c->c2.buf, &c->c2.crypto_options))
803
 
            {
804
 
              interval_action (&c->c2.tmp_int);
805
 
 
806
 
              /* reset packet received timer if TLS packet */
807
 
              if (c->options.ping_rec_timeout)
808
 
                event_timeout_reset (&c->c2.ping_rec_interval);
809
 
            }
810
 
        }
811
 
#if P2MP_SERVER
812
 
      /*
813
 
       * Drop non-TLS packet if client-connect script/plugin has not
814
 
       * yet succeeded.
815
 
       */
816
 
      if (c->c2.context_auth != CAS_SUCCEEDED)
817
 
        c->c2.buf.len = 0;
818
 
#endif
819
 
#endif /* USE_SSL */
820
 
 
821
 
      /* authenticate and decrypt the incoming packet */
822
 
      decrypt_status = openvpn_decrypt (&c->c2.buf, c->c2.buffers->decrypt_buf, &c->c2.crypto_options, &c->c2.frame);
823
 
 
824
 
      if (!decrypt_status && link_socket_connection_oriented (c->c2.link_socket))
825
 
        {
826
 
          /* decryption errors are fatal in TCP mode */
827
 
          c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- decryption error in TCP mode */
828
 
          c->sig->signal_text = "decryption-error";
829
 
          msg (D_STREAM_ERRORS, "Fatal decryption error (process_incoming_link), restarting");
830
 
          goto done;
831
 
        }
832
 
 
833
 
#endif /* USE_CRYPTO */
834
 
 
835
 
#ifdef ENABLE_FRAGMENT
836
 
      if (c->c2.fragment)
837
 
        fragment_incoming (c->c2.fragment, &c->c2.buf, &c->c2.frame_fragment);
838
 
#endif
839
 
 
840
 
#ifdef USE_LZO
841
 
      /* decompress the incoming packet */
842
 
      if (lzo_defined (&c->c2.lzo_compwork))
843
 
        lzo_decompress (&c->c2.buf, c->c2.buffers->lzo_decompress_buf, &c->c2.lzo_compwork, &c->c2.frame);
844
 
#endif
845
 
 
846
 
#ifdef PACKET_TRUNCATION_CHECK
847
 
      /* if (c->c2.buf.len > 1) --c->c2.buf.len; */
848
 
      ipv4_packet_size_verify (BPTR (&c->c2.buf),
849
 
                               BLEN (&c->c2.buf),
850
 
                               TUNNEL_TYPE (c->c1.tuntap),
851
 
                               "POST_DECRYPT",
852
 
                               &c->c2.n_trunc_post_decrypt);
853
 
#endif
854
 
 
855
 
      /*
856
 
       * Set our "official" outgoing address, since
857
 
       * if buf.len is non-zero, we know the packet
858
 
       * authenticated.  In TLS mode we do nothing
859
 
       * because TLS mode takes care of source address
860
 
       * authentication.
861
 
       *
862
 
       * Also, update the persisted version of our packet-id.
863
 
       */
864
 
      if (!TLS_MODE (c))
865
 
        link_socket_set_outgoing_addr (&c->c2.buf, lsi, &c->c2.from, NULL, c->c2.es);
866
 
 
867
 
      /* reset packet received timer */
868
 
      if (c->options.ping_rec_timeout && c->c2.buf.len > 0)
869
 
        event_timeout_reset (&c->c2.ping_rec_interval);
870
 
 
871
 
      /* increment authenticated receive byte count */
872
 
      if (c->c2.buf.len > 0)
873
 
        {
874
 
          c->c2.link_read_bytes_auth += c->c2.buf.len;
875
 
          c->c2.max_recv_size_local = max_int (c->c2.original_recv_size, c->c2.max_recv_size_local);
876
 
        }
877
 
 
878
 
      /* Did we just receive an openvpn ping packet? */
879
 
      if (is_ping_msg (&c->c2.buf))
880
 
        {
881
 
          dmsg (D_PING, "RECEIVED PING PACKET");
882
 
          c->c2.buf.len = 0; /* drop packet */
883
 
        }
884
 
 
885
 
#ifdef ENABLE_OCC
886
 
      /* Did we just receive an OCC packet? */
887
 
      if (is_occ_msg (&c->c2.buf))
888
 
        process_received_occ_msg (c);
889
 
#endif
890
 
 
891
 
      buffer_turnover (orig_buf, &c->c2.to_tun, &c->c2.buf, &c->c2.buffers->read_link_buf);
892
 
 
893
 
      /* to_tun defined + unopened tuntap can cause deadlock */
894
 
      if (!tuntap_defined (c->c1.tuntap))
895
 
        c->c2.to_tun.len = 0;
896
 
    }
897
 
  else
898
 
    {
899
 
      buf_reset (&c->c2.to_tun);
900
 
    }
901
 
 done:
902
 
  perf_pop ();
903
 
  gc_free (&gc);
904
 
}
905
 
 
906
 
/*
907
 
 * Output: c->c2.buf
908
 
 */
909
 
 
910
 
void
911
 
read_incoming_tun (struct context *c)
912
 
{
913
 
  /*
914
 
   * Setup for read() call on TUN/TAP device.
915
 
   */
916
 
  /*ASSERT (!c->c2.to_link.len);*/
917
 
 
918
 
  perf_push (PERF_READ_IN_TUN);
919
 
 
920
 
  c->c2.buf = c->c2.buffers->read_tun_buf;
921
 
#ifdef TUN_PASS_BUFFER
922
 
  read_tun_buffered (c->c1.tuntap, &c->c2.buf, MAX_RW_SIZE_TUN (&c->c2.frame));
923
 
#else
924
 
  ASSERT (buf_init (&c->c2.buf, FRAME_HEADROOM (&c->c2.frame)));
925
 
  ASSERT (buf_safe (&c->c2.buf, MAX_RW_SIZE_TUN (&c->c2.frame)));
926
 
  c->c2.buf.len = read_tun (c->c1.tuntap, BPTR (&c->c2.buf), MAX_RW_SIZE_TUN (&c->c2.frame));
927
 
#endif
928
 
 
929
 
#ifdef PACKET_TRUNCATION_CHECK
930
 
  ipv4_packet_size_verify (BPTR (&c->c2.buf),
931
 
                           BLEN (&c->c2.buf),
932
 
                           TUNNEL_TYPE (c->c1.tuntap),
933
 
                           "READ_TUN",
934
 
                           &c->c2.n_trunc_tun_read);
935
 
#endif
936
 
 
937
 
  /* Was TUN/TAP interface stopped? */
938
 
  if (tuntap_stop (c->c2.buf.len))
939
 
    {
940
 
      c->sig->signal_received = SIGTERM;
941
 
      c->sig->signal_text = "tun-stop";
942
 
      msg (M_INFO, "TUN/TAP interface has been stopped, exiting");
943
 
      perf_pop ();
944
 
      return;             
945
 
    }
946
 
 
947
 
  /* Check the status return from read() */
948
 
  check_status (c->c2.buf.len, "read from TUN/TAP", NULL, c->c1.tuntap);
949
 
 
950
 
  perf_pop ();
951
 
}
952
 
 
953
 
/*
954
 
 * Input:  c->c2.buf
955
 
 * Output: c->c2.to_link
956
 
 */
957
 
 
958
 
void
959
 
process_incoming_tun (struct context *c)
960
 
{
961
 
  struct gc_arena gc = gc_new ();
962
 
 
963
 
  perf_push (PERF_PROC_IN_TUN);
964
 
 
965
 
  if (c->c2.buf.len > 0)
966
 
    c->c2.tun_read_bytes += c->c2.buf.len;
967
 
 
968
 
#ifdef LOG_RW
969
 
  if (c->c2.log_rw && c->c2.buf.len > 0)
970
 
    fprintf (stderr, "r");
971
 
#endif
972
 
 
973
 
  /* Show packet content */
974
 
  dmsg (D_TUN_RW, "TUN READ [%d]", BLEN (&c->c2.buf));
975
 
 
976
 
  if (c->c2.buf.len > 0)
977
 
    {
978
 
      /*
979
 
       * The --passtos and --mssfix options require
980
 
       * us to examine the IPv4 header.
981
 
       */
982
 
      process_ipv4_header (c, PIPV4_PASSTOS|PIPV4_MSSFIX, &c->c2.buf);
983
 
 
984
 
#ifdef PACKET_TRUNCATION_CHECK
985
 
      /* if (c->c2.buf.len > 1) --c->c2.buf.len; */
986
 
      ipv4_packet_size_verify (BPTR (&c->c2.buf),
987
 
                               BLEN (&c->c2.buf),
988
 
                               TUNNEL_TYPE (c->c1.tuntap),
989
 
                               "PRE_ENCRYPT",
990
 
                               &c->c2.n_trunc_pre_encrypt);
991
 
#endif
992
 
 
993
 
      encrypt_sign (c, true);
994
 
    }
995
 
  else
996
 
    {
997
 
      buf_reset (&c->c2.to_link);
998
 
    }
999
 
  perf_pop ();
1000
 
  gc_free (&gc);
1001
 
}
1002
 
 
1003
 
void
1004
 
process_ipv4_header (struct context *c, unsigned int flags, struct buffer *buf)
1005
 
{
1006
 
  if (!c->options.mssfix)
1007
 
    flags &= ~PIPV4_MSSFIX;
1008
 
#if PASSTOS_CAPABILITY
1009
 
  if (!c->options.passtos)
1010
 
    flags &= ~PIPV4_PASSTOS;
1011
 
#endif
1012
 
  if (!c->options.route_gateway_via_dhcp || !route_list_default_gateway_needed (c->c1.route_list))
1013
 
    flags &= ~PIPV4_EXTRACT_DHCP_ROUTER;
1014
 
 
1015
 
  if (buf->len > 0)
1016
 
    {
1017
 
      /*
1018
 
       * The --passtos and --mssfix options require
1019
 
       * us to examine the IPv4 header.
1020
 
       */
1021
 
#if PASSTOS_CAPABILITY
1022
 
      if (flags & (PIPV4_PASSTOS|PIPV4_MSSFIX))
1023
 
#else
1024
 
      if (flags & PIPV4_MSSFIX)
1025
 
#endif
1026
 
        {
1027
 
          struct buffer ipbuf = *buf;
1028
 
          if (is_ipv4 (TUNNEL_TYPE (c->c1.tuntap), &ipbuf))
1029
 
            {
1030
 
#if PASSTOS_CAPABILITY
1031
 
              /* extract TOS from IP header */
1032
 
              if (flags & PIPV4_PASSTOS)
1033
 
                link_socket_extract_tos (c->c2.link_socket, &ipbuf);
1034
 
#endif
1035
 
                          
1036
 
              /* possibly alter the TCP MSS */
1037
 
              if (flags & PIPV4_MSSFIX)
1038
 
                mss_fixup (&ipbuf, MTU_TO_MSS (TUN_MTU_SIZE_DYNAMIC (&c->c2.frame)));
1039
 
 
1040
 
              /* possibly extract a DHCP router message */
1041
 
              if (flags & PIPV4_EXTRACT_DHCP_ROUTER)
1042
 
                {
1043
 
                  const in_addr_t dhcp_router = dhcp_extract_router_msg (&ipbuf);
1044
 
                  if (dhcp_router)
1045
 
                    route_list_add_default_gateway (c->c1.route_list, c->c2.es, dhcp_router);
1046
 
                }
1047
 
            }
1048
 
        }
1049
 
    }
1050
 
}
1051
 
 
1052
 
/*
1053
 
 * Input: c->c2.to_link
1054
 
 */
1055
 
 
1056
 
void
1057
 
process_outgoing_link (struct context *c)
1058
 
{
1059
 
  struct gc_arena gc = gc_new ();
1060
 
 
1061
 
  perf_push (PERF_PROC_OUT_LINK);
1062
 
 
1063
 
  if (c->c2.to_link.len > 0 && c->c2.to_link.len <= EXPANDED_SIZE (&c->c2.frame))
1064
 
    {
1065
 
      /*
1066
 
       * Setup for call to send/sendto which will send
1067
 
       * packet to remote over the TCP/UDP port.
1068
 
       */
1069
 
      int size = 0;
1070
 
      ASSERT (link_socket_actual_defined (c->c2.to_link_addr));
1071
 
 
1072
 
#ifdef ENABLE_DEBUG
1073
 
      /* In gremlin-test mode, we may choose to drop this packet */
1074
 
      if (!c->options.gremlin || ask_gremlin (c->options.gremlin))
1075
 
#endif
1076
 
        {
1077
 
          /*
1078
 
           * Let the traffic shaper know how many bytes
1079
 
           * we wrote.
1080
 
           */
1081
 
#ifdef HAVE_GETTIMEOFDAY
1082
 
          if (c->options.shaper)
1083
 
            shaper_wrote_bytes (&c->c2.shaper, BLEN (&c->c2.to_link)
1084
 
                                + datagram_overhead (c->options.ce.proto));
1085
 
#endif
1086
 
          /*
1087
 
           * Let the pinger know that we sent a packet.
1088
 
           */
1089
 
          if (c->options.ping_send_timeout)
1090
 
            event_timeout_reset (&c->c2.ping_send_interval);
1091
 
 
1092
 
#if PASSTOS_CAPABILITY
1093
 
          /* Set TOS */
1094
 
          link_socket_set_tos (c->c2.link_socket);
1095
 
#endif
1096
 
 
1097
 
          /* Log packet send */
1098
 
#ifdef LOG_RW
1099
 
          if (c->c2.log_rw)
1100
 
            fprintf (stderr, "W");
1101
 
#endif
1102
 
          msg (D_LINK_RW, "%s WRITE [%d] to %s: %s",
1103
 
               proto2ascii (c->c2.link_socket->info.proto, true),
1104
 
               BLEN (&c->c2.to_link),
1105
 
               print_link_socket_actual (c->c2.to_link_addr, &gc),
1106
 
               PROTO_DUMP (&c->c2.to_link, &gc));
1107
 
 
1108
 
          /* Packet send complexified by possible Socks5 usage */
1109
 
          {
1110
 
            struct link_socket_actual *to_addr = c->c2.to_link_addr;
1111
 
#ifdef ENABLE_SOCKS
1112
 
            int size_delta = 0;
1113
 
#endif
1114
 
 
1115
 
#ifdef ENABLE_SOCKS
1116
 
            /* If Socks5 over UDP, prepend header */
1117
 
            socks_preprocess_outgoing_link (c, &to_addr, &size_delta);
1118
 
#endif
1119
 
            /* Send packet */
1120
 
            size = link_socket_write (c->c2.link_socket,
1121
 
                                      &c->c2.to_link,
1122
 
                                      to_addr);
1123
 
 
1124
 
#ifdef ENABLE_SOCKS
1125
 
            /* Undo effect of prepend */
1126
 
            link_socket_write_post_size_adjust (&size, size_delta, &c->c2.to_link);
1127
 
#endif
1128
 
          }
1129
 
 
1130
 
          if (size > 0)
1131
 
            {
1132
 
              c->c2.max_send_size_local = max_int (size, c->c2.max_send_size_local);
1133
 
              c->c2.link_write_bytes += size;
1134
 
              link_write_bytes_global += size;
1135
 
#ifdef ENABLE_MANAGEMENT
1136
 
              if (management)
1137
 
                {
1138
 
                  management_bytes_out (management, size);
1139
 
#ifdef MANAGEMENT_DEF_AUTH
1140
 
                  management_bytes_server (management, &c->c2.link_read_bytes, &c->c2.link_write_bytes, &c->c2.mda_context);
1141
 
#endif
1142
 
                }
1143
 
#endif
1144
 
            }
1145
 
        }
1146
 
 
1147
 
      /* Check return status */
1148
 
      check_status (size, "write", c->c2.link_socket, NULL);
1149
 
 
1150
 
      if (size > 0)
1151
 
        {
1152
 
          /* Did we write a different size packet than we intended? */
1153
 
          if (size != BLEN (&c->c2.to_link))
1154
 
            msg (D_LINK_ERRORS,
1155
 
                 "TCP/UDP packet was truncated/expanded on write to %s (tried=%d,actual=%d)",
1156
 
                 print_link_socket_actual (c->c2.to_link_addr, &gc),
1157
 
                 BLEN (&c->c2.to_link),
1158
 
                 size);
1159
 
        }
1160
 
 
1161
 
      /* if not a ping/control message, indicate activity regarding --inactive parameter */
1162
 
      if (c->c2.buf.len > 0 )
1163
 
        register_activity (c, size);
1164
 
    }
1165
 
  else
1166
 
    {
1167
 
      if (c->c2.to_link.len > 0)
1168
 
        msg (D_LINK_ERRORS, "TCP/UDP packet too large on write to %s (tried=%d,max=%d)",
1169
 
             print_link_socket_actual (c->c2.to_link_addr, &gc),
1170
 
             c->c2.to_link.len,
1171
 
             EXPANDED_SIZE (&c->c2.frame));
1172
 
    }
1173
 
 
1174
 
  buf_reset (&c->c2.to_link);
1175
 
 
1176
 
  perf_pop ();
1177
 
  gc_free (&gc);
1178
 
}
1179
 
 
1180
 
/*
1181
 
 * Input: c->c2.to_tun
1182
 
 */
1183
 
 
1184
 
void
1185
 
process_outgoing_tun (struct context *c)
1186
 
{
1187
 
  struct gc_arena gc = gc_new ();
1188
 
 
1189
 
  /*
1190
 
   * Set up for write() call to TUN/TAP
1191
 
   * device.
1192
 
   */
1193
 
  if (c->c2.to_tun.len <= 0)
1194
 
    return;
1195
 
 
1196
 
  perf_push (PERF_PROC_OUT_TUN);
1197
 
 
1198
 
  /*
1199
 
   * The --mssfix option requires
1200
 
   * us to examine the IPv4 header.
1201
 
   */
1202
 
  process_ipv4_header (c, PIPV4_MSSFIX|PIPV4_EXTRACT_DHCP_ROUTER|PIPV4_OUTGOING, &c->c2.to_tun);
1203
 
 
1204
 
  if (c->c2.to_tun.len <= MAX_RW_SIZE_TUN (&c->c2.frame))
1205
 
    {
1206
 
      /*
1207
 
       * Write to TUN/TAP device.
1208
 
       */
1209
 
      int size;
1210
 
 
1211
 
#ifdef LOG_RW
1212
 
      if (c->c2.log_rw)
1213
 
        fprintf (stderr, "w");
1214
 
#endif
1215
 
      dmsg (D_TUN_RW, "TUN WRITE [%d]", BLEN (&c->c2.to_tun));
1216
 
 
1217
 
#ifdef PACKET_TRUNCATION_CHECK
1218
 
      ipv4_packet_size_verify (BPTR (&c->c2.to_tun),
1219
 
                               BLEN (&c->c2.to_tun),
1220
 
                               TUNNEL_TYPE (c->c1.tuntap),
1221
 
                               "WRITE_TUN",
1222
 
                               &c->c2.n_trunc_tun_write);
1223
 
#endif
1224
 
 
1225
 
#ifdef TUN_PASS_BUFFER
1226
 
      size = write_tun_buffered (c->c1.tuntap, &c->c2.to_tun);
1227
 
#else
1228
 
      size = write_tun (c->c1.tuntap, BPTR (&c->c2.to_tun), BLEN (&c->c2.to_tun));
1229
 
#endif
1230
 
 
1231
 
      if (size > 0)
1232
 
        c->c2.tun_write_bytes += size;
1233
 
      check_status (size, "write to TUN/TAP", NULL, c->c1.tuntap);
1234
 
 
1235
 
      /* check written packet size */
1236
 
      if (size > 0)
1237
 
        {
1238
 
          /* Did we write a different size packet than we intended? */
1239
 
          if (size != BLEN (&c->c2.to_tun))
1240
 
            msg (D_LINK_ERRORS,
1241
 
                 "TUN/TAP packet was destructively fragmented on write to %s (tried=%d,actual=%d)",
1242
 
                 c->c1.tuntap->actual_name,
1243
 
                 BLEN (&c->c2.to_tun),
1244
 
                 size);
1245
 
 
1246
 
          /* indicate activity regarding --inactive parameter */
1247
 
          register_activity (c, size);
1248
 
        }
1249
 
    }
1250
 
  else
1251
 
    {
1252
 
      /*
1253
 
       * This should never happen, probably indicates some kind
1254
 
       * of MTU mismatch.
1255
 
       */
1256
 
      msg (D_LINK_ERRORS, "tun packet too large on write (tried=%d,max=%d)",
1257
 
           c->c2.to_tun.len,
1258
 
           MAX_RW_SIZE_TUN (&c->c2.frame));
1259
 
    }
1260
 
 
1261
 
  buf_reset (&c->c2.to_tun);
1262
 
 
1263
 
  perf_pop ();
1264
 
  gc_free (&gc);
1265
 
}
1266
 
 
1267
 
void
1268
 
pre_select (struct context *c)
1269
 
{
1270
 
  /* make sure current time (now) is updated on function entry */
1271
 
 
1272
 
  /*
1273
 
   * Start with an effectively infinite timeout, then let it
1274
 
   * reduce to a timeout that reflects the component which
1275
 
   * needs the earliest service.
1276
 
   */
1277
 
  c->c2.timeval.tv_sec = BIG_TIMEOUT;
1278
 
  c->c2.timeval.tv_usec = 0;
1279
 
 
1280
 
#if defined(WIN32)
1281
 
  if (check_debug_level (D_TAP_WIN32_DEBUG))
1282
 
    {
1283
 
      c->c2.timeval.tv_sec = 1;
1284
 
      if (tuntap_defined (c->c1.tuntap))
1285
 
        tun_show_debug (c->c1.tuntap);
1286
 
    }
1287
 
#endif
1288
 
 
1289
 
  /* check coarse timers? */
1290
 
  check_coarse_timers (c);
1291
 
  if (c->sig->signal_received)
1292
 
    return;
1293
 
 
1294
 
  /* Does TLS need service? */
1295
 
  check_tls (c);
1296
 
 
1297
 
  /* In certain cases, TLS errors will require a restart */
1298
 
  check_tls_errors (c);
1299
 
  if (c->sig->signal_received)
1300
 
    return;
1301
 
 
1302
 
  /* check for incoming configuration info on the control channel */
1303
 
  check_incoming_control_channel (c);
1304
 
 
1305
 
#ifdef ENABLE_OCC
1306
 
  /* Should we send an OCC message? */
1307
 
  check_send_occ_msg (c);
1308
 
#endif
1309
 
 
1310
 
#ifdef ENABLE_FRAGMENT
1311
 
  /* Should we deliver a datagram fragment to remote? */
1312
 
  check_fragment (c);
1313
 
#endif
1314
 
 
1315
 
  /* Update random component of timeout */
1316
 
  check_timeout_random_component (c);
1317
 
}
1318
 
 
1319
 
/*
1320
 
 * Wait for I/O events.  Used for both TCP & UDP sockets
1321
 
 * in point-to-point mode and for UDP sockets in
1322
 
 * point-to-multipoint mode.
1323
 
 */
1324
 
 
1325
 
void
1326
 
io_wait_dowork (struct context *c, const unsigned int flags)
1327
 
{
1328
 
  unsigned int socket = 0;
1329
 
  unsigned int tuntap = 0;
1330
 
  struct event_set_return esr[4];
1331
 
 
1332
 
  /* These shifts all depend on EVENT_READ and EVENT_WRITE */
1333
 
  static int socket_shift = 0;     /* depends on SOCKET_READ and SOCKET_WRITE */
1334
 
  static int tun_shift = 2;        /* depends on TUN_READ and TUN_WRITE */
1335
 
  static int err_shift = 4;        /* depends on ES_ERROR */
1336
 
#ifdef ENABLE_MANAGEMENT
1337
 
  static int management_shift = 6; /* depends on MANAGEMENT_READ and MANAGEMENT_WRITE */
1338
 
#endif
1339
 
 
1340
 
  /*
1341
 
   * Decide what kind of events we want to wait for.
1342
 
   */
1343
 
  event_reset (c->c2.event_set);
1344
 
 
1345
 
  /*
1346
 
   * On win32 we use the keyboard or an event object as a source
1347
 
   * of asynchronous signals.
1348
 
   */
1349
 
  if (flags & IOW_WAIT_SIGNAL)
1350
 
    wait_signal (c->c2.event_set, (void*)&err_shift);
1351
 
 
1352
 
  /*
1353
 
   * If outgoing data (for TCP/UDP port) pending, wait for ready-to-send
1354
 
   * status from TCP/UDP port. Otherwise, wait for incoming data on
1355
 
   * TUN/TAP device.
1356
 
   */
1357
 
  if (flags & IOW_TO_LINK)
1358
 
    {
1359
 
      if (flags & IOW_SHAPER)
1360
 
        {
1361
 
          /*
1362
 
           * If sending this packet would put us over our traffic shaping
1363
 
           * quota, don't send -- instead compute the delay we must wait
1364
 
           * until it will be OK to send the packet.
1365
 
           */
1366
 
#ifdef HAVE_GETTIMEOFDAY
1367
 
          int delay = 0;
1368
 
 
1369
 
          /* set traffic shaping delay in microseconds */
1370
 
          if (c->options.shaper)
1371
 
            delay = max_int (delay, shaper_delay (&c->c2.shaper));
1372
 
          
1373
 
          if (delay < 1000)
1374
 
            {
1375
 
              socket |= EVENT_WRITE;
1376
 
            }
1377
 
          else
1378
 
            {
1379
 
              shaper_soonest_event (&c->c2.timeval, delay);
1380
 
            }
1381
 
#else /* HAVE_GETTIMEOFDAY */
1382
 
          socket |= EVENT_WRITE;
1383
 
#endif /* HAVE_GETTIMEOFDAY */
1384
 
        }
1385
 
      else
1386
 
        {
1387
 
          socket |= EVENT_WRITE;
1388
 
        }
1389
 
    }
1390
 
  else if (!((flags & IOW_FRAG) && TO_LINK_FRAG (c)))
1391
 
    {
1392
 
      if (flags & IOW_READ_TUN)
1393
 
        tuntap |= EVENT_READ;
1394
 
    }
1395
 
 
1396
 
  /*
1397
 
   * If outgoing data (for TUN/TAP device) pending, wait for ready-to-send status
1398
 
   * from device.  Otherwise, wait for incoming data on TCP/UDP port.
1399
 
   */
1400
 
  if (flags & IOW_TO_TUN)
1401
 
    {
1402
 
      tuntap |= EVENT_WRITE;
1403
 
    }
1404
 
  else
1405
 
    {
1406
 
      if (flags & IOW_READ_LINK)
1407
 
        socket |= EVENT_READ;
1408
 
    }
1409
 
 
1410
 
  /*
1411
 
   * outgoing bcast buffer waiting to be sent?
1412
 
   */
1413
 
  if (flags & IOW_MBUF)
1414
 
    socket |= EVENT_WRITE;
1415
 
 
1416
 
  /*
1417
 
   * Force wait on TUN input, even if also waiting on TCP/UDP output
1418
 
   */
1419
 
  if (flags & IOW_READ_TUN_FORCE)
1420
 
    tuntap |= EVENT_READ;
1421
 
 
1422
 
  /*
1423
 
   * Configure event wait based on socket, tuntap flags.
1424
 
   */
1425
 
  socket_set (c->c2.link_socket, c->c2.event_set, socket, (void*)&socket_shift, NULL);
1426
 
  tun_set (c->c1.tuntap, c->c2.event_set, tuntap, (void*)&tun_shift, NULL);
1427
 
 
1428
 
#ifdef ENABLE_MANAGEMENT
1429
 
  if (management)
1430
 
    management_socket_set (management, c->c2.event_set, (void*)&management_shift, NULL);
1431
 
#endif
1432
 
 
1433
 
  /*
1434
 
   * Possible scenarios:
1435
 
   *  (1) tcp/udp port has data available to read
1436
 
   *  (2) tcp/udp port is ready to accept more data to write
1437
 
   *  (3) tun dev has data available to read
1438
 
   *  (4) tun dev is ready to accept more data to write
1439
 
   *  (5) we received a signal (handler sets signal_received)
1440
 
   *  (6) timeout (tv) expired
1441
 
   */
1442
 
 
1443
 
  c->c2.event_set_status = ES_ERROR;
1444
 
 
1445
 
  if (!c->sig->signal_received)
1446
 
    {
1447
 
      if (!(flags & IOW_CHECK_RESIDUAL) || !socket_read_residual (c->c2.link_socket))
1448
 
        {
1449
 
          int status;
1450
 
 
1451
 
#ifdef ENABLE_DEBUG
1452
 
          if (check_debug_level (D_EVENT_WAIT))
1453
 
            show_wait_status (c);
1454
 
#endif
1455
 
 
1456
 
          /*
1457
 
           * Wait for something to happen.
1458
 
           */
1459
 
          status = event_wait (c->c2.event_set, &c->c2.timeval, esr, SIZE(esr));
1460
 
 
1461
 
          check_status (status, "event_wait", NULL, NULL);
1462
 
 
1463
 
          if (status > 0)
1464
 
            {
1465
 
              int i;
1466
 
              c->c2.event_set_status = 0;
1467
 
              for (i = 0; i < status; ++i)
1468
 
                {
1469
 
                  const struct event_set_return *e = &esr[i];
1470
 
                  c->c2.event_set_status |= ((e->rwflags & 3) << *((int*)e->arg));
1471
 
                }
1472
 
            }
1473
 
          else if (status == 0)
1474
 
            {
1475
 
              c->c2.event_set_status = ES_TIMEOUT;
1476
 
            }
1477
 
        }
1478
 
      else
1479
 
        {
1480
 
          c->c2.event_set_status = SOCKET_READ;
1481
 
        }
1482
 
    }
1483
 
 
1484
 
  /* 'now' should always be a reasonably up-to-date timestamp */
1485
 
  update_time ();
1486
 
 
1487
 
  /* set signal_received if a signal was received */
1488
 
  if (c->c2.event_set_status & ES_ERROR)
1489
 
    get_signal (&c->sig->signal_received);
1490
 
 
1491
 
  dmsg (D_EVENT_WAIT, "I/O WAIT status=0x%04x", c->c2.event_set_status);
1492
 
}
1493
 
 
1494
 
void
1495
 
process_io (struct context *c)
1496
 
{
1497
 
  const unsigned int status = c->c2.event_set_status;
1498
 
 
1499
 
#ifdef ENABLE_MANAGEMENT
1500
 
  if (status & (MANAGEMENT_READ|MANAGEMENT_WRITE))
1501
 
    {
1502
 
      ASSERT (management);
1503
 
      management_io (management);
1504
 
    }
1505
 
#endif
1506
 
 
1507
 
  /* TCP/UDP port ready to accept write */
1508
 
  if (status & SOCKET_WRITE)
1509
 
    {
1510
 
      process_outgoing_link (c);
1511
 
    }
1512
 
  /* TUN device ready to accept write */
1513
 
  else if (status & TUN_WRITE)
1514
 
    {
1515
 
      process_outgoing_tun (c);
1516
 
    }
1517
 
  /* Incoming data on TCP/UDP port */
1518
 
  else if (status & SOCKET_READ)
1519
 
    {
1520
 
      read_incoming_link (c);
1521
 
      if (!IS_SIG (c))
1522
 
        process_incoming_link (c);
1523
 
    }
1524
 
  /* Incoming data on TUN device */
1525
 
  else if (status & TUN_READ)
1526
 
    {
1527
 
      read_incoming_tun (c);
1528
 
      if (!IS_SIG (c))
1529
 
        process_incoming_tun (c);
1530
 
    }
1531
 
}