aboutsummaryrefslogtreecommitdiff
path: root/src/vpn/gnunet-helper-vpn-windows.c
blob: 39aa84d9dca68ef30b8d0adf55951815f46f41d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/*
     This file is part of GNUnet.
     (C) 2010, 2012 Christian Grothoff

     GNUnet is free software; you can redistribute it and/or modify
     it under the terms of the GNU General Public License as published
     by the Free Software Foundation; either version 3, or (at your
     option) any later version.

     GNUnet is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with GNUnet; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
 */

/**
 * @file vpn/gnunet-helper-vpn-windows.c
 * @brief the helper for the VPN service in win32 builds. 
 * Opens a virtual network-interface, sends data received on the if to stdout, 
 * sends data received on stdin to the interface
 * @author Christian M. Fuchs
 *
 * The following list of people have reviewed this code and considered
 * it safe since the last modification (if you reviewed it, please
 * have your name added to the list):
 *
 */

#include <stdio.h>
#include <windows.h>
#include <setupapi.h>
#include <ddk/cfgmgr32.h>
#include "platform.h"
#include "tap-windows.h"
#include <Winsock2.h>

/**
 * Need 'struct GNUNET_MessageHeader'.
 */
#include "gnunet_common.h"

/**
 * Need VPN message types.
 */
#include "gnunet_protocols.h"

/**
 * Should we print (interesting|debug) messages that can happen during
 * normal operation?
 */
#define DEBUG GNUNET_NO

/**
 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
 */
#define MAX_SIZE 65536

/**
 * Name or Path+Name of our driver in Unicode.
 * The .sys and .cat files HAVE to be in the same location as this file!
 */
#define INF_FILE "tapw32.inf"

/**
 * Hardware ID used in the inf-file. 
 * This might change over time, as openvpn advances their driver
 */
#define HARDWARE_ID "TAP0901"

/**
 * Component ID if our driver
 */
#define TAP_WIN_COMPONENT_ID "tap0901"

/**
 * Minimum major-id of the driver version we can work with
 */
#define TAP_WIN_MIN_MAJOR 9

/**
 * Minimum minor-id of the driver version we can work with. 
 * v <= 7 has buggy IPv6.
 * v == 8 is broken for small IPv4 Packets
 */
#define TAP_WIN_MIN_MINOR 9

/**
 * Time in seconds to wait for our virtual device to go up after telling it to do so.
 * 
 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
 * (in fact, 4 was chosen by a fair dice roll...)
 */
#define TAP32_POSTUP_WAITTIME 4

/**
 * Location of the network interface list resides in registry.
 * TODO: is this fixed on all version of windows? Checked with XP and 7
 */
#define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"

/**
 * Our local process' PID. Used for creating a sufficiently unique additional 
 * hardware ID for our device.
 */
static char secondary_hwid[LINE_LEN / 2];

/**
 * Device's visible Name, used to identify a network device in netsh.
 * eg: "Local Area Connection 9"
 */
static char device_visible_name[256];

/** 
 * This is our own local instance of a virtual network interface
 * It is (somewhat) equivalent to using tun/tap in unixoid systems
 * 
 * Upon initialization, we create such an device node.
 * Upon termination, we remove it again.
 * 
 * If we crash this device might stay around.
 */
static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;

/**
 * Registry Key we hand over to windows to spawn a new virtual interface
 */
static SP_DEVINFO_DATA DeviceNode;

/**
 * GUID of our virtual device in the form of 
 * {12345678-1234-1234-1234-123456789abc} - in hex
 */
static char device_guid[256];

/* Overlapped IO Begins here (warning: nasty!) */

/** 
 * A overlapped-IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
 */
struct overlapped_facility
{
  int iostate;
  BOOL status; // BOOL is winbool, NOT boolean!
  DWORD flags;

  OVERLAPPED overlapped;

  DWORD buffer_size;
  unsigned char buffer[MAX_SIZE];
};

