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
8
* Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
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.
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.
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
39
#include "forward-inline.h"
40
#include "occ-inline.h"
41
#include "ping-inline.h"
43
counter_type link_read_bytes_global; /* GLOBAL */
44
counter_type link_write_bytes_global; /* GLOBAL */
46
/* show event wait debugging info */
51
wait_status_string (struct context *c, struct gc_arena *gc)
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));
64
show_wait_status (struct context *c)
66
struct gc_arena gc = gc_new ();
67
dmsg (D_EVENT_WAIT, "%s", wait_status_string (c, &gc));
74
* In TLS mode, let TLS level respond to any control-channel
75
* packets which were received, or prepare any packets for
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.
83
#if defined(USE_CRYPTO) && defined(USE_SSL)
85
check_tls_dowork (struct context *c)
87
interval_t wakeup = BIG_TIMEOUT;
89
if (interval_test (&c->c2.tmp_int))
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)
97
interval_action (&c->c2.tmp_int);
99
else if (tmp_status == TLSMP_KILL)
101
c->sig->signal_received = SIGTERM;
102
c->sig->signal_text = "auth-control-exit";
105
interval_future_trigger (&c->c2.tmp_int, wakeup);
108
interval_schedule_wakeup (&c->c2.tmp_int, &wakeup);
111
context_reschedule_sec (c, wakeup);
115
#if defined(USE_CRYPTO) && defined(USE_SSL)
118
check_tls_errors_co (struct context *c)
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";
126
check_tls_errors_nco (struct context *c)
128
c->sig->signal_received = c->c2.tls_exit_signal; /* SOFT-SIGUSR1 -- TLS error */
129
c->sig->signal_text = "tls-error";
137
* Handle incoming configuration
138
* messages on the control channel.
141
check_incoming_control_channel_dowork (struct context *c)
143
const int len = tls_test_payload_len (c->c2.tls_multi);
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))
150
/* force null termination of message */
151
buf_null_terminate (&buf);
153
/* enforce character class restrictions */
154
string_mod (BSTR (&buf), CC_PRINT, CC_CRLF, 0);
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);
163
msg (D_PUSH_ERRORS, "WARNING: Received unknown control message: %s", BSTR (&buf));
167
msg (D_PUSH_ERRORS, "WARNING: Receive control message failed");
175
* Periodically resend PUSH_REQUEST until PUSH message received
178
check_push_request_dowork (struct context *c)
180
send_push_request (c);
182
/* if no response to first push_request, retry at 5 second intervals */
183
event_timeout_modify_wakeup (&c->c2.push_request_interval, 5);
189
* Things that need to happen immediately after connection initiation should go here.
192
check_connection_established_dowork (struct context *c)
194
if (event_timeout_trigger (&c->c2.wait_for_connect, &c->c2.timeval, ETT_DEFAULT))
196
if (CONNECTION_ESTABLISHED (c))
199
/* if --pull was specified, send a push request to server */
200
if (c->c2.tls_multi && c->options.pull)
202
#ifdef ENABLE_MANAGEMENT
205
management_set_state (management,
206
OPENVPN_STATE_GET_CONFIG,
212
/* send push request in 1 sec */
213
event_timeout_init (&c->c2.push_request_interval, 1, now);
214
reset_coarse_timers (c);
222
event_timeout_clear (&c->c2.wait_for_connect);
228
* Send a string to remote over the TLS control channel.
229
* Used for push/pull messages, passing username/password,
233
send_control_channel_string (struct context *c, const char *str, int msglevel)
235
#if defined(USE_CRYPTO) && defined(USE_SSL)
237
if (c->c2.tls_multi) {
240
/* buffered cleartext write onto TLS control channel */
241
stat = tls_send_payload (c->c2.tls_multi, (uint8_t*) str, strlen (str) + 1);
243
/* reschedule tls_multi_process */
244
interval_action (&c->c2.tmp_int);
245
context_immediate_reschedule (c); /* ZERO-TIMEOUT */
247
msg (msglevel, "SENT CONTROL [%s]: '%s' (status=%d)",
248
tls_common_name (c->c2.tls_multi, false),
263
check_add_routes_action (struct context *c, const bool errors)
265
do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
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 */
273
check_add_routes_dowork (struct context *c)
275
if (test_routes (c->c1.route_list, c->c1.tuntap))
277
check_add_routes_action (c, false);
279
else if (event_timeout_trigger (&c->c2.route_wakeup_expire, &c->c2.timeval, ETT_DEFAULT))
281
check_add_routes_action (c, true);
285
msg (D_ROUTE, "Route: Waiting for TUN/TAP interface to come up...");
288
if (!tun_standby (c->c1.tuntap))
290
c->sig->signal_received = SIGHUP;
291
c->sig->signal_text = "ip-fail";
292
c->persist.restart_sleep_seconds = 10;
294
show_routes (M_INFO|M_NOPREFIX);
295
show_adapters (M_INFO|M_NOPREFIX);
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);
307
* Should we exit due to inactivity timeout?
310
check_inactivity_timeout_dowork (struct context *c)
312
msg (M_INFO, "Inactivity timeout (--inactive), exiting");
313
c->sig->signal_received = SIGTERM;
314
c->sig->signal_text = "inactive";
320
check_server_poll_timeout_dowork (struct context *c)
322
event_timeout_reset (&c->c2.server_poll_interval);
323
if (!tls_initial_packet_received (c->c2.tls_multi))
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;
333
* Schedule a signal n_seconds from now.
336
schedule_exit (struct context *c, const int n_seconds, const int signal)
338
tls_set_single_session (c->c2.tls_multi);
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);
350
check_scheduled_exit_dowork (struct context *c)
352
c->sig->signal_received = c->c2.scheduled_exit_signal;
353
c->sig->signal_text = "delayed-exit";
359
* Should we write timer-triggered status file.
362
check_status_file_dowork (struct context *c)
364
if (c->c1.status_output)
365
print_status (c, c->c1.status_output);
368
#ifdef ENABLE_FRAGMENT
370
* Should we deliver a datagram fragment to remote?
373
check_fragment_dowork (struct context *c)
375
struct link_socket_info *lsi = get_link_socket_info (c);
378
if (lsi->mtu_changed && c->c2.ipv4_tun)
380
frame_adjust_path_mtu (&c->c2.frame_fragment, c->c2.link_socket->mtu,
381
c->options.ce.proto);
382
lsi->mtu_changed = false;
385
if (fragment_outgoing_defined (c->c2.fragment))
387
if (!c->c2.to_link.len)
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);
395
fragment_housekeeping (c->c2.fragment, &c->c2.frame_fragment, &c->c2.timeval);
400
* Buffer reallocation, for use with null encryption.
403
buffer_turnover (const uint8_t *orig_buf, struct buffer *dest_stub, struct buffer *src_stub, struct buffer *storage)
405
if (orig_buf == src_stub->data && src_stub->data != storage->data)
407
buf_assign (storage, src_stub);
408
*dest_stub = *storage;
412
*dest_stub = *src_stub;
417
* Compress, fragment, encrypt and HMAC-sign an outgoing packet.
419
* Output: c->c2.to_link
422
encrypt_sign (struct context *c, bool comp_frag)
424
struct context_buffers *b = c->c2.buffers;
425
const uint8_t *orig_buf = c->c2.buf.data;
429
* Drop non-TLS outgoing packet if client-connect script/plugin
430
* has not yet succeeded.
432
if (c->c2.context_auth != CAS_SUCCEEDED)
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);
443
#ifdef ENABLE_FRAGMENT
445
fragment_outgoing (c->c2.fragment, &c->c2.buf, &c->c2.frame_fragment);
452
* If TLS mode, get the key we will use to encrypt
457
tls_pre_encrypt (c->c2.tls_multi, &c->c2.buf, &c->c2.crypto_options);
462
* Encrypt the packet and write an optional
465
openvpn_encrypt (&c->c2.buf, b->encrypt_buf, &c->c2.crypto_options, &c->c2.frame);
468
* Get the address we will be sending the packet to.
470
link_socket_get_outgoing_addr (&c->c2.buf, get_link_socket_info (c),
471
&c->c2.to_link_addr);
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.
483
tls_post_encrypt (c->c2.tls_multi, &c->c2.buf);
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);
493
* Coarse timers work to 1 second resolution.
496
process_coarse_timers (struct context *c)
499
/* flush current packet-id to file once per 60
500
seconds if --replay-persist was specified */
501
check_packet_id_persist_flush (c);
504
/* should we update status file? */
505
check_status_file (c);
507
/* process connection establishment items */
508
check_connection_established (c);
511
/* see if we should send a push_request in response to --pull */
512
check_push_request (c);
519
/* process --route options */
520
check_add_routes (c);
522
/* possibly exit due to --inactive */
523
check_inactivity_timeout (c);
524
if (c->sig->signal_received)
527
/* restart if ping not received */
528
check_ping_restart (c);
529
if (c->sig->signal_received)
533
check_server_poll_timeout (c);
534
if (c->sig->signal_received)
537
check_scheduled_exit (c);
538
if (c->sig->signal_received)
543
/* Should we send an OCC_REQUEST message? */
544
check_send_occ_req (c);
546
/* Should we send an MTU load test? */
547
check_send_occ_load_test (c);
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);
554
/* Should we ping the remote? */
559
check_coarse_timers_dowork (struct context *c)
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;
567
dmsg (D_INTERVAL, "TIMER: coarse timer wakeup %d seconds", (int) c->c2.timeval.tv_sec);
569
/* Is the coarse timeout NOT the earliest one? */
570
if (c->c2.timeval.tv_sec > save.tv_sec)
571
c->c2.timeval = save;
575
check_coarse_timers (struct context *c)
577
const time_t local_now = now;
578
if (local_now >= c->c2.coarse_timer_wakeup)
579
check_coarse_timers_dowork (c);
581
context_reschedule_sec (c, c->c2.coarse_timer_wakeup - local_now);
585
check_timeout_random_component_dowork (struct context *c)
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;
592
dmsg (D_INTERVAL, "RANDOM USEC=%d", (int) c->c2.timeout_random_component.tv_usec);
596
check_timeout_random_component (struct context *c)
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);
607
* Handle addition and removal of the 10-byte Socks5 header
612
socks_postprocess_incoming_link (struct context *c)
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);
619
socks_preprocess_outgoing_link (struct context *c,
620
struct link_socket_actual **to_addr,
623
if (c->c2.link_socket->socks_proxy && c->c2.link_socket->info.proto == PROTO_UDPv4)
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;
630
/* undo effect of socks_preprocess_outgoing_link */
632
link_socket_write_post_size_adjust (int *size,
636
if (size_delta > 0 && *size > size_delta)
639
if (!buf_advance (buf, size_delta))
650
read_incoming_link (struct context *c)
653
* Set up for recvfrom call to read datagram
654
* sent to our TCP/UDP port.
658
/*ASSERT (!c->c2.to_tun.len);*/
660
perf_push (PERF_READ_IN_LINK);
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)));
665
status = link_socket_read (c->c2.link_socket,
667
MAX_RW_SIZE_LINK (&c->c2.frame),
670
if (socket_connection_reset (c->c2.link_socket, status))
673
if (port_share && socket_foreign_protocol_detected (c->c2.link_socket))
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";
684
/* received a disconnect from a connection-oriented protocol */
685
if (c->options.inetd)
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);
694
if (event_timeout_defined(&c->c2.explicit_exit_notification_interval))
696
msg (D_STREAM_ERRORS, "Connection reset during exit notification period, ignoring [%d]", status);
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);
712
/* check recvfrom status */
713
check_status (status, "read", c->c2.link_socket, NULL);
716
/* Remove socks header if applicable */
717
socks_postprocess_incoming_link (c);
725
* Output: c->c2.to_tun
729
process_incoming_link (struct context *c)
731
struct gc_arena gc = gc_new ();
733
struct link_socket_info *lsi = get_link_socket_info (c);
734
const uint8_t *orig_buf = c->c2.buf.data;
736
perf_push (PERF_PROC_IN_LINK);
738
if (c->c2.buf.len > 0)
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
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);
754
c->c2.original_recv_size = 0;
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))
761
corrupt_gremlin (&c->c2.buf, c->options.gremlin);
765
/* log incoming packet */
767
if (c->c2.log_rw && c->c2.buf.len > 0)
768
fprintf (stderr, "R");
770
msg (D_LINK_RW, "%s READ [%d] from %s: %s",
771
proto2ascii (lsi->proto, true),
773
print_link_socket_actual (&c->c2.from, &gc),
774
PROTO_DUMP (&c->c2.buf, &gc));
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.
783
if (c->c2.buf.len > 0)
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);
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
798
* If the packet is a data channel packet, tls_pre_decrypt
799
* will load crypto_options with the correct encryption key
802
if (tls_pre_decrypt (c->c2.tls_multi, &c->c2.from, &c->c2.buf, &c->c2.crypto_options))
804
interval_action (&c->c2.tmp_int);
806
/* reset packet received timer if TLS packet */
807
if (c->options.ping_rec_timeout)
808
event_timeout_reset (&c->c2.ping_rec_interval);
813
* Drop non-TLS packet if client-connect script/plugin has not
816
if (c->c2.context_auth != CAS_SUCCEEDED)
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);
824
if (!decrypt_status && link_socket_connection_oriented (c->c2.link_socket))
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");
833
#endif /* USE_CRYPTO */
835
#ifdef ENABLE_FRAGMENT
837
fragment_incoming (c->c2.fragment, &c->c2.buf, &c->c2.frame_fragment);
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);
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),
850
TUNNEL_TYPE (c->c1.tuntap),
852
&c->c2.n_trunc_post_decrypt);
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
862
* Also, update the persisted version of our packet-id.
865
link_socket_set_outgoing_addr (&c->c2.buf, lsi, &c->c2.from, NULL, c->c2.es);
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);
871
/* increment authenticated receive byte count */
872
if (c->c2.buf.len > 0)
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);
878
/* Did we just receive an openvpn ping packet? */
879
if (is_ping_msg (&c->c2.buf))
881
dmsg (D_PING, "RECEIVED PING PACKET");
882
c->c2.buf.len = 0; /* drop packet */
886
/* Did we just receive an OCC packet? */
887
if (is_occ_msg (&c->c2.buf))
888
process_received_occ_msg (c);
891
buffer_turnover (orig_buf, &c->c2.to_tun, &c->c2.buf, &c->c2.buffers->read_link_buf);
893
/* to_tun defined + unopened tuntap can cause deadlock */
894
if (!tuntap_defined (c->c1.tuntap))
895
c->c2.to_tun.len = 0;
899
buf_reset (&c->c2.to_tun);
911
read_incoming_tun (struct context *c)
914
* Setup for read() call on TUN/TAP device.
916
/*ASSERT (!c->c2.to_link.len);*/
918
perf_push (PERF_READ_IN_TUN);
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));
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));
929
#ifdef PACKET_TRUNCATION_CHECK
930
ipv4_packet_size_verify (BPTR (&c->c2.buf),
932
TUNNEL_TYPE (c->c1.tuntap),
934
&c->c2.n_trunc_tun_read);
937
/* Was TUN/TAP interface stopped? */
938
if (tuntap_stop (c->c2.buf.len))
940
c->sig->signal_received = SIGTERM;
941
c->sig->signal_text = "tun-stop";
942
msg (M_INFO, "TUN/TAP interface has been stopped, exiting");
947
/* Check the status return from read() */
948
check_status (c->c2.buf.len, "read from TUN/TAP", NULL, c->c1.tuntap);
955
* Output: c->c2.to_link
959
process_incoming_tun (struct context *c)
961
struct gc_arena gc = gc_new ();
963
perf_push (PERF_PROC_IN_TUN);
965
if (c->c2.buf.len > 0)
966
c->c2.tun_read_bytes += c->c2.buf.len;
969
if (c->c2.log_rw && c->c2.buf.len > 0)
970
fprintf (stderr, "r");
973
/* Show packet content */
974
dmsg (D_TUN_RW, "TUN READ [%d]", BLEN (&c->c2.buf));
976
if (c->c2.buf.len > 0)
979
* The --passtos and --mssfix options require
980
* us to examine the IPv4 header.
982
process_ipv4_header (c, PIPV4_PASSTOS|PIPV4_MSSFIX, &c->c2.buf);
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),
988
TUNNEL_TYPE (c->c1.tuntap),
990
&c->c2.n_trunc_pre_encrypt);
993
encrypt_sign (c, true);
997
buf_reset (&c->c2.to_link);
1004
process_ipv4_header (struct context *c, unsigned int flags, struct buffer *buf)
1006
if (!c->options.mssfix)
1007
flags &= ~PIPV4_MSSFIX;
1008
#if PASSTOS_CAPABILITY
1009
if (!c->options.passtos)
1010
flags &= ~PIPV4_PASSTOS;
1012
if (!c->options.route_gateway_via_dhcp || !route_list_default_gateway_needed (c->c1.route_list))
1013
flags &= ~PIPV4_EXTRACT_DHCP_ROUTER;
1018
* The --passtos and --mssfix options require
1019
* us to examine the IPv4 header.
1021
#if PASSTOS_CAPABILITY
1022
if (flags & (PIPV4_PASSTOS|PIPV4_MSSFIX))
1024
if (flags & PIPV4_MSSFIX)
1027
struct buffer ipbuf = *buf;
1028
if (is_ipv4 (TUNNEL_TYPE (c->c1.tuntap), &ipbuf))
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);
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)));
1040
/* possibly extract a DHCP router message */
1041
if (flags & PIPV4_EXTRACT_DHCP_ROUTER)
1043
const in_addr_t dhcp_router = dhcp_extract_router_msg (&ipbuf);
1045
route_list_add_default_gateway (c->c1.route_list, c->c2.es, dhcp_router);
1053
* Input: c->c2.to_link
1057
process_outgoing_link (struct context *c)
1059
struct gc_arena gc = gc_new ();
1061
perf_push (PERF_PROC_OUT_LINK);
1063
if (c->c2.to_link.len > 0 && c->c2.to_link.len <= EXPANDED_SIZE (&c->c2.frame))
1066
* Setup for call to send/sendto which will send
1067
* packet to remote over the TCP/UDP port.
1070
ASSERT (link_socket_actual_defined (c->c2.to_link_addr));
1073
/* In gremlin-test mode, we may choose to drop this packet */
1074
if (!c->options.gremlin || ask_gremlin (c->options.gremlin))
1078
* Let the traffic shaper know how many bytes
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));
1087
* Let the pinger know that we sent a packet.
1089
if (c->options.ping_send_timeout)
1090
event_timeout_reset (&c->c2.ping_send_interval);
1092
#if PASSTOS_CAPABILITY
1094
link_socket_set_tos (c->c2.link_socket);
1097
/* Log packet send */
1100
fprintf (stderr, "W");
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));
1108
/* Packet send complexified by possible Socks5 usage */
1110
struct link_socket_actual *to_addr = c->c2.to_link_addr;
1116
/* If Socks5 over UDP, prepend header */
1117
socks_preprocess_outgoing_link (c, &to_addr, &size_delta);
1120
size = link_socket_write (c->c2.link_socket,
1125
/* Undo effect of prepend */
1126
link_socket_write_post_size_adjust (&size, size_delta, &c->c2.to_link);
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
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);
1147
/* Check return status */
1148
check_status (size, "write", c->c2.link_socket, NULL);
1152
/* Did we write a different size packet than we intended? */
1153
if (size != BLEN (&c->c2.to_link))
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),
1161
/* if not a ping/control message, indicate activity regarding --inactive parameter */
1162
if (c->c2.buf.len > 0 )
1163
register_activity (c, size);
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),
1171
EXPANDED_SIZE (&c->c2.frame));
1174
buf_reset (&c->c2.to_link);
1181
* Input: c->c2.to_tun
1185
process_outgoing_tun (struct context *c)
1187
struct gc_arena gc = gc_new ();
1190
* Set up for write() call to TUN/TAP
1193
if (c->c2.to_tun.len <= 0)
1196
perf_push (PERF_PROC_OUT_TUN);
1199
* The --mssfix option requires
1200
* us to examine the IPv4 header.
1202
process_ipv4_header (c, PIPV4_MSSFIX|PIPV4_EXTRACT_DHCP_ROUTER|PIPV4_OUTGOING, &c->c2.to_tun);
1204
if (c->c2.to_tun.len <= MAX_RW_SIZE_TUN (&c->c2.frame))
1207
* Write to TUN/TAP device.
1213
fprintf (stderr, "w");
1215
dmsg (D_TUN_RW, "TUN WRITE [%d]", BLEN (&c->c2.to_tun));
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),
1222
&c->c2.n_trunc_tun_write);
1225
#ifdef TUN_PASS_BUFFER
1226
size = write_tun_buffered (c->c1.tuntap, &c->c2.to_tun);
1228
size = write_tun (c->c1.tuntap, BPTR (&c->c2.to_tun), BLEN (&c->c2.to_tun));
1232
c->c2.tun_write_bytes += size;
1233
check_status (size, "write to TUN/TAP", NULL, c->c1.tuntap);
1235
/* check written packet size */
1238
/* Did we write a different size packet than we intended? */
1239
if (size != BLEN (&c->c2.to_tun))
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),
1246
/* indicate activity regarding --inactive parameter */
1247
register_activity (c, size);
1253
* This should never happen, probably indicates some kind
1256
msg (D_LINK_ERRORS, "tun packet too large on write (tried=%d,max=%d)",
1258
MAX_RW_SIZE_TUN (&c->c2.frame));
1261
buf_reset (&c->c2.to_tun);
1268
pre_select (struct context *c)
1270
/* make sure current time (now) is updated on function entry */
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.
1277
c->c2.timeval.tv_sec = BIG_TIMEOUT;
1278
c->c2.timeval.tv_usec = 0;
1281
if (check_debug_level (D_TAP_WIN32_DEBUG))
1283
c->c2.timeval.tv_sec = 1;
1284
if (tuntap_defined (c->c1.tuntap))
1285
tun_show_debug (c->c1.tuntap);
1289
/* check coarse timers? */
1290
check_coarse_timers (c);
1291
if (c->sig->signal_received)
1294
/* Does TLS need service? */
1297
/* In certain cases, TLS errors will require a restart */
1298
check_tls_errors (c);
1299
if (c->sig->signal_received)
1302
/* check for incoming configuration info on the control channel */
1303
check_incoming_control_channel (c);
1306
/* Should we send an OCC message? */
1307
check_send_occ_msg (c);
1310
#ifdef ENABLE_FRAGMENT
1311
/* Should we deliver a datagram fragment to remote? */
1315
/* Update random component of timeout */
1316
check_timeout_random_component (c);
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.
1326
io_wait_dowork (struct context *c, const unsigned int flags)
1328
unsigned int socket = 0;
1329
unsigned int tuntap = 0;
1330
struct event_set_return esr[4];
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 */
1341
* Decide what kind of events we want to wait for.
1343
event_reset (c->c2.event_set);
1346
* On win32 we use the keyboard or an event object as a source
1347
* of asynchronous signals.
1349
if (flags & IOW_WAIT_SIGNAL)
1350
wait_signal (c->c2.event_set, (void*)&err_shift);
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
1357
if (flags & IOW_TO_LINK)
1359
if (flags & IOW_SHAPER)
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.
1366
#ifdef HAVE_GETTIMEOFDAY
1369
/* set traffic shaping delay in microseconds */
1370
if (c->options.shaper)
1371
delay = max_int (delay, shaper_delay (&c->c2.shaper));
1375
socket |= EVENT_WRITE;
1379
shaper_soonest_event (&c->c2.timeval, delay);
1381
#else /* HAVE_GETTIMEOFDAY */
1382
socket |= EVENT_WRITE;
1383
#endif /* HAVE_GETTIMEOFDAY */
1387
socket |= EVENT_WRITE;
1390
else if (!((flags & IOW_FRAG) && TO_LINK_FRAG (c)))
1392
if (flags & IOW_READ_TUN)
1393
tuntap |= EVENT_READ;
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.
1400
if (flags & IOW_TO_TUN)
1402
tuntap |= EVENT_WRITE;
1406
if (flags & IOW_READ_LINK)
1407
socket |= EVENT_READ;
1411
* outgoing bcast buffer waiting to be sent?
1413
if (flags & IOW_MBUF)
1414
socket |= EVENT_WRITE;
1417
* Force wait on TUN input, even if also waiting on TCP/UDP output
1419
if (flags & IOW_READ_TUN_FORCE)
1420
tuntap |= EVENT_READ;
1423
* Configure event wait based on socket, tuntap flags.
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);
1428
#ifdef ENABLE_MANAGEMENT
1430
management_socket_set (management, c->c2.event_set, (void*)&management_shift, NULL);
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
1443
c->c2.event_set_status = ES_ERROR;
1445
if (!c->sig->signal_received)
1447
if (!(flags & IOW_CHECK_RESIDUAL) || !socket_read_residual (c->c2.link_socket))
1452
if (check_debug_level (D_EVENT_WAIT))
1453
show_wait_status (c);
1457
* Wait for something to happen.
1459
status = event_wait (c->c2.event_set, &c->c2.timeval, esr, SIZE(esr));
1461
check_status (status, "event_wait", NULL, NULL);
1466
c->c2.event_set_status = 0;
1467
for (i = 0; i < status; ++i)
1469
const struct event_set_return *e = &esr[i];
1470
c->c2.event_set_status |= ((e->rwflags & 3) << *((int*)e->arg));
1473
else if (status == 0)
1475
c->c2.event_set_status = ES_TIMEOUT;
1480
c->c2.event_set_status = SOCKET_READ;
1484
/* 'now' should always be a reasonably up-to-date timestamp */
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);
1491
dmsg (D_EVENT_WAIT, "I/O WAIT status=0x%04x", c->c2.event_set_status);
1495
process_io (struct context *c)
1497
const unsigned int status = c->c2.event_set_status;
1499
#ifdef ENABLE_MANAGEMENT
1500
if (status & (MANAGEMENT_READ|MANAGEMENT_WRITE))
1502
ASSERT (management);
1503
management_io (management);
1507
/* TCP/UDP port ready to accept write */
1508
if (status & SOCKET_WRITE)
1510
process_outgoing_link (c);
1512
/* TUN device ready to accept write */
1513
else if (status & TUN_WRITE)
1515
process_outgoing_tun (c);
1517
/* Incoming data on TCP/UDP port */
1518
else if (status & SOCKET_READ)
1520
read_incoming_link (c);
1522
process_incoming_link (c);
1524
/* Incoming data on TUN device */
1525
else if (status & TUN_READ)
1527
read_incoming_tun (c);
1529
process_incoming_tun (c);