gnunet-helper-vpn-windows.c 51 KB

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