WindowsEthernetTap.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdint.h>
  29. #include <string.h>
  30. #include <WinSock2.h>
  31. #include <Windows.h>
  32. #include <tchar.h>
  33. #include <malloc.h>
  34. #include <winreg.h>
  35. #include <wchar.h>
  36. #include <ws2ipdef.h>
  37. #include <WS2tcpip.h>
  38. #include <IPHlpApi.h>
  39. #include <nldef.h>
  40. #include <netioapi.h>
  41. #include <atlbase.h>
  42. #include <netlistmgr.h>
  43. #include <nldef.h>
  44. #include <SetupAPI.h>
  45. #include <newdev.h>
  46. #include <cfgmgr32.h>
  47. #include <iostream>
  48. #include <set>
  49. #include "../node/Constants.hpp"
  50. #include "../node/Utils.hpp"
  51. #include "../node/Mutex.hpp"
  52. #include "WindowsEthernetTap.hpp"
  53. #include "OSUtils.hpp"
  54. #include "..\windows\TapDriver6\tap-windows.h"
  55. // Create a fake unused default route to force detection of network type on networks without gateways
  56. #define ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  57. // Function signatures of dynamically loaded functions, from newdev.h, setupapi.h, and cfgmgr32.h
  58. typedef BOOL (WINAPI *UpdateDriverForPlugAndPlayDevicesA_t)(_In_opt_ HWND hwndParent,_In_ LPCSTR HardwareId,_In_ LPCSTR FullInfPath,_In_ DWORD InstallFlags,_Out_opt_ PBOOL bRebootRequired);
  59. typedef BOOL (WINAPI *SetupDiGetINFClassA_t)(_In_ PCSTR InfName,_Out_ LPGUID ClassGuid,_Out_writes_(ClassNameSize) PSTR ClassName,_In_ DWORD ClassNameSize,_Out_opt_ PDWORD RequiredSize);
  60. typedef HDEVINFO (WINAPI *SetupDiCreateDeviceInfoList_t)(_In_opt_ CONST GUID *ClassGuid,_In_opt_ HWND hwndParent);
  61. typedef BOOL (WINAPI *SetupDiCreateDeviceInfoA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PCSTR DeviceName,_In_ CONST GUID *ClassGuid,_In_opt_ PCSTR DeviceDescription,_In_opt_ HWND hwndParent,_In_ DWORD CreationFlags,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  62. typedef BOOL (WINAPI *SetupDiSetDeviceRegistryPropertyA_t)(_In_ HDEVINFO DeviceInfoSet,_Inout_ PSP_DEVINFO_DATA DeviceInfoData,_In_ DWORD Property,_In_reads_bytes_opt_(PropertyBufferSize) CONST BYTE *PropertyBuffer,_In_ DWORD PropertyBufferSize);
  63. typedef BOOL (WINAPI *SetupDiCallClassInstaller_t)(_In_ DI_FUNCTION InstallFunction,_In_ HDEVINFO DeviceInfoSet,_In_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  64. typedef BOOL (WINAPI *SetupDiDestroyDeviceInfoList_t)(_In_ HDEVINFO DeviceInfoSet);
  65. typedef HDEVINFO (WINAPI *SetupDiGetClassDevsExA_t)(_In_opt_ CONST GUID *ClassGuid,_In_opt_ PCSTR Enumerator,_In_opt_ HWND hwndParent,_In_ DWORD Flags,_In_opt_ HDEVINFO DeviceInfoSet,_In_opt_ PCSTR MachineName,_Reserved_ PVOID Reserved);
  66. typedef BOOL (WINAPI *SetupDiOpenDeviceInfoA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PCSTR DeviceInstanceId,_In_opt_ HWND hwndParent,_In_ DWORD OpenFlags,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  67. typedef BOOL (WINAPI *SetupDiEnumDeviceInfo_t)(_In_ HDEVINFO DeviceInfoSet,_In_ DWORD MemberIndex,_Out_ PSP_DEVINFO_DATA DeviceInfoData);
  68. typedef BOOL (WINAPI *SetupDiSetClassInstallParamsA_t)(_In_ HDEVINFO DeviceInfoSet,_In_opt_ PSP_DEVINFO_DATA DeviceInfoData,_In_reads_bytes_opt_(ClassInstallParamsSize) PSP_CLASSINSTALL_HEADER ClassInstallParams,_In_ DWORD ClassInstallParamsSize);
  69. typedef CONFIGRET (WINAPI *CM_Get_Device_ID_ExA_t)(_In_ DEVINST dnDevInst,_Out_writes_(BufferLen) PSTR Buffer,_In_ ULONG BufferLen,_In_ ULONG ulFlags,_In_opt_ HMACHINE hMachine);
  70. typedef BOOL (WINAPI *SetupDiGetDeviceInstanceIdA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PSP_DEVINFO_DATA DeviceInfoData,_Out_writes_opt_(DeviceInstanceIdSize) PSTR DeviceInstanceId,_In_ DWORD DeviceInstanceIdSize,_Out_opt_ PDWORD RequiredSize);
  71. namespace ZeroTier {
  72. namespace {
  73. // Static/singleton class that when initialized loads a bunch of environment information and a few dynamically loaded DLLs
  74. class WindowsEthernetTapEnv
  75. {
  76. public:
  77. WindowsEthernetTapEnv()
  78. {
  79. #ifdef _WIN64
  80. is64Bit = TRUE;
  81. tapDriverPath = "\\tap-windows\\x64\\zttap300.inf";
  82. #else
  83. is64Bit = FALSE;
  84. IsWow64Process(GetCurrentProcess(),&is64Bit);
  85. if (is64Bit) {
  86. fprintf(stderr,"FATAL: you must use the 64-bit ZeroTier One service on 64-bit Windows systems\r\n");
  87. _exit(1);
  88. }
  89. tapDriverPath = "\\tap-windows\\x86\\zttap300.inf";
  90. #endif
  91. tapDriverName = "zttap300";
  92. setupApiMod = LoadLibraryA("setupapi.dll");
  93. if (!setupApiMod) {
  94. fprintf(stderr,"FATAL: unable to dynamically load setupapi.dll\r\n");
  95. _exit(1);
  96. }
  97. if (!(this->SetupDiGetINFClassA = (SetupDiGetINFClassA_t)GetProcAddress(setupApiMod,"SetupDiGetINFClassA"))) {
  98. fprintf(stderr,"FATAL: SetupDiGetINFClassA not found in setupapi.dll\r\n");
  99. _exit(1);
  100. }
  101. if (!(this->SetupDiCreateDeviceInfoList = (SetupDiCreateDeviceInfoList_t)GetProcAddress(setupApiMod,"SetupDiCreateDeviceInfoList"))) {
  102. fprintf(stderr,"FATAL: SetupDiCreateDeviceInfoList not found in setupapi.dll\r\n");
  103. _exit(1);
  104. }
  105. if (!(this->SetupDiCreateDeviceInfoA = (SetupDiCreateDeviceInfoA_t)GetProcAddress(setupApiMod,"SetupDiCreateDeviceInfoA"))) {
  106. fprintf(stderr,"FATAL: SetupDiCreateDeviceInfoA not found in setupapi.dll\r\n");
  107. _exit(1);
  108. }
  109. if (!(this->SetupDiSetDeviceRegistryPropertyA = (SetupDiSetDeviceRegistryPropertyA_t)GetProcAddress(setupApiMod,"SetupDiSetDeviceRegistryPropertyA"))) {
  110. fprintf(stderr,"FATAL: SetupDiSetDeviceRegistryPropertyA not found in setupapi.dll\r\n");
  111. _exit(1);
  112. }
  113. if (!(this->SetupDiCallClassInstaller = (SetupDiCallClassInstaller_t)GetProcAddress(setupApiMod,"SetupDiCallClassInstaller"))) {
  114. fprintf(stderr,"FATAL: SetupDiCallClassInstaller not found in setupapi.dll\r\n");
  115. _exit(1);
  116. }
  117. if (!(this->SetupDiDestroyDeviceInfoList = (SetupDiDestroyDeviceInfoList_t)GetProcAddress(setupApiMod,"SetupDiDestroyDeviceInfoList"))) {
  118. fprintf(stderr,"FATAL: SetupDiDestroyDeviceInfoList not found in setupapi.dll\r\n");
  119. _exit(1);
  120. }
  121. if (!(this->SetupDiGetClassDevsExA = (SetupDiGetClassDevsExA_t)GetProcAddress(setupApiMod,"SetupDiGetClassDevsExA"))) {
  122. fprintf(stderr,"FATAL: SetupDiGetClassDevsExA not found in setupapi.dll\r\n");
  123. _exit(1);
  124. }
  125. if (!(this->SetupDiOpenDeviceInfoA = (SetupDiOpenDeviceInfoA_t)GetProcAddress(setupApiMod,"SetupDiOpenDeviceInfoA"))) {
  126. fprintf(stderr,"FATAL: SetupDiOpenDeviceInfoA not found in setupapi.dll\r\n");
  127. _exit(1);
  128. }
  129. if (!(this->SetupDiEnumDeviceInfo = (SetupDiEnumDeviceInfo_t)GetProcAddress(setupApiMod,"SetupDiEnumDeviceInfo"))) {
  130. fprintf(stderr,"FATAL: SetupDiEnumDeviceInfo not found in setupapi.dll\r\n");
  131. _exit(1);
  132. }
  133. if (!(this->SetupDiSetClassInstallParamsA = (SetupDiSetClassInstallParamsA_t)GetProcAddress(setupApiMod,"SetupDiSetClassInstallParamsA"))) {
  134. fprintf(stderr,"FATAL: SetupDiSetClassInstallParamsA not found in setupapi.dll\r\n");
  135. _exit(1);
  136. }
  137. if (!(this->SetupDiGetDeviceInstanceIdA = (SetupDiGetDeviceInstanceIdA_t)GetProcAddress(setupApiMod,"SetupDiGetDeviceInstanceIdA"))) {
  138. fprintf(stderr,"FATAL: SetupDiGetDeviceInstanceIdA not found in setupapi.dll\r\n");
  139. _exit(1);
  140. }
  141. newDevMod = LoadLibraryA("newdev.dll");
  142. if (!newDevMod) {
  143. fprintf(stderr,"FATAL: unable to dynamically load newdev.dll\r\n");
  144. _exit(1);
  145. }
  146. if (!(this->UpdateDriverForPlugAndPlayDevicesA = (UpdateDriverForPlugAndPlayDevicesA_t)GetProcAddress(newDevMod,"UpdateDriverForPlugAndPlayDevicesA"))) {
  147. fprintf(stderr,"FATAL: UpdateDriverForPlugAndPlayDevicesA not found in newdev.dll\r\n");
  148. _exit(1);
  149. }
  150. cfgMgrMod = LoadLibraryA("cfgmgr32.dll");
  151. if (!cfgMgrMod) {
  152. fprintf(stderr,"FATAL: unable to dynamically load cfgmgr32.dll\r\n");
  153. _exit(1);
  154. }
  155. if (!(this->CM_Get_Device_ID_ExA = (CM_Get_Device_ID_ExA_t)GetProcAddress(cfgMgrMod,"CM_Get_Device_ID_ExA"))) {
  156. fprintf(stderr,"FATAL: CM_Get_Device_ID_ExA not found in cfgmgr32.dll\r\n");
  157. _exit(1);
  158. }
  159. }
  160. BOOL is64Bit; // is the system 64-bit, regardless of whether this binary is or not
  161. std::string tapDriverPath;
  162. std::string tapDriverName;
  163. UpdateDriverForPlugAndPlayDevicesA_t UpdateDriverForPlugAndPlayDevicesA;
  164. SetupDiGetINFClassA_t SetupDiGetINFClassA;
  165. SetupDiCreateDeviceInfoList_t SetupDiCreateDeviceInfoList;
  166. SetupDiCreateDeviceInfoA_t SetupDiCreateDeviceInfoA;
  167. SetupDiSetDeviceRegistryPropertyA_t SetupDiSetDeviceRegistryPropertyA;
  168. SetupDiCallClassInstaller_t SetupDiCallClassInstaller;
  169. SetupDiDestroyDeviceInfoList_t SetupDiDestroyDeviceInfoList;
  170. SetupDiGetClassDevsExA_t SetupDiGetClassDevsExA;
  171. SetupDiOpenDeviceInfoA_t SetupDiOpenDeviceInfoA;
  172. SetupDiEnumDeviceInfo_t SetupDiEnumDeviceInfo;
  173. SetupDiSetClassInstallParamsA_t SetupDiSetClassInstallParamsA;
  174. SetupDiGetDeviceInstanceIdA_t SetupDiGetDeviceInstanceIdA;
  175. CM_Get_Device_ID_ExA_t CM_Get_Device_ID_ExA;
  176. private:
  177. HMODULE setupApiMod;
  178. HMODULE newDevMod;
  179. HMODULE cfgMgrMod;
  180. };
  181. static const WindowsEthernetTapEnv WINENV;
  182. // Only create or delete devices one at a time
  183. static Mutex _systemTapInitLock;
  184. // Only perform installation or uninstallation options one at a time
  185. static Mutex _systemDeviceManagementLock;
  186. } // anonymous namespace
  187. std::string WindowsEthernetTap::addNewPersistentTapDevice(const char *pathToInf,std::string &deviceInstanceId)
  188. {
  189. Mutex::Lock _l(_systemDeviceManagementLock);
  190. GUID classGuid;
  191. char className[1024];
  192. if (!WINENV.SetupDiGetINFClassA(pathToInf,&classGuid,className,sizeof(className),(PDWORD)0)) {
  193. return std::string("SetupDiGetINFClassA() failed -- unable to read zttap driver INF file");
  194. }
  195. HDEVINFO deviceInfoSet = WINENV.SetupDiCreateDeviceInfoList(&classGuid,(HWND)0);
  196. if (deviceInfoSet == INVALID_HANDLE_VALUE) {
  197. return std::string("SetupDiCreateDeviceInfoList() failed");
  198. }
  199. SP_DEVINFO_DATA deviceInfoData;
  200. memset(&deviceInfoData,0,sizeof(deviceInfoData));
  201. deviceInfoData.cbSize = sizeof(deviceInfoData);
  202. if (!WINENV.SetupDiCreateDeviceInfoA(deviceInfoSet,className,&classGuid,(PCSTR)0,(HWND)0,DICD_GENERATE_ID,&deviceInfoData)) {
  203. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  204. return std::string("SetupDiCreateDeviceInfoA() failed");
  205. }
  206. if (!WINENV.SetupDiSetDeviceRegistryPropertyA(deviceInfoSet,&deviceInfoData,SPDRP_HARDWAREID,(const BYTE *)WINENV.tapDriverName.c_str(),(DWORD)(WINENV.tapDriverName.length() + 1))) {
  207. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  208. return std::string("SetupDiSetDeviceRegistryPropertyA() failed");
  209. }
  210. if (!WINENV.SetupDiCallClassInstaller(DIF_REGISTERDEVICE,deviceInfoSet,&deviceInfoData)) {
  211. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  212. return std::string("SetupDiCallClassInstaller(DIF_REGISTERDEVICE) failed");
  213. }
  214. // HACK: During upgrades, this can fail while the installer is still running. So make 60 attempts
  215. // with a 1s delay between each attempt.
  216. bool driverInstalled = false;
  217. for(int retryCounter=0;retryCounter<60;++retryCounter) {
  218. BOOL rebootRequired = FALSE;
  219. if (WINENV.UpdateDriverForPlugAndPlayDevicesA((HWND)0,WINENV.tapDriverName.c_str(),pathToInf,INSTALLFLAG_FORCE|INSTALLFLAG_NONINTERACTIVE,&rebootRequired)) {
  220. driverInstalled = true;
  221. break;
  222. } else Sleep(1000);
  223. }
  224. if (!driverInstalled) {
  225. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  226. return std::string("UpdateDriverForPlugAndPlayDevices() failed (made 60 attempts)");
  227. }
  228. char iidbuf[1024];
  229. DWORD iidReqSize = sizeof(iidbuf);
  230. if (WINENV.SetupDiGetDeviceInstanceIdA(deviceInfoSet,&deviceInfoData,iidbuf,sizeof(iidbuf),&iidReqSize)) {
  231. deviceInstanceId = iidbuf;
  232. } // failure here is not fatal since we only need this on Vista and 2008 -- other versions fill it into the registry automatically
  233. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  234. return std::string();
  235. }
  236. std::string WindowsEthernetTap::destroyAllLegacyPersistentTapDevices()
  237. {
  238. char subkeyName[1024];
  239. char subkeyClass[1024];
  240. char data[1024];
  241. std::set<std::string> instanceIdPathsToRemove;
  242. {
  243. HKEY nwAdapters;
  244. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  245. return std::string("Could not open registry key");
  246. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  247. DWORD type;
  248. DWORD dataLen;
  249. DWORD subkeyNameLen = sizeof(subkeyName);
  250. DWORD subkeyClassLen = sizeof(subkeyClass);
  251. FILETIME lastWriteTime;
  252. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  253. type = 0;
  254. dataLen = sizeof(data);
  255. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  256. data[dataLen] = '\0';
  257. if ((!strnicmp(data,"zttap",5))&&(WINENV.tapDriverName != data)) {
  258. std::string instanceIdPath;
  259. type = 0;
  260. dataLen = sizeof(data);
  261. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  262. instanceIdPath.assign(data,dataLen);
  263. if (instanceIdPath.length() != 0)
  264. instanceIdPathsToRemove.insert(instanceIdPath);
  265. }
  266. }
  267. } else break; // end of list or failure
  268. }
  269. RegCloseKey(nwAdapters);
  270. }
  271. std::string errlist;
  272. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  273. std::string err = deletePersistentTapDevice(iidp->c_str());
  274. if (err.length() > 0) {
  275. if (errlist.length() > 0)
  276. errlist.push_back(',');
  277. errlist.append(err);
  278. }
  279. }
  280. return errlist;
  281. }
  282. std::string WindowsEthernetTap::destroyAllPersistentTapDevices()
  283. {
  284. char subkeyName[1024];
  285. char subkeyClass[1024];
  286. char data[1024];
  287. std::set<std::string> instanceIdPathsToRemove;
  288. {
  289. HKEY nwAdapters;
  290. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  291. return std::string("Could not open registry key");
  292. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  293. DWORD type;
  294. DWORD dataLen;
  295. DWORD subkeyNameLen = sizeof(subkeyName);
  296. DWORD subkeyClassLen = sizeof(subkeyClass);
  297. FILETIME lastWriteTime;
  298. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  299. type = 0;
  300. dataLen = sizeof(data);
  301. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  302. data[dataLen] = '\0';
  303. if (!strnicmp(data,"zttap",5)) {
  304. std::string instanceIdPath;
  305. type = 0;
  306. dataLen = sizeof(data);
  307. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  308. instanceIdPath.assign(data,dataLen);
  309. if (instanceIdPath.length() != 0)
  310. instanceIdPathsToRemove.insert(instanceIdPath);
  311. }
  312. }
  313. } else break; // end of list or failure
  314. }
  315. RegCloseKey(nwAdapters);
  316. }
  317. std::string errlist;
  318. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  319. std::string err = deletePersistentTapDevice(iidp->c_str());
  320. if (err.length() > 0) {
  321. if (errlist.length() > 0)
  322. errlist.push_back(',');
  323. errlist.append(err);
  324. }
  325. }
  326. return errlist;
  327. }
  328. std::string WindowsEthernetTap::deletePersistentTapDevice(const char *instanceId)
  329. {
  330. char iid[256];
  331. SP_REMOVEDEVICE_PARAMS rmdParams;
  332. memset(&rmdParams,0,sizeof(rmdParams));
  333. rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  334. rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
  335. rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
  336. rmdParams.HwProfile = 0;
  337. Mutex::Lock _l(_systemDeviceManagementLock);
  338. HDEVINFO devInfo = WINENV.SetupDiGetClassDevsExA((const GUID *)0,(PCSTR)0,(HWND)0,DIGCF_ALLCLASSES,(HDEVINFO)0,(PCSTR)0,(PVOID)0);
  339. if (devInfo == INVALID_HANDLE_VALUE)
  340. return std::string("SetupDiGetClassDevsExA() failed");
  341. WINENV.SetupDiOpenDeviceInfoA(devInfo,instanceId,(HWND)0,0,(PSP_DEVINFO_DATA)0);
  342. SP_DEVINFO_DATA devInfoData;
  343. memset(&devInfoData,0,sizeof(devInfoData));
  344. devInfoData.cbSize = sizeof(devInfoData);
  345. for(DWORD devIndex=0;WINENV.SetupDiEnumDeviceInfo(devInfo,devIndex,&devInfoData);devIndex++) {
  346. if ((WINENV.CM_Get_Device_ID_ExA(devInfoData.DevInst,iid,sizeof(iid),0,(HMACHINE)0) == CR_SUCCESS)&&(!strcmp(iid,instanceId))) {
  347. if (!WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&rmdParams.ClassInstallHeader,sizeof(rmdParams))) {
  348. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  349. return std::string("SetupDiSetClassInstallParams() failed");
  350. }
  351. if (!WINENV.SetupDiCallClassInstaller(DIF_REMOVE,devInfo,&devInfoData)) {
  352. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  353. return std::string("SetupDiCallClassInstaller(DIF_REMOVE) failed");
  354. }
  355. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  356. return std::string();
  357. }
  358. }
  359. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  360. return std::string("instance ID not found");
  361. }
  362. bool WindowsEthernetTap::setPersistentTapDeviceState(const char *instanceId,bool enabled)
  363. {
  364. char iid[256];
  365. SP_PROPCHANGE_PARAMS params;
  366. Mutex::Lock _l(_systemDeviceManagementLock);
  367. HDEVINFO devInfo = WINENV.SetupDiGetClassDevsExA((const GUID *)0,(PCSTR)0,(HWND)0,DIGCF_ALLCLASSES,(HDEVINFO)0,(PCSTR)0,(PVOID)0);
  368. if (devInfo == INVALID_HANDLE_VALUE)
  369. return false;
  370. WINENV.SetupDiOpenDeviceInfoA(devInfo,instanceId,(HWND)0,0,(PSP_DEVINFO_DATA)0);
  371. SP_DEVINFO_DATA devInfoData;
  372. memset(&devInfoData,0,sizeof(devInfoData));
  373. devInfoData.cbSize = sizeof(devInfoData);
  374. for(DWORD devIndex=0;WINENV.SetupDiEnumDeviceInfo(devInfo,devIndex,&devInfoData);devIndex++) {
  375. if ((WINENV.CM_Get_Device_ID_ExA(devInfoData.DevInst,iid,sizeof(iid),0,(HMACHINE)0) == CR_SUCCESS)&&(!strcmp(iid,instanceId))) {
  376. memset(&params,0,sizeof(params));
  377. params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  378. params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
  379. params.StateChange = enabled ? DICS_ENABLE : DICS_DISABLE;
  380. params.Scope = DICS_FLAG_GLOBAL;
  381. params.HwProfile = 0;
  382. WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&params.ClassInstallHeader,sizeof(params));
  383. WINENV.SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,devInfo,&devInfoData);
  384. memset(&params,0,sizeof(params));
  385. params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  386. params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
  387. params.StateChange = enabled ? DICS_ENABLE : DICS_DISABLE;
  388. params.Scope = DICS_FLAG_CONFIGSPECIFIC;
  389. params.HwProfile = 0;
  390. WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&params.ClassInstallHeader,sizeof(params));
  391. WINENV.SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,devInfo,&devInfoData);
  392. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  393. return true;
  394. }
  395. }
  396. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  397. return false;
  398. }
  399. WindowsEthernetTap::WindowsEthernetTap(
  400. const char *hp,
  401. const MAC &mac,
  402. unsigned int mtu,
  403. unsigned int metric,
  404. uint64_t nwid,
  405. const char *friendlyName,
  406. void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  407. void *arg) :
  408. _handler(handler),
  409. _arg(arg),
  410. _mac(mac),
  411. _nwid(nwid),
  412. _mtu(mtu),
  413. _tap(INVALID_HANDLE_VALUE),
  414. _injectSemaphore(INVALID_HANDLE_VALUE),
  415. _pathToHelpers(hp),
  416. _run(true),
  417. _initialized(false),
  418. _enabled(true)
  419. {
  420. char subkeyName[1024];
  421. char subkeyClass[1024];
  422. char data[1024];
  423. char tag[24];
  424. // We "tag" registry entries with the network ID to identify persistent devices
  425. OSUtils::ztsnprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
  426. Mutex::Lock _l(_systemTapInitLock);
  427. HKEY nwAdapters;
  428. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  429. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  430. // Look for the tap instance that corresponds with this network
  431. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  432. DWORD type;
  433. DWORD dataLen;
  434. DWORD subkeyNameLen = sizeof(subkeyName);
  435. DWORD subkeyClassLen = sizeof(subkeyClass);
  436. FILETIME lastWriteTime;
  437. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  438. type = 0;
  439. dataLen = sizeof(data);
  440. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  441. data[dataLen] = (char)0;
  442. if (WINENV.tapDriverName == data) {
  443. std::string instanceId;
  444. type = 0;
  445. dataLen = sizeof(data);
  446. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  447. instanceId.assign(data,dataLen);
  448. std::string instanceIdPath;
  449. type = 0;
  450. dataLen = sizeof(data);
  451. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  452. instanceIdPath.assign(data,dataLen);
  453. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  454. type = 0;
  455. dataLen = sizeof(data);
  456. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  457. data[dataLen] = '\0';
  458. if (!strcmp(data,tag)) {
  459. _netCfgInstanceId = instanceId;
  460. _deviceInstanceId = instanceIdPath;
  461. _mySubkeyName = subkeyName;
  462. break; // found it!
  463. }
  464. }
  465. }
  466. }
  467. }
  468. } else break; // no more subkeys or error occurred enumerating them
  469. }
  470. // If there is no device, try to create one
  471. bool creatingNewDevice = (_netCfgInstanceId.length() == 0);
  472. std::string newDeviceInstanceId;
  473. if (creatingNewDevice) {
  474. for(int getNewAttemptCounter=0;getNewAttemptCounter<2;++getNewAttemptCounter) {
  475. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  476. DWORD type;
  477. DWORD dataLen;
  478. DWORD subkeyNameLen = sizeof(subkeyName);
  479. DWORD subkeyClassLen = sizeof(subkeyClass);
  480. FILETIME lastWriteTime;
  481. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  482. type = 0;
  483. dataLen = sizeof(data);
  484. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  485. data[dataLen] = '\0';
  486. if (WINENV.tapDriverName == data) {
  487. type = 0;
  488. dataLen = sizeof(data);
  489. if ((RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) != ERROR_SUCCESS)||(dataLen <= 0)) {
  490. type = 0;
  491. dataLen = sizeof(data);
  492. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  493. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  494. _netCfgInstanceId.assign(data,dataLen);
  495. type = 0;
  496. dataLen = sizeof(data);
  497. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  498. _deviceInstanceId.assign(data,dataLen);
  499. _mySubkeyName = subkeyName;
  500. // Disable DHCP by default on new devices
  501. HKEY tcpIpInterfaces;
  502. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  503. DWORD enable = 0;
  504. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  505. RegCloseKey(tcpIpInterfaces);
  506. }
  507. break; // found an unused zttap device
  508. }
  509. }
  510. }
  511. }
  512. } else break; // no more keys or error occurred
  513. }
  514. if (_netCfgInstanceId.length() > 0) {
  515. break; // found an unused zttap device
  516. } else {
  517. // no unused zttap devices, so create one
  518. std::string errm = addNewPersistentTapDevice((std::string(_pathToHelpers) + WINENV.tapDriverPath).c_str(),newDeviceInstanceId);
  519. if (errm.length() > 0)
  520. throw std::runtime_error(std::string("unable to create new device instance: ")+errm);
  521. }
  522. }
  523. }
  524. if (_netCfgInstanceId.length() > 0) {
  525. char tmps[64];
  526. unsigned int tmpsl = OSUtils::ztsnprintf(tmps,sizeof(tmps),"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X",(unsigned int)mac[0],(unsigned int)mac[1],(unsigned int)mac[2],(unsigned int)mac[3],(unsigned int)mac[4],(unsigned int)mac[5]) + 1;
  527. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  528. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  529. tmpsl = OSUtils::ztsnprintf(tmps, sizeof(tmps), "%d", mtu);
  530. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"MTU",REG_SZ,tmps,tmpsl);
  531. DWORD tmp = 0;
  532. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"*NdisDeviceType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  533. tmp = IF_TYPE_ETHERNET_CSMACD;
  534. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"*IfType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  535. if (creatingNewDevice) {
  536. // Vista/2008 does not set this
  537. if (newDeviceInstanceId.length() > 0)
  538. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"DeviceInstanceID",REG_SZ,newDeviceInstanceId.c_str(),(DWORD)newDeviceInstanceId.length());
  539. // Set EnableDHCP to 0 by default on new devices
  540. tmp = 0;
  541. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  542. }
  543. RegCloseKey(nwAdapters);
  544. } else {
  545. RegCloseKey(nwAdapters);
  546. throw std::runtime_error("unable to find or create tap adapter");
  547. }
  548. {
  549. char nobraces[128]; // strip braces from GUID before converting it, because Windows
  550. const char *nbtmp1 = _netCfgInstanceId.c_str();
  551. char *nbtmp2 = nobraces;
  552. while (*nbtmp1) {
  553. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  554. *nbtmp2++ = *nbtmp1;
  555. ++nbtmp1;
  556. }
  557. *nbtmp2 = (char)0;
  558. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  559. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  560. }
  561. // Get the LUID, which is one of like four fucking ways to refer to a network device in Windows
  562. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  563. throw std::runtime_error("unable to convert device interface GUID to LUID");
  564. //_initialized = true;
  565. if (friendlyName)
  566. setFriendlyName(friendlyName);
  567. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  568. _thread = Thread::start(this);
  569. }
  570. WindowsEthernetTap::~WindowsEthernetTap()
  571. {
  572. _run = false;
  573. ReleaseSemaphore(_injectSemaphore,1,NULL);
  574. Thread::join(_thread);
  575. CloseHandle(_injectSemaphore);
  576. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  577. }
  578. void WindowsEthernetTap::setEnabled(bool en)
  579. {
  580. _enabled = en;
  581. }
  582. bool WindowsEthernetTap::enabled() const
  583. {
  584. return _enabled;
  585. }
  586. bool WindowsEthernetTap::addIp(const InetAddress &ip)
  587. {
  588. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  589. return false;
  590. Mutex::Lock _l(_assignedIps_m);
  591. if (std::find(_assignedIps.begin(),_assignedIps.end(),ip) != _assignedIps.end())
  592. return true;
  593. _assignedIps.push_back(ip);
  594. _syncIps();
  595. return true;
  596. }
  597. bool WindowsEthernetTap::removeIp(const InetAddress &ip)
  598. {
  599. if (ip.isV6())
  600. return true;
  601. {
  602. Mutex::Lock _l(_assignedIps_m);
  603. std::vector<InetAddress>::iterator aip(std::find(_assignedIps.begin(),_assignedIps.end(),ip));
  604. if (aip != _assignedIps.end())
  605. _assignedIps.erase(aip);
  606. }
  607. if (!_initialized)
  608. return false;
  609. try {
  610. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  611. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  612. if ((ipt)&&(ipt->NumEntries > 0)) {
  613. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  614. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  615. InetAddress addr;
  616. switch(ipt->Table[i].Address.si_family) {
  617. case AF_INET:
  618. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  619. break;
  620. case AF_INET6:
  621. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  622. if (addr.ipScope() == InetAddress::IP_SCOPE_LINK_LOCAL)
  623. continue; // can't remove link-local IPv6 addresses
  624. break;
  625. }
  626. if (addr == ip) {
  627. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  628. FreeMibTable(ipt);
  629. if (ip.isV4()) {
  630. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  631. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  632. char ipbuf[64];
  633. std::string ipstr(ip.toIpString(ipbuf));
  634. for (std::vector<std::string>::iterator rip(regIps.begin()), rm(regSubnetMasks.begin()); ((rip != regIps.end()) && (rm != regSubnetMasks.end())); ++rip, ++rm) {
  635. if (*rip == ipstr) {
  636. regIps.erase(rip);
  637. regSubnetMasks.erase(rm);
  638. _setRegistryIPv4Value("IPAddress", regIps);
  639. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  640. break;
  641. }
  642. }
  643. }
  644. return true;
  645. }
  646. }
  647. }
  648. }
  649. FreeMibTable((PVOID)ipt);
  650. }
  651. } catch ( ... ) {}
  652. return false;
  653. }
  654. std::vector<InetAddress> WindowsEthernetTap::ips() const
  655. {
  656. static const InetAddress linkLocalLoopback("fe80::1/64"); // what is this and why does Windows assign it?
  657. std::vector<InetAddress> addrs;
  658. if (!_initialized)
  659. return addrs;
  660. try {
  661. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  662. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  663. if ((ipt)&&(ipt->NumEntries > 0)) {
  664. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  665. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  666. switch(ipt->Table[i].Address.si_family) {
  667. case AF_INET: {
  668. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  669. if (ip != InetAddress::LO4)
  670. addrs.push_back(ip);
  671. } break;
  672. case AF_INET6: {
  673. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  674. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  675. addrs.push_back(ip);
  676. } break;
  677. }
  678. }
  679. }
  680. }
  681. FreeMibTable(ipt);
  682. }
  683. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  684. std::sort(addrs.begin(),addrs.end());
  685. addrs.erase(std::unique(addrs.begin(),addrs.end()),addrs.end());
  686. return addrs;
  687. }
  688. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  689. {
  690. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > _mtu))
  691. return;
  692. Mutex::Lock _l(_injectPending_m);
  693. _injectPending.push( std::pair<Array<char,ZT_MAX_MTU + 32>,unsigned int>(Array<char,ZT_MAX_MTU + 32>(),len + 14) );
  694. char *d = _injectPending.back().first.data;
  695. to.copyTo(d,6);
  696. from.copyTo(d + 6,6);
  697. d[12] = (char)((etherType >> 8) & 0xff);
  698. d[13] = (char)(etherType & 0xff);
  699. memcpy(d + 14,data,len);
  700. ReleaseSemaphore(_injectSemaphore,1,NULL);
  701. }
  702. std::string WindowsEthernetTap::deviceName() const
  703. {
  704. char tmp[1024];
  705. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  706. return std::string("[ConvertInterfaceLuidToName() failed]");
  707. return std::string(tmp);
  708. }
  709. void WindowsEthernetTap::setFriendlyName(const char *dn)
  710. {
  711. if (!_initialized)
  712. return;
  713. HKEY ifp;
  714. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,(std::string("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\") + _netCfgInstanceId).c_str(),0,KEY_READ|KEY_WRITE,&ifp) == ERROR_SUCCESS) {
  715. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  716. RegCloseKey(ifp);
  717. }
  718. }
  719. void WindowsEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  720. {
  721. if (!_initialized)
  722. return;
  723. HANDLE t = _tap;
  724. if (t == INVALID_HANDLE_VALUE)
  725. return;
  726. std::vector<MulticastGroup> newGroups;
  727. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  728. // level... something Windows does not seem to expose ordinarily. This lets
  729. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  730. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  731. DWORD bytesReturned = 0;
  732. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  733. if ((bytesReturned > 0)&&(bytesReturned <= TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE)) { // sanity check
  734. MAC mac;
  735. DWORD i = 0;
  736. while ((i + 6) <= bytesReturned) {
  737. mac.setTo(mcastbuf + i,6);
  738. i += 6;
  739. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  740. // exclude the nulls that may be returned or any other junk Windows puts in there
  741. newGroups.push_back(MulticastGroup(mac,0));
  742. }
  743. }
  744. }
  745. }
  746. std::vector<InetAddress> allIps(ips());
  747. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  748. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  749. std::sort(newGroups.begin(),newGroups.end());
  750. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  751. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  752. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  753. added.push_back(*m);
  754. }
  755. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  756. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  757. removed.push_back(*m);
  758. }
  759. _multicastGroups.swap(newGroups);
  760. }
  761. void WindowsEthernetTap::setMtu(unsigned int mtu)
  762. {
  763. if (mtu != _mtu) {
  764. _mtu = mtu;
  765. HKEY nwAdapters;
  766. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}", 0, KEY_READ | KEY_WRITE, &nwAdapters) == ERROR_SUCCESS) {
  767. char tmps[64];
  768. unsigned int tmpsl = OSUtils::ztsnprintf(tmps, sizeof(tmps), "%d", mtu);
  769. RegSetKeyValueA(nwAdapters, _mySubkeyName.c_str(), "MTU", REG_SZ, tmps, tmpsl);
  770. RegCloseKey(nwAdapters);
  771. }
  772. }
  773. }
  774. NET_IFINDEX WindowsEthernetTap::interfaceIndex() const
  775. {
  776. NET_IFINDEX idx = -1;
  777. if (ConvertInterfaceLuidToIndex(&_deviceLuid,&idx) == NO_ERROR)
  778. return idx;
  779. return -1;
  780. }
  781. void WindowsEthernetTap::threadMain()
  782. throw()
  783. {
  784. char tapReadBuf[ZT_MAX_MTU + 32];
  785. char tapPath[128];
  786. HANDLE wait4[3];
  787. OVERLAPPED tapOvlRead,tapOvlWrite;
  788. OSUtils::ztsnprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  789. try {
  790. while (_run) {
  791. // Because Windows
  792. Sleep(250);
  793. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  794. Sleep(250);
  795. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  796. Sleep(250);
  797. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  798. Sleep(250);
  799. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  800. Sleep(250);
  801. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  802. if (_tap == INVALID_HANDLE_VALUE) {
  803. Sleep(250);
  804. continue;
  805. }
  806. {
  807. uint32_t tmpi = 1;
  808. DWORD bytesReturned = 0;
  809. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  810. }
  811. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  812. {
  813. /* This inserts a fake default route and a fake ARP entry, forcing
  814. * Windows to detect this as a "real" network and apply proper
  815. * firewall rules.
  816. *
  817. * This hack is completely stupid, but Windows made me do it
  818. * by being broken and insane.
  819. *
  820. * Background: Windows tries to detect its network location by
  821. * matching it to the ARP address of the default route. Networks
  822. * without default routes are "unidentified networks" and cannot
  823. * have their firewall classification changed by the user (easily).
  824. *
  825. * Yes, you read that right.
  826. *
  827. * The common workaround is to set *NdisDeviceType to 1, which
  828. * totally disables all Windows firewall functionality. This is
  829. * the answer you'll find on most forums for things like OpenVPN.
  830. *
  831. * Yes, you read that right.
  832. *
  833. * The default route workaround is also known, but for this to
  834. * work there must be a known default IP that resolves to a known
  835. * ARP address. This works for an OpenVPN tunnel, but not here
  836. * because this isn't a tunnel. It's a mesh. There is no "other
  837. * end," or any other known always on IP.
  838. *
  839. * So let's make a fake one and shove it in there along with its
  840. * fake static ARP entry. Also makes it instant-on and static.
  841. *
  842. * We'll have to see what DHCP does with this. In the future we
  843. * probably will not want to do this on DHCP-enabled networks, so
  844. * when we enable DHCP we will go in and yank this wacko hacko from
  845. * the routing table before doing so.
  846. *
  847. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  848. const uint32_t fakeIp = htonl(0x19fffffe); // 25.255.255.254 -- unrouted IPv4 block
  849. for(int i=0;i<8;++i) {
  850. MIB_IPNET_ROW2 ipnr;
  851. memset(&ipnr,0,sizeof(ipnr));
  852. ipnr.Address.si_family = AF_INET;
  853. ipnr.Address.Ipv4.sin_addr.s_addr = fakeIp;
  854. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  855. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  856. ipnr.PhysicalAddress[1] = 0x00;
  857. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  858. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  859. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  860. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  861. ipnr.PhysicalAddressLength = 6;
  862. ipnr.State = NlnsPermanent;
  863. ipnr.IsRouter = 1;
  864. ipnr.IsUnreachable = 0;
  865. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  866. ipnr.ReachabilityTime.LastUnreachable = 1;
  867. DWORD result = CreateIpNetEntry2(&ipnr);
  868. if (result != NO_ERROR)
  869. Sleep(250);
  870. else break;
  871. }
  872. for(int i=0;i<8;++i) {
  873. MIB_IPFORWARD_ROW2 nr;
  874. memset(&nr,0,sizeof(nr));
  875. InitializeIpForwardEntry(&nr);
  876. nr.InterfaceLuid.Value = _deviceLuid.Value;
  877. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  878. nr.NextHop.si_family = AF_INET;
  879. nr.NextHop.Ipv4.sin_addr.s_addr = fakeIp;
  880. nr.Metric = 9999; // do not use as real default route
  881. nr.Protocol = MIB_IPPROTO_NETMGMT;
  882. DWORD result = CreateIpForwardEntry2(&nr);
  883. if (result != NO_ERROR)
  884. Sleep(250);
  885. else break;
  886. }
  887. }
  888. #endif
  889. // Assign or re-assign any should-be-assigned IPs in case we have restarted
  890. {
  891. Mutex::Lock _l(_assignedIps_m);
  892. _syncIps();
  893. }
  894. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  895. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  896. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  897. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  898. wait4[0] = _injectSemaphore;
  899. wait4[1] = tapOvlRead.hEvent;
  900. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  901. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  902. bool writeInProgress = false;
  903. ULONGLONG timeOfLastBorkCheck = GetTickCount64();
  904. _initialized = true;
  905. unsigned int oldmtu = _mtu;
  906. while (_run) {
  907. DWORD waitResult = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,2500,TRUE);
  908. if (!_run) break; // will also break outer while(_run) since _run is false
  909. // Check for changes in MTU and break to restart tap device to reconfigure in this case
  910. if (_mtu != oldmtu)
  911. break;
  912. // Check for issues with adapter and close/reopen if any are detected. This
  913. // check fixes a while boatload of Windows adapter 'coma' issues after
  914. // sleep/wake and when adapters are added/removed. Basically if the tap
  915. // device is borked, whack it.
  916. {
  917. ULONGLONG tc = GetTickCount64();
  918. if ((tc - timeOfLastBorkCheck) >= 2500) {
  919. timeOfLastBorkCheck = tc;
  920. char aabuf[16384];
  921. ULONG aalen = sizeof(aabuf);
  922. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_UNICAST|GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER|GAA_FLAG_SKIP_FRIENDLY_NAME,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  923. bool isBorked = false;
  924. PIP_ADAPTER_ADDRESSES aa = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  925. while (aa) {
  926. if (_deviceLuid.Value == aa->Luid.Value) {
  927. isBorked = (aa->OperStatus != IfOperStatusUp);
  928. break;
  929. }
  930. aa = aa->Next;
  931. }
  932. if (isBorked) {
  933. // Close and reopen tap device if there's an issue (outer loop)
  934. break;
  935. }
  936. }
  937. }
  938. }
  939. if ((waitResult == WAIT_TIMEOUT)||(waitResult == WAIT_FAILED)) {
  940. Sleep(250); // guard against spinning under some conditions
  941. continue;
  942. }
  943. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  944. DWORD bytesRead = 0;
  945. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  946. if ((bytesRead > 14)&&(_enabled)) {
  947. MAC to(tapReadBuf,6);
  948. MAC from(tapReadBuf + 6,6);
  949. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  950. try {
  951. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,tapReadBuf + 14,bytesRead - 14);
  952. } catch ( ... ) {} // handlers should not throw
  953. }
  954. }
  955. ReadFile(_tap,tapReadBuf,ZT_MAX_MTU + 32,NULL,&tapOvlRead);
  956. }
  957. if (writeInProgress) {
  958. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  959. writeInProgress = false;
  960. _injectPending_m.lock();
  961. _injectPending.pop();
  962. } else continue; // still writing, so skip code below and wait
  963. } else _injectPending_m.lock();
  964. if (!_injectPending.empty()) {
  965. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  966. writeInProgress = true;
  967. }
  968. _injectPending_m.unlock();
  969. }
  970. CancelIo(_tap);
  971. CloseHandle(tapOvlRead.hEvent);
  972. CloseHandle(tapOvlWrite.hEvent);
  973. CloseHandle(_tap);
  974. _tap = INVALID_HANDLE_VALUE;
  975. // We will restart and re-open the tap unless _run == false
  976. }
  977. } catch ( ... ) {} // catch unexpected exceptions -- this should not happen but would prevent program crash or other weird issues since threads should not throw
  978. }
  979. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  980. {
  981. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  982. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  983. throw std::runtime_error("GetIfTable2Ex() failed");
  984. if (ift->NumEntries > 0) {
  985. for(ULONG i=0;i<ift->NumEntries;++i) {
  986. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  987. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  988. FreeMibTable(ift);
  989. return idx;
  990. }
  991. }
  992. }
  993. FreeMibTable(&ift);
  994. throw std::runtime_error("interface not found");
  995. }
  996. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  997. {
  998. std::vector<std::string> value;
  999. HKEY tcpIpInterfaces;
  1000. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  1001. char buf[16384];
  1002. DWORD len = sizeof(buf);
  1003. DWORD kt = REG_MULTI_SZ;
  1004. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  1005. switch(kt) {
  1006. case REG_SZ:
  1007. if (len > 0)
  1008. value.push_back(std::string(buf));
  1009. break;
  1010. case REG_MULTI_SZ: {
  1011. for(DWORD k=0,s=0;k<len;++k) {
  1012. if (!buf[k]) {
  1013. if (s < k) {
  1014. value.push_back(std::string(buf + s));
  1015. s = k + 1;
  1016. } else break;
  1017. }
  1018. }
  1019. } break;
  1020. }
  1021. }
  1022. RegCloseKey(tcpIpInterfaces);
  1023. }
  1024. return value;
  1025. }
  1026. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  1027. {
  1028. std::string regMulti;
  1029. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  1030. regMulti.append(*s);
  1031. regMulti.push_back((char)0);
  1032. }
  1033. HKEY tcpIpInterfaces;
  1034. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  1035. if (regMulti.length() > 0) {
  1036. regMulti.push_back((char)0);
  1037. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  1038. } else {
  1039. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  1040. }
  1041. RegCloseKey(tcpIpInterfaces);
  1042. }
  1043. }
  1044. void WindowsEthernetTap::_syncIps()
  1045. {
  1046. // assumes _assignedIps_m is locked
  1047. if (!_initialized)
  1048. return;
  1049. std::vector<InetAddress> haveIps(ips());
  1050. for(std::vector<InetAddress>::const_iterator aip(_assignedIps.begin());aip!=_assignedIps.end();++aip) {
  1051. if (std::find(haveIps.begin(),haveIps.end(),*aip) == haveIps.end()) {
  1052. MIB_UNICASTIPADDRESS_ROW ipr;
  1053. InitializeUnicastIpAddressEntry(&ipr);
  1054. if (aip->isV4()) {
  1055. ipr.Address.Ipv4.sin_family = AF_INET;
  1056. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)aip->rawIpData());
  1057. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1058. if (ipr.OnLinkPrefixLength >= 32)
  1059. continue;
  1060. } else if (aip->isV6()) {
  1061. ipr.Address.Ipv6.sin6_family = AF_INET6;
  1062. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,aip->rawIpData(),16);
  1063. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1064. if (ipr.OnLinkPrefixLength >= 128)
  1065. continue;
  1066. } else continue;
  1067. ipr.PrefixOrigin = IpPrefixOriginManual;
  1068. ipr.SuffixOrigin = IpSuffixOriginManual;
  1069. ipr.ValidLifetime = 0xffffffff;
  1070. ipr.PreferredLifetime = 0xffffffff;
  1071. ipr.InterfaceLuid = _deviceLuid;
  1072. ipr.InterfaceIndex = _getDeviceIndex();
  1073. CreateUnicastIpAddressEntry(&ipr);
  1074. }
  1075. if (aip->isV4()) {
  1076. char ipbuf[64];
  1077. std::string ipStr(aip->toIpString(ipbuf));
  1078. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  1079. if (std::find(regIps.begin(), regIps.end(), ipStr) == regIps.end()) {
  1080. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  1081. regIps.push_back(ipStr);
  1082. regSubnetMasks.push_back(aip->netmask().toIpString(ipbuf));
  1083. _setRegistryIPv4Value("IPAddress", regIps);
  1084. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. } // namespace ZeroTier