/** 
 * Operlapped IO states for its objects
 */
#define IOSTATE_INITIAL          0
#define IOSTATE_QUEUED           1 /* overlapped I/O has been queued */
#define IOSTATE_IMMEDIATE_RETURN 2 /* I/O function returned immediately without queueing */

#if WINVER < 0x0600

/**
 * inet_pton() wrapper for WSAStringToAddress()
 *
 * this is needed as long as we support WinXP, because only Vista+ support 
 * inet_pton at all, and mingw does not yet offer inet_pton/ntop at all
 * 
 * @param af - IN - the aftype this address is supposed to be (v4/v6) 
 * @param src - IN - the presentation form of the address
 * @param dst - OUT - the numerical form of the address
 * @return 0 on success, 1 on failure
 */
int
inet_pton (int af, const char *src, void *dst)
{
  struct sockaddr_storage addr;
  int size = sizeof (addr);
  char local_copy[INET6_ADDRSTRLEN + 1];

  ZeroMemory (&addr, sizeof (addr));
  /* stupid non-const API */
  strncpy (local_copy, src, INET6_ADDRSTRLEN + 1);
  local_copy[INET6_ADDRSTRLEN] = 0;

  if (WSAStringToAddressA (local_copy, af, NULL, (struct sockaddr *) &addr, &size) == 0)
    {
      switch (af)
        {
        case AF_INET:
          *(struct in_addr *) dst = ((struct sockaddr_in *) &addr)->sin_addr;
          return 1;
        case AF_INET6:
          *(struct in6_addr *) dst = ((struct sockaddr_in6 *) &addr)->sin6_addr;
          return 1;
        }
    }
  return 0;
}
#endif

/**
 * Wrapper for executing a shellcommand in windows.
 * 
 * @param command - the command + parameters to execute
 * @return * exitcode of the program executed, 
 *         * EINVAL (cmd/file not found)
 *         * EPIPE (could not read STDOUT)
 */
static int
execute_shellcommand (char * command)
{
  FILE *pipe;

  if (NULL == command ||
      NULL == (pipe = _popen (command, "rt")))
    return EINVAL;

#ifdef TESTING
  {
    char output[LINE_LEN];

    printf ("executed command: %s", command);
    while (NULL != fgets (output, sizeof (output), pipe))
      printf (output);
  }
#endif

  if (!feof (pipe))
    return EPIPE;

  return _pclose (pipe);
}

/**
 * @brief Sets the IPv6-Address given in address on the interface dev
 *
 * @param address the IPv6-Address
 * @param prefix_len the length of the network-prefix
 */
static void
set_address6 (const char *address, unsigned long prefix_len)
{
  int ret = EINVAL;
  char command[LINE_LEN];
  struct sockaddr_in6 sa6;

  /*
   * parse the new address
   */
  memset (&sa6, 0, sizeof (struct sockaddr_in6));
  sa6.sin6_family = AF_INET6;
  if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
    {
      fprintf (stderr, "Failed to parse address `%s': %s\n", address,
               strerror (errno));
      exit (1);
    }

  /*
   * prepare the command
   */
  snprintf (command, LINE_LEN,
            "netsh interface ipv6 add address \"%s\" %s/%d",
            device_visible_name, address, prefix_len);
  /*
   * Set the address
   */
  ret = execute_shellcommand (command);

  /* Did it work?*/
  if (0 != ret)
    {
      fprintf (stderr, "Setting IPv6 address failed: %s\n", strerror (ret));
      exit (1); // FIXME: return error code, shut down interface / unload driver
    }
}

/**
 * @brief Sets the IPv4-Address given in address on the interface dev
 *
 * @param dev the interface to configure
 * @param address the IPv4-Address
 * @param mask the netmask
 */
