gnunet-helper-vpn-windows.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. /*
  2. This file is part of GNUnet.
  3. (C) 2010, 2012 Christian Grothoff
  4. GNUnet is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published
  6. by the Free Software Foundation; either version 3, or (at your
  7. option) any later version.
  8. GNUnet is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNUnet; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  15. Boston, MA 02111-1307, USA.
  16. */
  17. /**
  18. * @file vpn/gnunet-helper-vpn-windows.c
  19. * @brief the helper for the VPN service in win32 builds.
  20. * Opens a virtual network-interface, sends data received on the if to stdout,
  21. * sends data received on stdin to the interface
  22. * @author Christian M. Fuchs
  23. *
  24. * The following list of people have reviewed this code and considered
  25. * it safe since the last modification (if you reviewed it, please
  26. * have your name added to the list):
  27. *
  28. */
  29. #include <stdio.h>
  30. #include <Winsock2.h>
  31. #include <windows.h>
  32. #include <setupapi.h>
  33. #ifndef __MINGW64_VERSION_MAJOR
  34. #include <ddk/cfgmgr32.h>
  35. #include <ddk/newdev.h>
  36. #else
  37. #include <cfgmgr32.h>
  38. #include <newdev.h>
  39. #endif
  40. #include <time.h>
  41. #include "platform.h"
  42. #include "tap-windows.h"
  43. /**
  44. * Need 'struct GNUNET_HashCode' and 'struct GNUNET_PeerIdentity'.
  45. */
  46. #include "gnunet_crypto_lib.h"
  47. /**
  48. * Need 'struct GNUNET_MessageHeader'.
  49. */
  50. #include "gnunet_common.h"
  51. /**
  52. * Need VPN message types.
  53. */
  54. #include "gnunet_protocols.h"
  55. /**
  56. * Should we print (interesting|debug) messages that can happen during
  57. * normal operation?
  58. */
  59. #define DEBUG GNUNET_NO
  60. #if DEBUG
  61. /* FIXME: define with varargs... */
  62. #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
  63. #else
  64. #define LOG_DEBUG(msg) do {} while (0)
  65. #endif
  66. /**
  67. * Will this binary be run in permissions testing mode?
  68. */
  69. static boolean privilege_testing = FALSE;
  70. /**
  71. * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
  72. */
  73. #define MAX_SIZE 65536
  74. /**
  75. * Name or Path+Name of our win32 driver.
  76. * The .sys and .cat files HAVE to be in the same location as this file!
  77. */
  78. #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
  79. /**
  80. * Name or Path+Name of our win64 driver.
  81. * The .sys and .cat files HAVE to be in the same location as this file!
  82. */
  83. #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
  84. /**
  85. * Hardware ID used in the inf-file.
  86. * This might change over time, as openvpn advances their driver
  87. */
  88. #define HARDWARE_ID "tap0901"
  89. /**
  90. * Minimum major-id of the driver version we can work with
  91. */
  92. #define TAP_WIN_MIN_MAJOR 9
  93. /**
  94. * Minimum minor-id of the driver version we can work with.
  95. * v <= 7 has buggy IPv6.
  96. * v == 8 is broken for small IPv4 Packets
  97. */
  98. #define TAP_WIN_MIN_MINOR 9
  99. /**
  100. * Time in seconds to wait for our virtual device to go up after telling it to do so.
  101. *
  102. * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
  103. * (in fact, 4 was chosen by a fair dice roll...)
  104. */
  105. #define TAP32_POSTUP_WAITTIME 4
  106. /**
  107. * Location of the network interface list resides in registry.
  108. */
  109. #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
  110. /**
  111. * Our local process' PID. Used for creating a sufficiently unique additional
  112. * hardware ID for our device.
  113. */
  114. static char secondary_hwid[LINE_LEN / 2];
  115. /**
  116. * Device's visible Name, used to identify a network device in netsh.
  117. * eg: "Local Area Connection 9"
  118. */
  119. static char device_visible_name[256];
  120. /**
  121. * This is our own local instance of a virtual network interface
  122. * It is (somewhat) equivalent to using tun/tap in unixoid systems
  123. *
  124. * Upon initialization, we create such an device node.
  125. * Upon termination, we remove it again.
  126. *
  127. * If we crash this device might stay around.
  128. */
  129. static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
  130. /**
  131. * Registry Key we hand over to windows to spawn a new virtual interface
  132. */
  133. static SP_DEVINFO_DATA DeviceNode;
  134. /**
  135. * GUID of our virtual device in the form of
  136. * {12345678-1234-1234-1234-123456789abc} - in hex
  137. */
  138. static char device_guid[256];
  139. /**
  140. * Possible states of an IO facility.
  141. */
  142. enum IO_State
  143. {
  144. /**
  145. * overlapped I/O is ready for work
  146. */
  147. IOSTATE_READY = 0,
  148. /**
  149. * overlapped I/O has been queued
  150. */
  151. IOSTATE_QUEUED,
  152. /**
  153. * overlapped I/O has finished, but is waiting for it's write-partner
  154. */
  155. IOSTATE_WAITING,
  156. /**
  157. * there is a full buffer waiting
  158. */
  159. IOSTATE_RESUME,
  160. /**
  161. * Operlapped IO states for facility objects
  162. * overlapped I/O has failed, stop processing
  163. */
  164. IOSTATE_FAILED
  165. };
  166. /**
  167. * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
  168. */
  169. struct io_facility
  170. {
  171. /**
  172. * The mode the state machine associated with this object is in.
  173. */
  174. enum IO_State facility_state;
  175. /**
  176. * If the path is open or blocked in general (used for quickly checking)
  177. */
  178. BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
  179. /**
  180. * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
  181. */
  182. HANDLE handle;
  183. /**
  184. * Overlaped IO structure used for asynchronous IO in windows.
  185. */
  186. OVERLAPPED overlapped;
  187. /**
  188. * Buffer for reading things to and writing from...
  189. */
  190. unsigned char buffer[MAX_SIZE];
  191. /**
  192. * How much of this buffer was used when reading or how much data can be written
  193. */
  194. DWORD buffer_size;
  195. /**
  196. * Amount of data actually written or read by readfile/writefile.
  197. */
  198. DWORD buffer_size_processed;
  199. /**
  200. * How much of this buffer we have writte in total
  201. */
  202. DWORD buffer_size_written;
  203. };
  204. /**
  205. * ReOpenFile is only available as of XP SP2 and 2003 SP1
  206. */
  207. WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
  208. /**
  209. * IsWow64Process definition for our is_win64, as this is a kernel function
  210. */
  211. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  212. /**
  213. * Determines if the host OS is win32 or win64
  214. *
  215. * @return true if
  216. */
  217. BOOL
  218. is_win64 ()
  219. {
  220. #if defined(_WIN64)
  221. //this is a win64 binary,
  222. return TRUE;
  223. #elif defined(_WIN32)
  224. //this is a 32bit binary, and we need to check if we are running in WOW64
  225. BOOL success = FALSE;
  226. BOOL on_wow64 = FALSE;
  227. LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
  228. if (NULL != IsWow64Process)
  229. success = IsWow64Process (GetCurrentProcess (), &on_wow64);
  230. return success && on_wow64;
  231. #endif
  232. }
  233. /**
  234. * Wrapper for executing a shellcommand in windows.
  235. *
  236. * @param command - the command + parameters to execute
  237. * @return * exitcode of the program executed,
  238. * * EINVAL (cmd/file not found)
  239. * * EPIPE (could not read STDOUT)
  240. */
  241. static int
  242. execute_shellcommand (const char *command)
  243. {
  244. FILE *pipe;
  245. if ( (NULL == command) ||
  246. (NULL == (pipe = _popen (command, "rt"))) )
  247. return EINVAL;
  248. #if DEBUG
  249. fprintf (stderr, "DEBUG: Command output: \n");
  250. char output[LINE_LEN];
  251. while (NULL != fgets (output, sizeof (output), pipe))
  252. fprintf (stderr, "%s", output);
  253. #endif
  254. return _pclose (pipe);
  255. }
  256. /**
  257. * @brief Sets the IPv6-Address given in address on the interface dev
  258. *
  259. * @param address the IPv6-Address
  260. * @param prefix_len the length of the network-prefix
  261. */
  262. static int
  263. set_address6 (const char *address, unsigned long prefix_len)
  264. {
  265. int ret = EINVAL;
  266. char command[LINE_LEN];
  267. struct sockaddr_in6 sa6;
  268. /*
  269. * parse the new address
  270. */
  271. memset (&sa6, 0, sizeof (struct sockaddr_in6));
  272. sa6.sin6_family = AF_INET6;
  273. if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
  274. {
  275. fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
  276. strerror (errno));
  277. return -1;
  278. }
  279. /*
  280. * prepare the command
  281. */
  282. snprintf (command, LINE_LEN,
  283. "netsh interface ipv6 add address \"%s\" %s/%d store=active",
  284. device_visible_name, address, prefix_len);
  285. /*
  286. * Set the address
  287. */
  288. ret = execute_shellcommand (command);
  289. /* Did it work?*/
  290. if (0 != ret)
  291. fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
  292. return ret;
  293. }
  294. /**
  295. * @brief Removes the IPv6-Address given in address from the interface dev
  296. *
  297. * @param address the IPv4-Address
  298. */
  299. static void
  300. remove_address6 (const char *address)
  301. {
  302. char command[LINE_LEN];
  303. int ret = EINVAL;
  304. // sanity checking was already done in set_address6
  305. /*
  306. * prepare the command
  307. */
  308. snprintf (command, LINE_LEN,
  309. "netsh interface ipv6 delete address \"%s\" store=persistent",
  310. device_visible_name);
  311. /*
  312. * Set the address
  313. */
  314. ret = execute_shellcommand (command);
  315. /* Did it work?*/
  316. if (0 != ret)
  317. fprintf (stderr,
  318. "FATAL: removing IPv6 address failed: %s\n",
  319. strerror (ret));
  320. }
  321. /**
  322. * @brief Sets the IPv4-Address given in address on the interface dev
  323. *
  324. * @param address the IPv4-Address
  325. * @param mask the netmask
  326. */
  327. static int
  328. set_address4 (const char *address, const char *mask)
  329. {
  330. int ret = EINVAL;
  331. char command[LINE_LEN];
  332. struct sockaddr_in addr;
  333. addr.sin_family = AF_INET;
  334. /*
  335. * Parse the address
  336. */
  337. if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
  338. {
  339. fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
  340. strerror (errno));
  341. return -1;
  342. }
  343. // Set Device to Subnet-Mode? do we really need openvpn/tun.c:2925 ?
  344. /*
  345. * prepare the command
  346. */
  347. snprintf (command, LINE_LEN,
  348. "netsh interface ipv4 add address \"%s\" %s %s store=active",
  349. device_visible_name, address, mask);
  350. /*
  351. * Set the address
  352. */
  353. ret = execute_shellcommand (command);
  354. /* Did it work?*/
  355. if (0 != ret)
  356. fprintf (stderr,
  357. "FATAL: Setting IPv4 address failed: %s\n",
  358. strerror (ret));
  359. return ret;
  360. }
  361. /**
  362. * @brief Removes the IPv4-Address given in address from the interface dev
  363. *
  364. * @param address the IPv4-Address
  365. */
  366. static void
  367. remove_address4 (const char *address)
  368. {
  369. char command[LINE_LEN];
  370. int ret = EINVAL;
  371. // sanity checking was already done in set_address4
  372. /*
  373. * prepare the command
  374. */
  375. snprintf (command, LINE_LEN,
  376. "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
  377. device_visible_name);
  378. /*
  379. * Set the address
  380. */
  381. ret = execute_shellcommand (command);
  382. /* Did it work?*/
  383. if (0 != ret)
  384. fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
  385. }
  386. /**
  387. * Setup a new virtual interface to use for tunneling.
  388. *
  389. * @return: TRUE if setup was successful, else FALSE
  390. */
  391. static BOOL
  392. setup_interface ()
  393. {
  394. /*
  395. * where to find our inf-file. (+ the "full" path, after windows found")
  396. *
  397. * We do not directly input all the props here, because openvpn will update
  398. * these details over time.
  399. */
  400. char inf_file_path[MAX_PATH];
  401. char * temp_inf_filename;
  402. char hwidlist[LINE_LEN + 4];
  403. char class_name[128];
  404. GUID class_guid;
  405. int str_length = 0;
  406. /**
  407. * Set the device's hardware ID and add it to a list.
  408. * This information will later on identify this device in registry.
  409. */
  410. strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
  411. /**
  412. * this is kind of over-complicated, but allows keeps things independent of
  413. * how the openvpn-hwid is actually stored.
  414. *
  415. * A HWID list is double-\0 terminated and \0 separated
  416. */
  417. str_length = strlen (hwidlist) + 1;
  418. strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
  419. str_length += strlen (&hwidlist[str_length]) + 1;
  420. /**
  421. * Locate the inf-file, we need to store it somewhere where the system can
  422. * find it. We need to pick the correct driver for win32/win64.
  423. */
  424. if (is_win64())
  425. GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
  426. else
  427. GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
  428. fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
  429. /**
  430. * Bootstrap our device info using the drivers inf-file
  431. */
  432. if ( ! SetupDiGetINFClassA (inf_file_path,
  433. &class_guid,
  434. class_name, sizeof (class_name) / sizeof (char),
  435. NULL))
  436. return FALSE;
  437. /**
  438. * Collect all the other needed information...
  439. * let the system fill our this form
  440. */
  441. DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
  442. if (DeviceInfo == INVALID_HANDLE_VALUE)
  443. return FALSE;
  444. DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
  445. if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
  446. class_name,
  447. &class_guid,
  448. NULL,
  449. 0,
  450. DICD_GENERATE_ID,
  451. &DeviceNode))
  452. return FALSE;
  453. /* Deploy all the information collected into the registry */
  454. if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
  455. &DeviceNode,
  456. SPDRP_HARDWAREID,
  457. (LPBYTE) hwidlist,
  458. str_length * sizeof (char)))
  459. return FALSE;
  460. /* Install our new class(=device) into the system */
  461. if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
  462. DeviceInfo,
  463. &DeviceNode))
  464. return FALSE;
  465. /* This system call tends to take a while (several seconds!) on
  466. "modern" Windoze systems */
  467. if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
  468. secondary_hwid,
  469. inf_file_path,
  470. INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
  471. NULL)) //reboot required? NEVER!
  472. return FALSE;
  473. fprintf (stderr, "DEBUG: successfully created a network device\n");
  474. return TRUE;
  475. }
  476. /**
  477. * Remove our new virtual interface to use for tunneling.
  478. * This function must be called AFTER setup_interface!
  479. *
  480. * @return: TRUE if destruction was successful, else FALSE
  481. */
  482. static BOOL
  483. remove_interface ()
  484. {
  485. SP_REMOVEDEVICE_PARAMS remove;
  486. if (INVALID_HANDLE_VALUE == DeviceInfo)
  487. return FALSE;
  488. remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
  489. remove.HwProfile = 0;
  490. remove.Scope = DI_REMOVEDEVICE_GLOBAL;
  491. remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
  492. /*
  493. * 1. Prepare our existing device information set, and place the
  494. * uninstall related information into the structure
  495. */
  496. if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
  497. (PSP_DEVINFO_DATA) & DeviceNode,
  498. &remove.ClassInstallHeader,
  499. sizeof (remove)))
  500. return FALSE;
  501. /*
  502. * 2. Uninstall the virtual interface using the class installer
  503. */
  504. if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
  505. DeviceInfo,
  506. (PSP_DEVINFO_DATA) & DeviceNode))
  507. return FALSE;
  508. SetupDiDestroyDeviceInfoList (DeviceInfo);
  509. fprintf (stderr, "DEBUG: removed interface successfully\n");
  510. return TRUE;
  511. }
  512. /**
  513. * Do all the lookup necessary to retrieve the inteface's actual name
  514. * off the registry.
  515. *
  516. * @return: TRUE if we were able to lookup the interface's name, else FALSE
  517. */
  518. static BOOL
  519. resolve_interface_name ()
  520. {
  521. SP_DEVINFO_LIST_DETAIL_DATA device_details;
  522. char pnp_instance_id [MAX_DEVICE_ID_LEN];
  523. HKEY adapter_key_handle;
  524. LONG status;
  525. DWORD len;
  526. int i = 0;
  527. int retrys;
  528. BOOL retval = FALSE;
  529. char adapter[] = INTERFACE_REGISTRY_LOCATION;
  530. /* We can obtain the PNP instance ID from our setupapi handle */
  531. device_details.cbSize = sizeof (device_details);
  532. if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
  533. (PCHAR) pnp_instance_id,
  534. MAX_DEVICE_ID_LEN,
  535. 0, //must be 0
  536. NULL)) //hMachine, we are local
  537. return FALSE;
  538. fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
  539. /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
  540. for (retrys = 0; retrys < 120 && !retval; retrys++)
  541. {
  542. /* sleep for 250ms*/
  543. Sleep (250);
  544. /* Now we can use this ID to locate the correct networks interface in registry */
  545. if (ERROR_SUCCESS != RegOpenKeyExA (
  546. HKEY_LOCAL_MACHINE,
  547. adapter,
  548. 0,
  549. KEY_READ,
  550. &adapter_key_handle))
  551. return FALSE;
  552. /* Of course there is a multitude of entries here, with arbitrary names,
  553. * thus we need to iterate through there.
  554. */
  555. while (!retval)
  556. {
  557. char instance_key[256];
  558. char query_key [256];
  559. HKEY instance_key_handle;
  560. char pnpinstanceid_name[] = "PnpInstanceID";
  561. char pnpinstanceid_value[256];
  562. char adaptername_name[] = "Name";
  563. DWORD data_type;
  564. len = 256 * sizeof (char);
  565. /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
  566. status = RegEnumKeyExA (
  567. adapter_key_handle,
  568. i,
  569. instance_key,
  570. &len,
  571. NULL,
  572. NULL,
  573. NULL,
  574. NULL);
  575. /* this may fail due to one of two reasons:
  576. * we are at the end of the list*/
  577. if (ERROR_NO_MORE_ITEMS == status)
  578. break;
  579. // * we found a broken registry key, continue with the next key.
  580. if (ERROR_SUCCESS != status)
  581. goto cleanup;
  582. /* prepare our new query string: */
  583. snprintf (query_key, 256, "%s\\%s\\Connection",
  584. adapter,
  585. instance_key);
  586. /* look inside instance_key\\Connection */
  587. if (ERROR_SUCCESS != RegOpenKeyExA (
  588. HKEY_LOCAL_MACHINE,
  589. query_key,
  590. 0,
  591. KEY_READ,
  592. &instance_key_handle))
  593. goto cleanup;
  594. /* now, read our PnpInstanceID */
  595. len = sizeof (pnpinstanceid_value);
  596. status = RegQueryValueExA (instance_key_handle,
  597. pnpinstanceid_name,
  598. NULL, //reserved, always NULL according to MSDN
  599. &data_type,
  600. (LPBYTE) pnpinstanceid_value,
  601. &len);
  602. if (status != ERROR_SUCCESS || data_type != REG_SZ)
  603. goto cleanup;
  604. /* compare the value we got to our devices PNPInstanceID*/
  605. if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
  606. sizeof (pnpinstanceid_value) / sizeof (char)))
  607. goto cleanup;
  608. len = sizeof (device_visible_name);
  609. status = RegQueryValueExA (
  610. instance_key_handle,
  611. adaptername_name,
  612. NULL, //reserved, always NULL according to MSDN
  613. &data_type,
  614. (LPBYTE) device_visible_name,
  615. &len);
  616. if (status != ERROR_SUCCESS || data_type != REG_SZ)
  617. goto cleanup;
  618. /*
  619. * we have successfully found OUR instance,
  620. * save the device GUID before exiting
  621. */
  622. strncpy (device_guid, instance_key, 256);
  623. retval = TRUE;
  624. fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
  625. cleanup:
  626. RegCloseKey (instance_key_handle);
  627. ++i;
  628. }
  629. RegCloseKey (adapter_key_handle);
  630. }
  631. return retval;
  632. }
  633. /**
  634. * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
  635. *
  636. * @param handle the handle to our tap device
  637. * @return TRUE if the version is sufficient, else FALSE
  638. */
  639. static BOOL
  640. check_tapw32_version (HANDLE handle)
  641. {
  642. ULONG version[3];
  643. DWORD len;
  644. memset (&(version), 0, sizeof (version));
  645. if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
  646. &version, sizeof (version),
  647. &version, sizeof (version), &len, NULL))
  648. fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
  649. (int) version[0],
  650. (int) version[1],
  651. (version[2] ? "(DEBUG)" : ""));
  652. if ((version[0] != TAP_WIN_MIN_MAJOR) ||
  653. (version[1] < TAP_WIN_MIN_MINOR )){
  654. fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
  655. TAP_WIN_MIN_MAJOR,
  656. TAP_WIN_MIN_MINOR);
  657. return FALSE;
  658. }
  659. return TRUE;
  660. }
  661. /**
  662. * Creates a tun-interface called dev;
  663. *
  664. * @return the fd to the tun or -1 on error
  665. */
  666. static HANDLE
  667. init_tun ()
  668. {
  669. char device_path[256];
  670. HANDLE handle;
  671. if (! setup_interface ())
  672. {
  673. errno = ENODEV;
  674. return INVALID_HANDLE_VALUE;
  675. }
  676. if (! resolve_interface_name ())
  677. {
  678. errno = ENODEV;
  679. return INVALID_HANDLE_VALUE;
  680. }
  681. /* Open Windows TAP-Windows adapter */
  682. snprintf (device_path, sizeof (device_path), "%s%s%s",
  683. USERMODEDEVICEDIR,
  684. device_guid,
  685. TAP_WIN_SUFFIX);
  686. handle = CreateFile (
  687. device_path,
  688. GENERIC_READ | GENERIC_WRITE,
  689. 0, /* was: FILE_SHARE_READ */
  690. 0,
  691. OPEN_EXISTING,
  692. FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
  693. 0
  694. );
  695. if (INVALID_HANDLE_VALUE == handle)
  696. {
  697. fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
  698. return handle;
  699. }
  700. /* get driver version info */
  701. if (! check_tapw32_version (handle))
  702. {
  703. CloseHandle (handle);
  704. return INVALID_HANDLE_VALUE;
  705. }
  706. /* TODO (opt?): get MTU-Size */
  707. fprintf (stderr, "DEBUG: successfully opened TAP device\n");
  708. return handle;
  709. }
  710. /**
  711. * Brings a TAP device up and sets it to connected state.
  712. *
  713. * @param handle the handle to our TAP device
  714. * @return True if the operation succeeded, else false
  715. */
  716. static BOOL
  717. tun_up (HANDLE handle)
  718. {
  719. ULONG status = TRUE;
  720. DWORD len;
  721. if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
  722. &status, sizeof (status),
  723. &status, sizeof (status), &len, NULL))
  724. {
  725. fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
  726. return FALSE;
  727. }
  728. /* Wait for the device to go UP, might take some time. */
  729. Sleep (TAP32_POSTUP_WAITTIME * 1000);
  730. fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
  731. return TRUE;
  732. }
  733. /**
  734. * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
  735. *
  736. * 1.
  737. * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
  738. * input handle. Then it goes into IOSTATE_QUEUED state.
  739. * In case the read succeeded instantly the input facility enters 3.
  740. *
  741. * 2.
  742. * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
  743. * If it has finished, go to state 3.
  744. * If it has failed, set IOSTATE_FAILED
  745. *
  746. * 3.
  747. * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
  748. * The input facility enters state IOSTATE_READY
  749. * The output facility enters state IOSTATE_READY
  750. * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
  751. *
  752. * IOSTATE_WAITING is reset by the output facility, once it has completed.
  753. *
  754. * @param input_facility input named pipe or file to work with.
  755. * @param output_facility output pipe or file to hand over data to.
  756. * @return false if an event reset was impossible (OS error), else true
  757. */
  758. static BOOL
  759. attempt_read_tap (struct io_facility * input_facility,
  760. struct io_facility * output_facility)
  761. {
  762. struct GNUNET_MessageHeader * hdr;
  763. unsigned short size;
  764. switch (input_facility->facility_state)
  765. {
  766. case IOSTATE_READY:
  767. {
  768. if (! ResetEvent (input_facility->overlapped.hEvent))
  769. {
  770. return FALSE;
  771. }
  772. input_facility->buffer_size = 0;
  773. /* Check how the task is handled */
  774. if (ReadFile (input_facility->handle,
  775. input_facility->buffer,
  776. sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
  777. &input_facility->buffer_size,
  778. &input_facility->overlapped))
  779. {/* async event processed immediately*/
  780. /* reset event manually*/
  781. if (! SetEvent (input_facility->overlapped.hEvent))
  782. return FALSE;
  783. fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
  784. /* we successfully read something from the TAP and now need to
  785. * send it our via STDOUT. Is that possible at the moment? */
  786. if ((IOSTATE_READY == output_facility->facility_state ||
  787. IOSTATE_WAITING == output_facility->facility_state)
  788. && (0 < input_facility->buffer_size))
  789. { /* hand over this buffers content and apply message header for gnunet */
  790. hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
  791. size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
  792. memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
  793. input_facility->buffer,
  794. input_facility->buffer_size);
  795. output_facility->buffer_size = size;
  796. hdr->size = htons (size);
  797. hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
  798. output_facility->facility_state = IOSTATE_READY;
  799. }
  800. else if (0 < input_facility->buffer_size)
  801. /* If we have have read our buffer, wait for our write-partner*/
  802. input_facility->facility_state = IOSTATE_WAITING;
  803. }
  804. else /* operation was either queued or failed*/
  805. {
  806. int err = GetLastError ();
  807. if (ERROR_IO_PENDING == err)
  808. { /* operation queued */
  809. input_facility->facility_state = IOSTATE_QUEUED;
  810. }
  811. else
  812. { /* error occurred, let the rest of the elements finish */
  813. input_facility->path_open = FALSE;
  814. input_facility->facility_state = IOSTATE_FAILED;
  815. if (IOSTATE_WAITING == output_facility->facility_state)
  816. output_facility->path_open = FALSE;
  817. fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
  818. }
  819. }
  820. }
  821. return TRUE;
  822. // We are queued and should check if the read has finished
  823. case IOSTATE_QUEUED:
  824. {
  825. // there was an operation going on already, check if that has completed now.
  826. if (GetOverlappedResult (input_facility->handle,
  827. &input_facility->overlapped,
  828. &input_facility->buffer_size,
  829. FALSE))
  830. {/* successful return for a queued operation */
  831. if (! ResetEvent (input_facility->overlapped.hEvent))
  832. return FALSE;
  833. fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
  834. /* we successfully read something from the TAP and now need to
  835. * send it our via STDOUT. Is that possible at the moment? */
  836. if ((IOSTATE_READY == output_facility->facility_state ||
  837. IOSTATE_WAITING == output_facility->facility_state)
  838. && 0 < input_facility->buffer_size)
  839. { /* hand over this buffers content and apply message header for gnunet */
  840. hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
  841. size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
  842. memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
  843. input_facility->buffer,
  844. input_facility->buffer_size);
  845. output_facility->buffer_size = size;
  846. hdr->size = htons(size);
  847. hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
  848. output_facility->facility_state = IOSTATE_READY;
  849. input_facility->facility_state = IOSTATE_READY;
  850. }
  851. else if (0 < input_facility->buffer_size)
  852. { /* If we have have read our buffer, wait for our write-partner*/
  853. input_facility->facility_state = IOSTATE_WAITING;
  854. // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
  855. }
  856. }
  857. else
  858. { /* operation still pending/queued or failed? */
  859. int err = GetLastError ();
  860. if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
  861. { /* error occurred, let the rest of the elements finish */
  862. input_facility->path_open = FALSE;
  863. input_facility->facility_state = IOSTATE_FAILED;
  864. if (IOSTATE_WAITING == output_facility->facility_state)
  865. output_facility->path_open = FALSE;
  866. fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
  867. }
  868. }
  869. }
  870. return TRUE;
  871. case IOSTATE_RESUME:
  872. hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
  873. size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
  874. memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
  875. input_facility->buffer,
  876. input_facility->buffer_size);
  877. output_facility->buffer_size = size;
  878. hdr->size = htons (size);
  879. hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
  880. output_facility->facility_state = IOSTATE_READY;
  881. input_facility->facility_state = IOSTATE_READY;
  882. return TRUE;
  883. default:
  884. return TRUE;
  885. }
  886. }
  887. /**
  888. * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
  889. *
  890. * 1.
  891. * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
  892. * input handle. Then it goes into IOSTATE_QUEUED state.
  893. * In case the read succeeded instantly the input facility enters 3.
  894. *
  895. * 2.
  896. * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
  897. * If it has finished, go to state 3.
  898. * If it has failed, set IOSTATE_FAILED
  899. *
  900. * 3.
  901. * If the facility is finished with ready
  902. * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
  903. * The input facility enters state IOSTATE_READY
  904. * The output facility enters state IOSTATE_READY
  905. * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
  906. *
  907. * IOSTATE_WAITING is reset by the output facility, once it has completed.
  908. *
  909. * @param input_facility input named pipe or file to work with.
  910. * @param output_facility output pipe or file to hand over data to.
  911. * @return false if an event reset was impossible (OS error), else true
  912. */
  913. static BOOL
  914. attempt_read_stdin (struct io_facility * input_facility,
  915. struct io_facility * output_facility)
  916. {
  917. struct GNUNET_MessageHeader * hdr;
  918. switch (input_facility->facility_state)
  919. {
  920. case IOSTATE_READY:
  921. {
  922. input_facility->buffer_size = 0;
  923. partial_read_iostate_ready:
  924. if (! ResetEvent (input_facility->overlapped.hEvent))
  925. return FALSE;
  926. /* Check how the task is handled */
  927. if (ReadFile (input_facility->handle,
  928. input_facility->buffer + input_facility->buffer_size,
  929. sizeof (input_facility->buffer) - input_facility->buffer_size,
  930. &input_facility->buffer_size_processed,
  931. &input_facility->overlapped))
  932. {/* async event processed immediately*/
  933. hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
  934. /* reset event manually*/
  935. if (!SetEvent (input_facility->overlapped.hEvent))
  936. return FALSE;
  937. fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
  938. input_facility->buffer_size += input_facility->buffer_size_processed;
  939. if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
  940. ntohs (hdr->size) > sizeof (input_facility->buffer))
  941. {
  942. fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
  943. input_facility->facility_state = IOSTATE_READY;
  944. return TRUE;
  945. }
  946. /* we got the a part of a packet */
  947. if (ntohs (hdr->size) > input_facility->buffer_size)
  948. goto partial_read_iostate_ready;
  949. /* have we read more than 0 bytes of payload? (sizeread > header)*/
  950. if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
  951. ((IOSTATE_READY == output_facility->facility_state) ||
  952. (IOSTATE_WAITING == output_facility->facility_state)))
  953. {/* we successfully read something from the TAP and now need to
  954. * send it our via STDOUT. Is that possible at the moment? */
  955. /* hand over this buffers content and strip gnunet message header */
  956. memcpy (output_facility->buffer,
  957. input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
  958. input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
  959. output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
  960. output_facility->facility_state = IOSTATE_READY;
  961. input_facility->facility_state = IOSTATE_READY;
  962. }
  963. else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
  964. /* If we have have read our buffer, wait for our write-partner*/
  965. input_facility->facility_state = IOSTATE_WAITING;
  966. else /* we read nothing */
  967. input_facility->facility_state = IOSTATE_READY;
  968. }
  969. else /* operation was either queued or failed*/
  970. {
  971. int err = GetLastError ();
  972. if (ERROR_IO_PENDING == err) /* operation queued */
  973. input_facility->facility_state = IOSTATE_QUEUED;
  974. else
  975. { /* error occurred, let the rest of the elements finish */
  976. input_facility->path_open = FALSE;
  977. input_facility->facility_state = IOSTATE_FAILED;
  978. if (IOSTATE_WAITING == output_facility->facility_state)
  979. output_facility->path_open = FALSE;
  980. fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
  981. }
  982. }
  983. }
  984. return TRUE;
  985. // We are queued and should check if the read has finished
  986. case IOSTATE_QUEUED:
  987. {
  988. // there was an operation going on already, check if that has completed now.
  989. if (GetOverlappedResult (input_facility->handle,
  990. &input_facility->overlapped,
  991. &input_facility->buffer_size_processed,
  992. FALSE))
  993. {/* successful return for a queued operation */
  994. hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
  995. if (! ResetEvent (input_facility->overlapped.hEvent))
  996. return FALSE;
  997. fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
  998. input_facility->buffer_size += input_facility->buffer_size_processed;
  999. if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
  1000. (ntohs (hdr->size) > sizeof (input_facility->buffer)))
  1001. {
  1002. fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
  1003. input_facility->facility_state = IOSTATE_READY;
  1004. return TRUE;
  1005. }
  1006. /* we got the a part of a packet */
  1007. if (ntohs (hdr->size) > input_facility->buffer_size );
  1008. goto partial_read_iostate_ready;
  1009. /* we successfully read something from the TAP and now need to
  1010. * send it our via STDOUT. Is that possible at the moment? */
  1011. if ((IOSTATE_READY == output_facility->facility_state ||
  1012. IOSTATE_WAITING == output_facility->facility_state)
  1013. && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
  1014. { /* hand over this buffers content and strip gnunet message header */
  1015. memcpy (output_facility->buffer,
  1016. input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
  1017. input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
  1018. output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
  1019. output_facility->facility_state = IOSTATE_READY;
  1020. input_facility->facility_state = IOSTATE_READY;
  1021. }
  1022. else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
  1023. input_facility->facility_state = IOSTATE_WAITING;
  1024. else
  1025. input_facility->facility_state = IOSTATE_READY;
  1026. }
  1027. else
  1028. { /* operation still pending/queued or failed? */
  1029. int err = GetLastError ();
  1030. if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
  1031. { /* error occurred, let the rest of the elements finish */
  1032. input_facility->path_open = FALSE;
  1033. input_facility->facility_state = IOSTATE_FAILED;
  1034. if (IOSTATE_WAITING == output_facility->facility_state)
  1035. output_facility->path_open = FALSE;
  1036. fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
  1037. }
  1038. }
  1039. }
  1040. return TRUE;
  1041. case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
  1042. memcpy (output_facility->buffer,
  1043. input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
  1044. input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
  1045. output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
  1046. output_facility->facility_state = IOSTATE_READY;
  1047. input_facility->facility_state = IOSTATE_READY;
  1048. return TRUE;
  1049. default:
  1050. return TRUE;
  1051. }
  1052. }
  1053. /**
  1054. * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
  1055. *
  1056. * TODO: high level description
  1057. *
  1058. * @param output_facility output pipe or file to hand over data to.
  1059. * @param input_facility input named pipe or file to work with.
  1060. * @return false if an event reset was impossible (OS error), else true
  1061. */
  1062. static BOOL
  1063. attempt_write (struct io_facility * output_facility,
  1064. struct io_facility * input_facility)
  1065. {
  1066. switch (output_facility->facility_state)
  1067. {
  1068. case IOSTATE_READY:
  1069. output_facility->buffer_size_written = 0;
  1070. continue_partial_write:
  1071. if (! ResetEvent (output_facility->overlapped.hEvent))
  1072. return FALSE;
  1073. /* Check how the task was handled */
  1074. if (WriteFile (output_facility->handle,
  1075. output_facility->buffer + output_facility->buffer_size_written,
  1076. output_facility->buffer_size - output_facility->buffer_size_written,
  1077. &output_facility->buffer_size_processed,
  1078. &output_facility->overlapped))
  1079. {/* async event processed immediately*/
  1080. fprintf (stderr, "DEBUG: write succeeded immediately\n");
  1081. output_facility->buffer_size_written += output_facility->buffer_size_processed;
  1082. /* reset event manually*/
  1083. if (! SetEvent (output_facility->overlapped.hEvent))
  1084. return FALSE;
  1085. /* partial write */
  1086. if (output_facility->buffer_size_written < output_facility->buffer_size)
  1087. goto continue_partial_write;
  1088. /* we are now waiting for our buffer to be filled*/
  1089. output_facility->facility_state = IOSTATE_WAITING;
  1090. /* we successfully wrote something and now need to reset our reader */
  1091. if (IOSTATE_WAITING == input_facility->facility_state)
  1092. input_facility->facility_state = IOSTATE_RESUME;
  1093. else if (IOSTATE_FAILED == input_facility->facility_state)
  1094. output_facility->path_open = FALSE;
  1095. }
  1096. else /* operation was either queued or failed*/
  1097. {
  1098. int err = GetLastError ();
  1099. if (ERROR_IO_PENDING == err)
  1100. { /* operation queued */
  1101. output_facility->facility_state = IOSTATE_QUEUED;
  1102. }
  1103. else
  1104. { /* error occurred, close this path */
  1105. output_facility->path_open = FALSE;
  1106. output_facility->facility_state = IOSTATE_FAILED;
  1107. fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
  1108. }
  1109. }
  1110. return TRUE;
  1111. case IOSTATE_QUEUED:
  1112. // there was an operation going on already, check if that has completed now.
  1113. if (GetOverlappedResult (output_facility->handle,
  1114. &output_facility->overlapped,
  1115. &output_facility->buffer_size_processed,
  1116. FALSE))
  1117. {/* successful return for a queued operation */
  1118. if (! ResetEvent (output_facility->overlapped.hEvent))
  1119. return FALSE;
  1120. fprintf (stderr, "DEBUG: write succeeded delayed\n");
  1121. output_facility->buffer_size_written += output_facility->buffer_size_processed;
  1122. /* partial write */
  1123. if (output_facility->buffer_size_written < output_facility->buffer_size)
  1124. goto continue_partial_write;
  1125. /* we are now waiting for our buffer to be filled*/
  1126. output_facility->facility_state = IOSTATE_WAITING;
  1127. /* we successfully wrote something and now need to reset our reader */
  1128. if (IOSTATE_WAITING == input_facility->facility_state)
  1129. input_facility->facility_state = IOSTATE_RESUME;
  1130. else if (IOSTATE_FAILED == input_facility->facility_state)
  1131. output_facility->path_open = FALSE;
  1132. }
  1133. else
  1134. { /* operation still pending/queued or failed? */
  1135. int err = GetLastError ();
  1136. if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
  1137. { /* error occurred, close this path */
  1138. output_facility->path_open = FALSE;
  1139. output_facility->facility_state = IOSTATE_FAILED;
  1140. fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
  1141. }
  1142. }
  1143. default:
  1144. return TRUE;
  1145. }
  1146. }
  1147. /**
  1148. * Initialize a overlapped structure
  1149. *
  1150. * @param elem the element to initilize
  1151. * @param initial_state the initial state for this instance
  1152. * @param signaled if the hEvent created should default to signaled or not
  1153. * @return true on success, else false
  1154. */
  1155. static BOOL
  1156. initialize_io_facility (struct io_facility * elem,
  1157. int initial_state,
  1158. BOOL signaled)
  1159. {
  1160. elem->path_open = TRUE;
  1161. elem->handle = INVALID_HANDLE_VALUE;
  1162. elem->facility_state = initial_state;
  1163. elem->buffer_size = 0;
  1164. elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
  1165. if (NULL == elem->overlapped.hEvent)
  1166. return FALSE;
  1167. return TRUE;
  1168. }
  1169. /**
  1170. * Start forwarding to and from the tunnel.
  1171. *
  1172. * @param tap_handle device handle for interacting with the Virtual interface
  1173. */
  1174. static void
  1175. run (HANDLE tap_handle)
  1176. {
  1177. /* IO-Facility for reading from our virtual interface */
  1178. struct io_facility tap_read;
  1179. /* IO-Facility for writing to our virtual interface */
  1180. struct io_facility tap_write;
  1181. /* IO-Facility for reading from stdin */
  1182. struct io_facility std_in;
  1183. /* IO-Facility for writing to stdout */
  1184. struct io_facility std_out;
  1185. HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
  1186. HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
  1187. /* tun up: */
  1188. /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
  1189. * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
  1190. *
  1191. * DHCP and such are all features we will never use in gnunet afaik.
  1192. * But for openvpn those are essential.
  1193. */
  1194. if ((privilege_testing) || (! tun_up (tap_handle)))
  1195. goto teardown_final;
  1196. /* Initialize our overlapped IO structures*/
  1197. if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
  1198. && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
  1199. && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
  1200. && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
  1201. goto teardown_final;
  1202. /* Handles for STDIN and STDOUT */
  1203. tap_read.handle = tap_handle;
  1204. tap_write.handle = tap_handle;
  1205. #ifdef DEBUG_TO_CONSOLE
  1206. /* Debug output to console STDIN/STDOUT*/
  1207. std_in.handle = parent_std_in_handle;
  1208. std_out.handle = parent_std_out_handle;
  1209. #else
  1210. fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
  1211. /*
  1212. * Find out the types of our handles.
  1213. * This part is a problem, because in windows we need to handle files,
  1214. * pipes and the console differently.
  1215. */
  1216. if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
  1217. (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
  1218. {
  1219. fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
  1220. goto teardown;
  1221. }
  1222. std_in.handle = ReOpenFile (parent_std_in_handle,
  1223. GENERIC_READ,
  1224. FILE_SHARE_WRITE | FILE_SHARE_READ,
  1225. FILE_FLAG_OVERLAPPED);
  1226. if (INVALID_HANDLE_VALUE == std_in.handle)
  1227. {
  1228. fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
  1229. goto teardown;
  1230. }
  1231. std_out.handle = ReOpenFile (parent_std_out_handle,
  1232. GENERIC_WRITE,
  1233. FILE_SHARE_READ,
  1234. FILE_FLAG_OVERLAPPED);
  1235. if (INVALID_HANDLE_VALUE == std_out.handle)
  1236. {
  1237. fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
  1238. goto teardown;
  1239. }
  1240. #endif
  1241. fprintf (stderr, "DEBUG: mainloop has begun\n");
  1242. while (std_out.path_open || tap_write.path_open)
  1243. {
  1244. /* perform READ from stdin if possible */
  1245. if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
  1246. break;
  1247. /* perform READ from tap if possible */
  1248. if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
  1249. break;
  1250. /* perform WRITE to tap if possible */
  1251. if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
  1252. break;
  1253. /* perform WRITE to STDOUT if possible */
  1254. if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
  1255. break;
  1256. }
  1257. fprintf (stderr, "DEBUG: teardown initiated\n");
  1258. teardown:
  1259. CancelIo (tap_handle);
  1260. CancelIo (std_in.handle);
  1261. CancelIo (std_out.handle);
  1262. teardown_final:
  1263. CloseHandle (tap_handle);
  1264. }
  1265. /**
  1266. * Open VPN tunnel interface.
  1267. *
  1268. * @param argc must be 6
  1269. * @param argv 0: binary name (gnunet-helper-vpn)
  1270. * [1: dryrun/testrun (does not execute mainloop)]
  1271. * 2: tunnel interface prefix (gnunet-vpn)
  1272. * 3: IPv6 address (::1), "-" to disable
  1273. * 4: IPv6 netmask length in bits (64), ignored if #2 is "-"
  1274. * 5: IPv4 address (1.2.3.4), "-" to disable
  1275. * 6: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
  1276. */
  1277. int
  1278. main (int argc, char **argv)
  1279. {
  1280. char hwid[LINE_LEN];
  1281. HANDLE handle;
  1282. int global_ret = 0;
  1283. BOOL have_ip4 = FALSE;
  1284. BOOL have_ip6 = FALSE;
  1285. if (argc > 1 && 0 == strcmp (argv[1], "-d")){
  1286. privilege_testing = TRUE;
  1287. fprintf (stderr,
  1288. "%s",
  1289. "DEBUG: Running binary in privilege testing mode.");
  1290. argv++;
  1291. argc--;
  1292. }
  1293. if (6 != argc)
  1294. {
  1295. fprintf (stderr,
  1296. "%s",
  1297. "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn [-d] <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
  1298. return 1;
  1299. }
  1300. strncpy (hwid, argv[1], LINE_LEN);
  1301. hwid[LINE_LEN - 1] = '\0';
  1302. /*
  1303. * We use our PID for finding/resolving the control-panel name of our virtual
  1304. * device. PIDs are (of course) unique at runtime, thus we can safely use it
  1305. * as additional hardware-id for our device.
  1306. */
  1307. snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
  1308. hwid,
  1309. _getpid ());
  1310. if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
  1311. {
  1312. fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
  1313. hwid,
  1314. argv[2],
  1315. argv[3],
  1316. argv[4],
  1317. argv[5]);
  1318. global_ret = -1;
  1319. goto cleanup;
  1320. }
  1321. fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
  1322. if (0 != strcmp (argv[2], "-"))
  1323. {
  1324. const char *address = argv[2];
  1325. long prefix_len = atol (argv[3]);
  1326. if ((prefix_len < 1) || (prefix_len > 127))
  1327. {
  1328. fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
  1329. global_ret = -1;
  1330. goto cleanup;
  1331. }
  1332. fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
  1333. if (0 != (global_ret = set_address6 (address, prefix_len)))
  1334. goto cleanup;
  1335. have_ip6 = TRUE;
  1336. }
  1337. if (0 != strcmp (argv[4], "-"))
  1338. {
  1339. const char *address = argv[4];
  1340. const char *mask = argv[5];
  1341. fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
  1342. if (0 != (global_ret = set_address4 (address, mask)))
  1343. goto cleanup;
  1344. have_ip4 = TRUE;
  1345. }
  1346. run (handle);
  1347. cleanup:
  1348. if (have_ip4)
  1349. {
  1350. const char *address = argv[4];
  1351. fprintf (stderr, "DEBUG: Removing IP4 address\n");
  1352. remove_address4 (address);
  1353. }
  1354. if (have_ip6)
  1355. {
  1356. const char *address = argv[2];
  1357. fprintf (stderr, "DEBUG: Removing IP6 address\n");
  1358. remove_address6 (address);
  1359. }
  1360. fprintf (stderr, "DEBUG: removing interface\n");
  1361. remove_interface ();
  1362. fprintf (stderr, "DEBUG: graceful exit completed\n");
  1363. return global_ret;
  1364. }