WindowsEthernetTap.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "Constants.hpp"
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <string.h>
  32. #include <WinSock2.h>
  33. #include <Windows.h>
  34. #include <tchar.h>
  35. #include <winreg.h>
  36. #include <wchar.h>
  37. #include <ws2ipdef.h>
  38. #include <WS2tcpip.h>
  39. #include <IPHlpApi.h>
  40. #include <nldef.h>
  41. #include <netioapi.h>
  42. #include "EthernetTap.hpp"
  43. #include "WindowsEthernetTap.hpp"
  44. #include "Logger.hpp"
  45. #include "RuntimeEnvironment.hpp"
  46. #include "Utils.hpp"
  47. #include "Mutex.hpp"
  48. #include "..\windows\TapDriver\tap-windows.h"
  49. // ff:ff:ff:ff:ff:ff with no ADI
  50. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  51. namespace ZeroTier {
  52. // Helper function to get an adapter's LUID and index from its GUID. The LUID is
  53. // constant but the index can change, so go ahead and just look them both up by
  54. // the GUID which is constant. (The GUID is the instance ID in the registry.)
  55. static inline std::pair<NET_LUID,NET_IFINDEX> _findAdapterByGuid(const GUID &guid)
  56. throw(std::runtime_error)
  57. {
  58. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  59. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  60. throw std::runtime_error("GetIfTable2Ex() failed");
  61. for(ULONG i=0;i<ift->NumEntries;++i) {
  62. if (ift->Table[i].InterfaceGuid == guid) {
  63. std::pair<NET_LUID,NET_IFINDEX> tmp(ift->Table[i].InterfaceLuid,ift->Table[i].InterfaceIndex);
  64. FreeMibTable(ift);
  65. return tmp;
  66. }
  67. }
  68. FreeMibTable(&ift);
  69. throw std::runtime_error("interface not found");
  70. }
  71. // Only create or manipulate devices one at a time to avoid weird driver layer demons
  72. static Mutex _systemTapInitLock;
  73. // Compute some basic environment stuff on startup
  74. class _WinSysEnv
  75. {
  76. public:
  77. _WinSysEnv()
  78. {
  79. #ifdef _WIN64
  80. is64Bit = TRUE;
  81. devcon = "\\devcon_x64.exe";
  82. tapDriver = "\\tap-windows\\x64\\zttap200.inf";
  83. #else
  84. is64Bit = FALSE;
  85. IsWow64Process(GetCurrentProcess(),&is64Bit);
  86. devcon = ((is64Bit == TRUE) ? "\\devcon_x64.exe" : "\\devcon_x86.exe");
  87. tapDriver = ((is64Bit == TRUE) ? "\\tap-windows\\x64\\zttap200.inf" : "\\tap-windows\\x86\\zttap200.inf");
  88. #endif
  89. }
  90. BOOL is64Bit;
  91. const char *devcon;
  92. const char *tapDriver;
  93. };
  94. static const _WinSysEnv _winEnv;
  95. static bool _disableTapDevice(const RuntimeEnvironment *_r,const std::string deviceInstanceId)
  96. {
  97. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  98. if (devconLog != INVALID_HANDLE_VALUE)
  99. SetFilePointer(devconLog,0,0,FILE_END);
  100. STARTUPINFOA startupInfo;
  101. startupInfo.cb = sizeof(startupInfo);
  102. if (devconLog != INVALID_HANDLE_VALUE) {
  103. startupInfo.hStdOutput = devconLog;
  104. startupInfo.hStdError = devconLog;
  105. }
  106. PROCESS_INFORMATION processInfo;
  107. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  108. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  109. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" disable @" + deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  110. if (devconLog != INVALID_HANDLE_VALUE)
  111. CloseHandle(devconLog);
  112. return false;
  113. }
  114. WaitForSingleObject(processInfo.hProcess,INFINITE);
  115. CloseHandle(processInfo.hProcess);
  116. CloseHandle(processInfo.hThread);
  117. if (devconLog != INVALID_HANDLE_VALUE)
  118. CloseHandle(devconLog);
  119. return true;
  120. }
  121. static bool _enableTapDevice(const RuntimeEnvironment *_r,const std::string deviceInstanceId)
  122. {
  123. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  124. if (devconLog != INVALID_HANDLE_VALUE)
  125. SetFilePointer(devconLog,0,0,FILE_END);
  126. STARTUPINFOA startupInfo;
  127. startupInfo.cb = sizeof(startupInfo);
  128. if (devconLog != INVALID_HANDLE_VALUE) {
  129. startupInfo.hStdOutput = devconLog;
  130. startupInfo.hStdError = devconLog;
  131. }
  132. PROCESS_INFORMATION processInfo;
  133. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  134. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  135. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" enable @" + deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  136. if (devconLog != INVALID_HANDLE_VALUE)
  137. CloseHandle(devconLog);
  138. return false;
  139. }
  140. WaitForSingleObject(processInfo.hProcess,INFINITE);
  141. CloseHandle(processInfo.hProcess);
  142. CloseHandle(processInfo.hThread);
  143. if (devconLog != INVALID_HANDLE_VALUE)
  144. CloseHandle(devconLog);
  145. return true;
  146. }
  147. static void _syncIpsWithRegistry(const std::set<InetAddress> &haveIps,const std::string netCfgInstanceId)
  148. {
  149. // Update registry to contain all non-link-local IPs for this interface
  150. std::string regMultiIps,regMultiNetmasks;
  151. for(std::set<InetAddress>::const_iterator i(haveIps.begin());i!=haveIps.end();++i) {
  152. if (!i->isLinkLocal()) {
  153. regMultiIps.append(i->toIpString());
  154. regMultiIps.push_back((char)0);
  155. regMultiNetmasks.append(i->netmask().toIpString());
  156. regMultiNetmasks.push_back((char)0);
  157. }
  158. }
  159. HKEY tcpIpInterfaces;
  160. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  161. if (regMultiIps.length()) {
  162. regMultiIps.push_back((char)0);
  163. regMultiNetmasks.push_back((char)0);
  164. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress",REG_MULTI_SZ,regMultiIps.data(),(DWORD)regMultiIps.length());
  165. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask",REG_MULTI_SZ,regMultiNetmasks.data(),(DWORD)regMultiNetmasks.length());
  166. } else {
  167. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress");
  168. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask");
  169. }
  170. }
  171. RegCloseKey(tcpIpInterfaces);
  172. }
  173. WindowsEthernetTap::WindowsEthernetTap(
  174. const RuntimeEnvironment *renv,
  175. const char *tag,
  176. const MAC &mac,
  177. unsigned int mtu,
  178. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  179. void *arg)
  180. throw(std::runtime_error) :
  181. EthernetTap("WindowsEthernetTap",mac,mtu),
  182. _r(renv),
  183. _handler(handler),
  184. _arg(arg),
  185. _tap(INVALID_HANDLE_VALUE),
  186. _injectSemaphore(INVALID_HANDLE_VALUE),
  187. _run(true),
  188. _initialized(false),
  189. _enabled(false)
  190. {
  191. char subkeyName[4096];
  192. char subkeyClass[4096];
  193. char data[4096];
  194. if (mtu > ZT_IF_MTU)
  195. throw std::runtime_error("MTU too large for Windows tap");
  196. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  197. HKEY nwAdapters;
  198. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  199. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  200. std::set<std::string> existingDeviceInstances;
  201. std::string mySubkeyName;
  202. // Look for the tap instance that corresponds with our interface tag (network ID)
  203. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  204. DWORD type;
  205. DWORD dataLen;
  206. DWORD subkeyNameLen = sizeof(subkeyName);
  207. DWORD subkeyClassLen = sizeof(subkeyClass);
  208. FILETIME lastWriteTime;
  209. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  210. type = 0;
  211. dataLen = sizeof(data);
  212. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  213. data[dataLen] = '\0';
  214. if (!strnicmp(data,"zttap",5)) {
  215. std::string instanceId;
  216. type = 0;
  217. dataLen = sizeof(data);
  218. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  219. instanceId.assign(data,dataLen);
  220. existingDeviceInstances.insert(instanceId);
  221. }
  222. std::string instanceIdPath;
  223. type = 0;
  224. dataLen = sizeof(data);
  225. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  226. instanceIdPath.assign(data,dataLen);
  227. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  228. type = 0;
  229. dataLen = sizeof(data);
  230. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  231. data[dataLen] = '\0';
  232. if (!strcmp(data,tag)) {
  233. _netCfgInstanceId = instanceId;
  234. _deviceInstanceId = instanceIdPath;
  235. mySubkeyName = subkeyName;
  236. break; // found it!
  237. }
  238. }
  239. }
  240. }
  241. }
  242. } else break; // no more subkeys or error occurred enumerating them
  243. }
  244. // If there is no device, try to create one
  245. if (_netCfgInstanceId.length() == 0) {
  246. // Log devcon output to a file
  247. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  248. if (devconLog == INVALID_HANDLE_VALUE) {
  249. LOG("WARNING: unable to open devcon.log");
  250. } else {
  251. SetFilePointer(devconLog,0,0,FILE_END);
  252. }
  253. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  254. STARTUPINFOA startupInfo;
  255. startupInfo.cb = sizeof(startupInfo);
  256. if (devconLog != INVALID_HANDLE_VALUE) {
  257. SetFilePointer(devconLog,0,0,FILE_END);
  258. startupInfo.hStdOutput = devconLog;
  259. startupInfo.hStdError = devconLog;
  260. }
  261. PROCESS_INFORMATION processInfo;
  262. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  263. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  264. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" install \"" + _r->homePath + _winEnv.tapDriver + "\" zttap200").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  265. RegCloseKey(nwAdapters);
  266. if (devconLog != INVALID_HANDLE_VALUE)
  267. CloseHandle(devconLog);
  268. throw std::runtime_error(std::string("unable to find or execute devcon at ") + _winEnv.devcon);
  269. }
  270. WaitForSingleObject(processInfo.hProcess,INFINITE);
  271. CloseHandle(processInfo.hProcess);
  272. CloseHandle(processInfo.hThread);
  273. if (devconLog != INVALID_HANDLE_VALUE)
  274. CloseHandle(devconLog);
  275. // Scan for the new instance by simply looking for taps that weren't
  276. // there originally. The static mutex we lock ensures this can't step
  277. // on its own toes.
  278. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  279. DWORD type;
  280. DWORD dataLen;
  281. DWORD subkeyNameLen = sizeof(subkeyName);
  282. DWORD subkeyClassLen = sizeof(subkeyClass);
  283. FILETIME lastWriteTime;
  284. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  285. type = 0;
  286. dataLen = sizeof(data);
  287. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  288. data[dataLen] = '\0';
  289. if (!strnicmp(data,"zttap",5)) {
  290. type = 0;
  291. dataLen = sizeof(data);
  292. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  293. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  294. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  295. _netCfgInstanceId.assign(data,dataLen);
  296. type = 0;
  297. dataLen = sizeof(data);
  298. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  299. _deviceInstanceId.assign(data,dataLen);
  300. mySubkeyName = subkeyName;
  301. // Disable DHCP by default on newly created devices
  302. HKEY tcpIpInterfaces;
  303. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  304. DWORD enable = 0;
  305. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  306. RegCloseKey(tcpIpInterfaces);
  307. }
  308. break; // found it!
  309. }
  310. }
  311. }
  312. }
  313. } else break; // no more keys or error occurred
  314. }
  315. }
  316. if (_netCfgInstanceId.length() > 0) {
  317. char tmps[4096];
  318. unsigned int tmpsl = Utils::snprintf(tmps,sizeof(tmps),"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X",(unsigned int)mac.data[0],(unsigned int)mac.data[1],(unsigned int)mac.data[2],(unsigned int)mac.data[3],(unsigned int)mac.data[4],(unsigned int)mac.data[5]) + 1;
  319. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  320. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  321. DWORD tmp = mtu;
  322. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  323. tmp = 0;
  324. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  325. } else {
  326. RegCloseKey(nwAdapters);
  327. throw std::runtime_error("unable to find or create tap adapter");
  328. }
  329. RegCloseKey(nwAdapters);
  330. // Convert device GUID junk... blech... is there an easier way to do this?
  331. {
  332. char nobraces[128];
  333. const char *nbtmp1 = _netCfgInstanceId.c_str();
  334. char *nbtmp2 = nobraces;
  335. while (*nbtmp1) {
  336. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  337. *nbtmp2++ = *nbtmp1;
  338. ++nbtmp1;
  339. }
  340. *nbtmp2 = (char)0;
  341. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  342. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  343. }
  344. // Disable and enable interface to ensure registry settings take effect
  345. _disableTapDevice(_r,_deviceInstanceId);
  346. if (!_enableTapDevice(_r,_deviceInstanceId))
  347. throw std::runtime_error("cannot enable tap device driver");
  348. // Open the tap, which is in this weird Windows analog of /dev
  349. char tapPath[4096];
  350. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  351. for(int openTrials=0;;) {
  352. // Try multiple times, since there seem to be reports from the field
  353. // of driver init timing issues. Blech.
  354. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  355. if (_tap == INVALID_HANDLE_VALUE) {
  356. if (++openTrials >= 3)
  357. throw std::runtime_error(std::string("unable to open tap device ")+tapPath);
  358. else Sleep(500);
  359. } else break;
  360. }
  361. setEnabled(true);
  362. if (!_enabled) {
  363. CloseHandle(_tap);
  364. throw std::runtime_error("cannot enable tap device using IOCTL");
  365. }
  366. // Initialized overlapped I/O structures and related events
  367. memset(&_tapOvlRead,0,sizeof(_tapOvlRead));
  368. _tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  369. memset(&_tapOvlWrite,0,sizeof(_tapOvlWrite));
  370. _tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  371. // Start background thread that actually performs I/O
  372. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  373. _thread = Thread::start(this);
  374. // Certain functions can now work (e.g. ips())
  375. _initialized = true;
  376. }
  377. WindowsEthernetTap::~WindowsEthernetTap()
  378. {
  379. _run = false;
  380. ReleaseSemaphore(_injectSemaphore,1,NULL);
  381. Thread::join(_thread);
  382. CloseHandle(_tap);
  383. CloseHandle(_tapOvlRead.hEvent);
  384. CloseHandle(_tapOvlWrite.hEvent);
  385. CloseHandle(_injectSemaphore);
  386. _disableTapDevice(_r,_deviceInstanceId);
  387. }
  388. void WindowsEthernetTap::setEnabled(bool en)
  389. {
  390. if (_tap == INVALID_HANDLE_VALUE) {
  391. _enabled = false;
  392. } else {
  393. uint32_t tmpi = (en ? 1 : 0);
  394. DWORD bytesReturned = 0;
  395. if (DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL))
  396. _enabled = en;
  397. else _enabled = false;
  398. }
  399. }
  400. bool WindowsEthernetTap::enabled() const
  401. {
  402. return _enabled;
  403. }
  404. void WindowsEthernetTap::setDisplayName(const char *dn)
  405. {
  406. if (!_initialized)
  407. return;
  408. HKEY ifp;
  409. 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) {
  410. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  411. RegCloseKey(ifp);
  412. }
  413. }
  414. bool WindowsEthernetTap::addIP(const InetAddress &ip)
  415. {
  416. if (!_initialized)
  417. return false;
  418. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  419. return false;
  420. std::set<InetAddress> haveIps(ips());
  421. try {
  422. // Add IP to interface at the netlink level if not already assigned.
  423. if (!haveIps.count(ip)) {
  424. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  425. MIB_UNICASTIPADDRESS_ROW ipr;
  426. InitializeUnicastIpAddressEntry(&ipr);
  427. if (ip.isV4()) {
  428. ipr.Address.Ipv4.sin_family = AF_INET;
  429. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  430. ipr.OnLinkPrefixLength = ip.port();
  431. } else if (ip.isV6()) {
  432. ipr.Address.Ipv6.sin6_family = AF_INET6;
  433. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,ip.rawIpData(),16);
  434. ipr.OnLinkPrefixLength = ip.port();
  435. } else return false;
  436. ipr.PrefixOrigin = IpPrefixOriginManual;
  437. ipr.SuffixOrigin = IpSuffixOriginManual;
  438. ipr.ValidLifetime = 0xffffffff;
  439. ipr.PreferredLifetime = 0xffffffff;
  440. ipr.InterfaceLuid = ifidx.first;
  441. ipr.InterfaceIndex = ifidx.second;
  442. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  443. haveIps.insert(ip);
  444. } else {
  445. LOG("unable to add IP address %s to interface %s: %d",ip.toString().c_str(),deviceName().c_str(),(int)GetLastError());
  446. return false;
  447. }
  448. }
  449. _syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  450. } catch (std::exception &exc) {
  451. LOG("unexpected exception adding IP address %s to %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  452. } catch ( ... ) {
  453. LOG("unexpected exception adding IP address %s to %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  454. }
  455. return false;
  456. }
  457. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  458. {
  459. if (!_initialized)
  460. return false;
  461. try {
  462. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  463. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  464. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  465. for(DWORD i=0;i<ipt->NumEntries;++i) {
  466. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  467. InetAddress addr;
  468. switch(ipt->Table[i].Address.si_family) {
  469. case AF_INET:
  470. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  471. break;
  472. case AF_INET6:
  473. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  474. if (addr.isLinkLocal())
  475. continue; // can't remove link-local IPv6 addresses
  476. break;
  477. }
  478. if (addr == ip) {
  479. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  480. FreeMibTable(ipt);
  481. _syncIpsWithRegistry(ips(),_netCfgInstanceId);
  482. return true;
  483. }
  484. }
  485. }
  486. FreeMibTable((PVOID)ipt);
  487. }
  488. } catch (std::exception &exc) {
  489. LOG("unexpected exception removing IP address %s from %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  490. } catch ( ... ) {
  491. LOG("unexpected exception removing IP address %s from %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  492. }
  493. return false;
  494. }
  495. std::set<InetAddress> WindowsEthernetTap::ips() const
  496. {
  497. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  498. std::set<InetAddress> addrs;
  499. if (!_initialized)
  500. return addrs;
  501. try {
  502. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  503. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  504. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  505. for(DWORD i=0;i<ipt->NumEntries;++i) {
  506. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  507. switch(ipt->Table[i].Address.si_family) {
  508. case AF_INET: {
  509. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  510. if (ip != InetAddress::LO4)
  511. addrs.insert(ip);
  512. } break;
  513. case AF_INET6: {
  514. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  515. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  516. addrs.insert(ip);
  517. } break;
  518. }
  519. }
  520. }
  521. FreeMibTable(ipt);
  522. }
  523. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  524. return addrs;
  525. }
  526. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  527. {
  528. if ((!_initialized)||(!_enabled))
  529. return;
  530. if (len > (ZT_IF_MTU))
  531. return; // sanity check
  532. {
  533. Mutex::Lock _l(_injectPending_m);
  534. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  535. char *d = _injectPending.back().first.data;
  536. memcpy(d,to.data,6);
  537. memcpy(d + 6,from.data,6);
  538. d[12] = (char)((etherType >> 8) & 0xff);
  539. d[13] = (char)(etherType & 0xff);
  540. memcpy(d + 14,data,len);
  541. }
  542. ReleaseSemaphore(_injectSemaphore,1,NULL);
  543. }
  544. std::string WindowsEthernetTap::deviceName() const
  545. {
  546. return _netCfgInstanceId;
  547. }
  548. std::string WindowsEthernetTap::persistentId() const
  549. {
  550. return _deviceInstanceId;
  551. }
  552. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  553. {
  554. if (!_initialized)
  555. return false;
  556. std::set<MulticastGroup> newGroups;
  557. // Ensure that groups are added for each IP... this handles the MAC:ADI
  558. // groups that are created from IPv4 addresses. Some of these may end
  559. // up being duplicates of what the IOCTL returns but that's okay since
  560. // the set<> will filter that.
  561. std::set<InetAddress> ipaddrs(ips());
  562. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  563. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  564. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  565. // level... something Windows does not seem to expose ordinarily. This lets
  566. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  567. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  568. DWORD bytesReturned = 0;
  569. if (DeviceIoControl(_tap,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  570. MAC mac;
  571. DWORD i = 0;
  572. while ((i + 6) <= bytesReturned) {
  573. mac.data[0] = mcastbuf[i++];
  574. mac.data[1] = mcastbuf[i++];
  575. mac.data[2] = mcastbuf[i++];
  576. mac.data[3] = mcastbuf[i++];
  577. mac.data[4] = mcastbuf[i++];
  578. mac.data[5] = mcastbuf[i++];
  579. if (mac.isMulticast()) {
  580. // exclude the nulls that may be returned or any other junk Windows puts in there
  581. newGroups.insert(MulticastGroup(mac,0));
  582. }
  583. }
  584. }
  585. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  586. bool changed = false;
  587. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  588. if (!groups.count(*mg)) {
  589. groups.insert(*mg);
  590. changed = true;
  591. }
  592. }
  593. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  594. if (!newGroups.count(*mg)) {
  595. groups.erase(mg++);
  596. changed = true;
  597. } else ++mg;
  598. }
  599. return changed;
  600. }
  601. void WindowsEthernetTap::threadMain()
  602. throw()
  603. {
  604. HANDLE wait4[3];
  605. wait4[0] = _injectSemaphore;
  606. wait4[1] = _tapOvlRead.hEvent;
  607. wait4[2] = _tapOvlWrite.hEvent; // only included if writeInProgress is true
  608. ReadFile(_tap,_tapReadBuf,sizeof(_tapReadBuf),NULL,&_tapOvlRead);
  609. bool writeInProgress = false;
  610. for(;;) {
  611. // Windows can DIAF
  612. if (_enabled)
  613. setEnabled(true);
  614. if (!_run) break;
  615. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,INFINITE,TRUE);
  616. if (!_run) break;
  617. if (HasOverlappedIoCompleted(&_tapOvlRead)) {
  618. DWORD bytesRead = 0;
  619. if (GetOverlappedResult(_tap,&_tapOvlRead,&bytesRead,FALSE)) {
  620. if ((bytesRead > 14)&&(_enabled)) {
  621. MAC to(_tapReadBuf);
  622. MAC from(_tapReadBuf + 6);
  623. unsigned int etherType = ((((unsigned int)_tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)_tapReadBuf[13]) & 0xff);
  624. try {
  625. Buffer<4096> tmp(_tapReadBuf + 14,bytesRead - 14);
  626. _handler(_arg,from,to,etherType,tmp);
  627. } catch ( ... ) {} // handlers should not throw
  628. }
  629. }
  630. ReadFile(_tap,_tapReadBuf,sizeof(_tapReadBuf),NULL,&_tapOvlRead);
  631. }
  632. if (writeInProgress) {
  633. if (HasOverlappedIoCompleted(&_tapOvlWrite)) {
  634. writeInProgress = false;
  635. _injectPending_m.lock();
  636. _injectPending.pop();
  637. } else continue; // still writing, so skip code below and wait
  638. } else _injectPending_m.lock();
  639. if (!_injectPending.empty()) {
  640. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&_tapOvlWrite);
  641. writeInProgress = true;
  642. }
  643. _injectPending_m.unlock();
  644. }
  645. CancelIo(_tap);
  646. }
  647. bool WindowsEthernetTap::deletePersistentTapDevice(const RuntimeEnvironment *_r,const char *pid)
  648. {
  649. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  650. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  651. STARTUPINFOA startupInfo;
  652. startupInfo.cb = sizeof(startupInfo);
  653. if (devconLog != INVALID_HANDLE_VALUE) {
  654. SetFilePointer(devconLog,0,0,FILE_END);
  655. startupInfo.hStdOutput = devconLog;
  656. startupInfo.hStdError = devconLog;
  657. }
  658. PROCESS_INFORMATION processInfo;
  659. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  660. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  661. if (CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" remove @" + pid).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  662. WaitForSingleObject(processInfo.hProcess,INFINITE);
  663. CloseHandle(processInfo.hProcess);
  664. CloseHandle(processInfo.hThread);
  665. if (devconLog != INVALID_HANDLE_VALUE)
  666. CloseHandle(devconLog);
  667. return true;
  668. }
  669. if (devconLog != INVALID_HANDLE_VALUE)
  670. CloseHandle(devconLog);
  671. return false;
  672. }
  673. int WindowsEthernetTap::cleanPersistentTapDevices(const RuntimeEnvironment *_r,const std::set<std::string> &exceptThese,bool alsoRemoveUnassociatedDevices)
  674. {
  675. char subkeyName[4096];
  676. char subkeyClass[4096];
  677. char data[4096];
  678. std::set<std::string> instanceIdPathsToRemove;
  679. {
  680. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  681. HKEY nwAdapters;
  682. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  683. return -1;
  684. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  685. DWORD type;
  686. DWORD dataLen;
  687. DWORD subkeyNameLen = sizeof(subkeyName);
  688. DWORD subkeyClassLen = sizeof(subkeyClass);
  689. FILETIME lastWriteTime;
  690. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  691. type = 0;
  692. dataLen = sizeof(data);
  693. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  694. data[dataLen] = '\0';
  695. if (!strnicmp(data,"zttap",5)) {
  696. std::string instanceIdPath;
  697. type = 0;
  698. dataLen = sizeof(data);
  699. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  700. instanceIdPath.assign(data,dataLen);
  701. if (instanceIdPath.length() != 0) {
  702. type = 0;
  703. dataLen = sizeof(data);
  704. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  705. if (dataLen <= 0) {
  706. if (alsoRemoveUnassociatedDevices)
  707. instanceIdPathsToRemove.insert(instanceIdPath);
  708. } else {
  709. if (!exceptThese.count(std::string(data,dataLen)))
  710. instanceIdPathsToRemove.insert(instanceIdPath);
  711. }
  712. } else if (alsoRemoveUnassociatedDevices)
  713. instanceIdPathsToRemove.insert(instanceIdPath);
  714. }
  715. }
  716. }
  717. } else break; // end of list or failure
  718. }
  719. RegCloseKey(nwAdapters);
  720. }
  721. int removed = 0;
  722. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  723. if (deletePersistentTapDevice(_r,iidp->c_str()))
  724. ++removed;
  725. }
  726. return removed;
  727. }
  728. } // namespace ZeroTier