static void
set_address4 (const char *address, const char *mask)
{
  int ret = EINVAL;
  char command[LINE_LEN];

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;

  /*
   * Parse the address
   */
  if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
    {
      fprintf (stderr, "Failed to parse address `%s': %s\n", address,
               strerror (errno));
      exit (1);
    }

  /*
   * prepare the command
   */
  snprintf (command, LINE_LEN,
            "netsh interface ipv4 add address \"%s\" %s %s",
            device_visible_name, address, mask);
  /*
   * Set the address
   */
  ret = execute_shellcommand (command);

  /* Did it work?*/
  if (0 != ret)
    {
      fprintf (stderr, "Setting IPv4 address failed: %s\n", strerror (ret));
      exit (1); // FIXME: return error code, shut down interface / unload driver
    }
}

/**
 * Setup a new virtual interface to use for tunneling. 
 * 
 * @return: TRUE if setup was successful, else FALSE
 */
static boolean
setup_interface ()
{
  /*
   * where to find our inf-file. (+ the "full" path, after windows found")
   * 
   * We do not directly input all the props here, because openvpn will update
   * these details over time.
   */
  char inf_file_path[MAX_PATH];
  char hwidlist[LINE_LEN + 4];
  char class_name[128];
  GUID class_guid;
  int str_lenth = 0;

  /** 
   * Set the device's hardware ID and add it to a list.
   * This information will later on identify this device in registry. 
   * 
   * TODO: Currently we just use TAP0901 as HWID, 
   * but we might want to add additional information
   */
  strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
  /**
   * this is kind of over-complicated, but allows keeps things independent of 
   * how the openvpn-hwid is actually stored. 
   * 
   * A HWID list is double-\0 terminated and \0 separated
   */
  str_lenth = strlen (hwidlist) + 1;
  strncpy (&hwidlist[str_lenth], secondary_hwid, LINE_LEN - str_lenth);

  /** 
   * Locate the inf-file, we need to store it somewhere where the system can
   * find it. A good choice would be CWD/PDW or %WINDIR$\system32\
   * 
   * TODO: How about win64 in the future? 
   *       We need to use a different driver for amd64/i386 !
   */
  GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, NULL);

  /** 
   * Bootstrap our device info using the drivers inf-file
   */
  if (!SetupDiGetINFClassA (inf_file_path,
                            &class_guid,
                            class_name, sizeof (class_name) / sizeof (char),
                            NULL))
    return FALSE;

  /** 
   * Collect all the other needed information... 
   * let the system fill our this form 
   */
  DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
  if (DeviceInfo == INVALID_HANDLE_VALUE)
    return FALSE;

  DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
  if (!SetupDiCreateDeviceInfoA (DeviceInfo,
                                 class_name,
                                 &class_guid,
                                 NULL,
                                 NULL,
                                 DICD_GENERATE_ID,
                                 &DeviceNode))
    return FALSE;

  /* Deploy all the information collected into the registry */
  if (!SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
                                          &DeviceNode,
                                          SPDRP_HARDWAREID,
                                          (LPBYTE) hwidlist,
                                          (strlen (hwidlist) + 2) * sizeof (char)))
    return FALSE;

  /* Install our new class(=device) into the system */
  if (!SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
                                  DeviceInfo,
                                  &DeviceNode))
    return FALSE;

  return TRUE;
}

/**
 * Remove our new virtual interface to use for tunneling. 
 * This function must be called AFTER setup_interface!
 * 
 * @return: TRUE if destruction was successful, else FALSE
 */
static boolean
remove_interface ()
{
  SP_REMOVEDEVICE_PARAMS remove;

  if (INVALID_HANDLE_VALUE == DeviceInfo)
    return FALSE;

  remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
  remove.HwProfile = 0;
  remove.Scope = DI_REMOVEDEVICE_GLOBAL;
  remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
  /*
   * 1. Prepare our existing device information set, and place the 
   *    uninstall related information into the structure
   */
  if (!SetupDiSetClassInstallParamsA (DeviceInfo,
                                      (PSP_DEVINFO_DATA) & DeviceNode,
                                      &remove.ClassInstallHeader,
                                      sizeof (remove)))
    return FALSE;
  /*
   * 2. Uninstall the virtual interface using the class installer
   */
  if (!SetupDiCallClassInstaller (DIF_REMOVE,
                                  DeviceInfo,
                                  (PSP_DEVINFO_DATA) & DeviceNode))
    return FALSE;

  SetupDiDestroyDeviceInfoList (DeviceInfo);

  return TRUE;
}

