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