/**
 * Do all the lookup necessary to retrieve the inteface's actual name
 * off the registry. 
 * 
 * @return: TRUE if we were able to lookup the interface's name, else FALSE
 */
static boolean
resolve_interface_name ()
{

  SP_DEVINFO_LIST_DETAIL_DATA device_details;
  char pnp_instance_id [MAX_DEVICE_ID_LEN];
  HKEY adapter_key_handle;
  LONG status;
  DWORD len;
  int i = 0;
  boolean retval = FALSE;
  char adapter[] = INTERFACE_REGISTRY_LOCATION;

  /* We can obtain the PNP instance ID from our setupapi handle */
  device_details.cbSize = sizeof (device_details);
  if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
                                          (PCHAR) pnp_instance_id,
                                          MAX_DEVICE_ID_LEN,
                                          0, //must be 0
                                          NULL)) //hMachine, we are local
    return FALSE;

  /* Now we can use this ID to locate the correct networks interface in registry */
  if (ERROR_SUCCESS != RegOpenKeyExA (
                                      HKEY_LOCAL_MACHINE,
                                      adapter,
                                      0,
                                      KEY_READ,
                                      &adapter_key_handle))
    return FALSE;

  /* Of course there is a multitude of entries here, with arbitrary names, 
   * thus we need to iterate through there.
   */
  while (!retval)
    {
      char instance_key[256];
      char query_key [256];
      HKEY instance_key_handle;
      char pnpinstanceid_name[] = "PnpInstanceID";
      char pnpinstanceid_value[256];
      char adaptername_name[] = "Name";
      DWORD data_type;

      len = sizeof (adapter_key_handle);
      /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
      status = RegEnumKeyExA (
                              adapter_key_handle,
                              i,
                              instance_key,
                              &len,
                              NULL,
                              NULL,
                              NULL,
                              NULL);

      /* this may fail due to one of two reasons: 
       * we are at the end of the list*/
      if (ERROR_NO_MORE_ITEMS == status)
        break;
      // * we found a broken registry key, continue with the next key.
      if (ERROR_SUCCESS != status)
        goto cleanup;

      /* prepare our new query string: */
      snprintf (query_key, 256, "%s\\%s\\Connection",
                INTERFACE_REGISTRY_LOCATION,
                instance_key);

      /* look inside instance_key\\Connection */
      status = RegOpenKeyExA (
                              HKEY_LOCAL_MACHINE,
                              query_key,
                              0,
                              KEY_READ,
                              &instance_key_handle);

      if (status != ERROR_SUCCESS)
        continue;

      /* now, read our PnpInstanceID */
      len = sizeof (pnpinstanceid_value);
      status = RegQueryValueExA (instance_key_handle,
                                 pnpinstanceid_name,
                                 NULL, //reserved, always NULL according to MSDN
                                 &data_type,
                                 (LPBYTE) pnpinstanceid_value,
                                 &len);

      if (status != ERROR_SUCCESS || data_type != REG_SZ)
        goto cleanup;

      /* compare the value we got to our devices PNPInstanceID*/
      if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
                        sizeof (pnpinstanceid_value) / sizeof (char)))
        goto cleanup;

      len = sizeof (device_visible_name);
      status = RegQueryValueExA (
                                 instance_key_handle,
                                 adaptername_name,
                                 NULL, //reserved, always NULL according to MSDN
                                 &data_type,
                                 (LPBYTE) device_visible_name,
                                 &len);

      if (status != ERROR_SUCCESS || data_type != REG_SZ)
        goto cleanup;

      /* 
       * we have successfully found OUR instance, 
       * save the device GUID before exiting
       */

      strncpy (device_guid, instance_key, 256);
      retval = TRUE;

cleanup:
      RegCloseKey (instance_key_handle);

      ++i;
    }

  RegCloseKey (adapter_key_handle);

  return retval;
}

static boolean
check_tapw32_version (HANDLE handle)
{
  {
    ULONG version[3];
    DWORD len;
    memset (&(version), 0, sizeof (version));


    if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
                         &version, sizeof (version),
                         &version, sizeof (version), &len, NULL))
      {
#ifdef TESTING
        fprintf (stderr, "TAP-Windows Driver Version %d.%d %s",
                 (int) version[0],
                 (int) version[1],
                 (version[2] ? "(DEBUG)" : ""));
#endif
      }

    if (version[0] != TAP_WIN_MIN_MAJOR || version[1] < TAP_WIN_MIN_MINOR)
      {
        fprintf (stderr, "ERROR:  This version of gnunet requires a TAP-Windows driver that is at least version %d.%d!\n",
                 TAP_WIN_MIN_MAJOR,
                 TAP_WIN_MIN_MINOR);
        return FALSE;
      }
    return TRUE;
  }
}

/**
 * Creates a tun-interface called dev;
 *
 * @return the fd to the tun or -1 on error
 */
static HANDLE
init_tun ()
{
  char device_path[256];
  HANDLE handle;

  if (!setup_interface ())
    {
      errno = ENODEV;
      return INVALID_HANDLE_VALUE;
    }

  if (!resolve_interface_name ())
    {
      errno = ENODEV;
      return INVALID_HANDLE_VALUE;
    }

  /* Open Windows TAP-Windows adapter */
  snprintf (device_path, sizeof (device_path), "%s%s%s",
            USERMODEDEVICEDIR,
            device_guid,
            TAP_WIN_SUFFIX);

  handle = CreateFile (
                       device_path,
                       GENERIC_READ | GENERIC_WRITE,
                       0, /* was: FILE_SHARE_READ */
                       0,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
                       0
                       );

  if (handle == INVALID_HANDLE_VALUE)
    {
      fprintf (stderr, "CreateFile failed on TAP device: %s\n", device_path);
      return handle;
    }

  /* get driver version info */
  if (!check_tapw32_version (handle))
    {
      CloseHandle (handle);
      return INVALID_HANDLE_VALUE;
    }

  /* TODO (opt?): get MTU-Size */

  return handle;
}

static boolean
tun_up (HANDLE handle)
{
  ULONG status = TRUE;
  DWORD len;
  if (DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
                       &status, sizeof (status),
                       &status, sizeof (status), &len, NULL))
    {
      fprintf (stderr, "The TAP-Windows driver ignored our request to set the interface UP (TAP_WIN_IOCTL_SET_MEDIA_STATUS DeviceIoControl call)!\n");
      return FALSE;
    }

  /* Wait for the device to go UP, might take some time. */
  Sleep ((TAP32_POSTUP_WAITTIME)*1000);

  return TRUE;

}

/**
 * Initialize a overlapped structure
 * 
 * @param elem the element to initilize
 * @param initial_state the initial state for this instance
 * @param signaled if the hEvent created should default to signaled or not
 * @return true on success, else false
 */
static boolean
initialize_overlapped_facility (struct overlapped_facility * elem,
                                BOOL initial_state,
                                BOOL signaled)
{

  elem->status = initial_state;
  elem->iostate = 0;
  elem->buffer_size = MAX_SIZE;
  elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
  if (NULL == elem->overlapped.hEvent)
    return FALSE;

  return TRUE;
}

/**
 * Start forwarding to and from the tunnel.
 *
 * @param fd_tun tunnel FD
 */
static void
run (HANDLE handle)
{
  /* read refers to reading from fd_tun, writing to stdout */
  int read_open = 1;
  /* write refers to reading from stdin, writing to fd_tun */
  int write_open = 1;

  /* IO-Facility for reading from our virtual interface */
  struct overlapped_facility tap_read;
  /* IO-Facility for writing to our virtual interface */
  struct overlapped_facility tap_write;
  /* IO-Facility for reading from stdin */
  struct overlapped_facility std_in;
  /* IO-Facility for writing to stdout */
  struct overlapped_facility std_out;

  /* tun up: */
  /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
   * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
   *  
   * DHCP and such are all features we will never use in gnunet afaik.
   * But for openvpn those are essential.
   */
  if (!tun_up (handle))
    goto teardown;

  if (!)
    goto teardown;

  /* Initialize our overlapped IO structures*/
  if (initialize_overlapped_facility (&tap_read, TRUE, FALSE)
      && initialize_overlapped_facility (&tap_write, FALSE, TRUE)
      && initialize_overlapped_facility (&std_in, TRUE, FALSE)
      && initialize_overlapped_facility (&std_out, FALSE, TRUE))
    goto teardown;


  //openvpn  
  // Set Device to Subnet-Mode? 
  // do we really need tun.c:2925 ?
  // Why does openvpn assign IPv4's there??? Foobar??

  // Setup should be complete here.
  // If something is missing, check init.c:3400+

  // mainloop:
  // tunnel_point_to_point
  // openvpn.c:62

  while ((1 == read_open) || (1 == write_open))
    {

      /* READ from stdin is possible */
      if (std_in.status)
        {

        }
      /* READ from tap is possible */
      if (tap_read.status)
        {

        }
      /* WRITE to tap is possible */
      if (tap_write.status)
        {

        }
      /* WRITE to STDOUT is possible */
      if (std_out.status)
        {

        }
    }
teardown:
  ;
  //init.c:3472
}

/**
 * Open VPN tunnel interface.
 *
 * @param argc must be 6
 * @param argv 0: binary name (gnunet-helper-vpn)
 *             1: tunnel interface name (gnunet-vpn)
 *             2: IPv6 address (::1), "-" to disable
 *             3: IPv6 netmask length in bits (64), ignored if #2 is "-"
 *             4: IPv4 address (1.2.3.4), "-" to disable
 *             5: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
 */
int
main (int argc, char **argv)
{
  char hwid[LINE_LEN];
  HANDLE handle;
  int global_ret;

  if (6 != argc)
    {
      fprintf (stderr, "Fatal: must supply 5 arguments!\n");
      return 1;
    }

  strncpy (hwid, argv[1], LINE_LEN);
  hwid[LINE_LEN - 1] = '\0';

  /* 
   * We use our PID for finding/resolving the control-panel name of our virtual 
   * device. PIDs are (of course) unique at runtime, thus we can safely use it 
   * as additional hardware-id for our device.
   */
  snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
            hwid,
            _getpid ());

  if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
    {
      fprintf (stderr, "Fatal: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
               hwid,
               argv[2],
               argv[3],
               argv[4],
               argv[5]);
      return 1;
    }

  if (0 != strcmp (argv[2], "-"))
    {
      const char *address = argv[2];
      long prefix_len = atol (argv[3]);

      if ((prefix_len < 1) || (prefix_len > 127))
        {
          fprintf (stderr, "Fatal: prefix_len out of range\n");
          global_ret = -1;
          goto cleanup;
        }

      set_address6 (address, prefix_len);
    }

  if (0 != strcmp (argv[4], "-"))
    {
      const char *address = argv[4];
      const char *mask = argv[5];

      set_address4 (address, mask);
    }

  //eventuell: 
  // tap_allow_nonadmin_access
  //tun.c:2023

  run (handle);
  global_ret = 0;
cleanup:
  remove_interface ();

  return global_ret;
}