Imported Upstream version 0.3.4
[anytun.git] / src / win32 / tunDevice.cpp
1 /*
2  *  anytun
3  *
4  *  The secure anycast tunneling protocol (satp) defines a protocol used
5  *  for communication between any combination of unicast and anycast
6  *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
7  *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
8  *  ethernet, ip, arp ...). satp directly includes cryptography and
9  *  message authentication based on the methodes used by SRTP.  It is
10  *  intended to deliver a generic, scaleable and secure solution for
11  *  tunneling and relaying of packets of any protocol.
12  *
13  *
14  *  Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl,
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License as published by
21  *  the Free Software Foundation, either version 3 of the License, or
22  *  any later version.
23  *
24  *  Anytun is distributed in the hope that it will be useful,
25  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *  GNU General Public License for more details.
28  *
29  *  You should have received a copy of the GNU General Public License
30  *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
31  */
32
33 #include <string.h>
34 #include <sstream>
35 #include <windows.h>
36 #include <winioctl.h>
37
38 #include "../endian.h"
39 #include "../tunDevice.h"
40 #include "../threadUtils.hpp"
41 #include "../log.h"
42 #include "../anytunError.h"
43
44 #include "registryKey.h"
45 #include "common.h"
46
47 #define MIN_TAP_VER_MAJOR 8
48 #define MIN_TAP_VER_MINOR 2
49
50 TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400)
51 {
52   if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP) {
53     AnytunError::throwErr() << "unable to recognize type of device (tun or tap)";
54   }
55
56   handle_ = INVALID_HANDLE_VALUE;
57   if(!getAdapter(dev_name)) {
58     AnytunError::throwErr() << "can't find any suitable device";
59   }
60
61   if(handle_ == INVALID_HANDLE_VALUE) {
62     std::stringstream tapname;
63     tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX;
64     handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
65     if(handle_ == INVALID_HANDLE_VALUE) {
66       AnytunError::throwErr() << "Unable to open device: " << actual_node_ << " (" << actual_name_ << "): " << AnytunErrno(GetLastError());
67     }
68   }
69
70   DWORD err;
71   u_long info[3];
72   info[0] = info[1] = info[2] = 0;
73   err = performIoControl(TAP_IOCTL_GET_VERSION, info, sizeof(info), info, sizeof(info));
74   if(err != ERROR_SUCCESS) {
75     CloseHandle(handle_);
76     AnytunError::throwErr() << "Unable to get device version: " << AnytunErrno(err);
77   }
78   cLog.msg(Log::PRIO_NOTICE) << "Windows TAP Driver Version " << info[0] << "." << info[1] << " " << (info[2] ? "(DEBUG)" : "");
79   if(!(info[0] > MIN_TAP_VER_MAJOR || (info[0] == MIN_TAP_VER_MAJOR && info[1] >= MIN_TAP_VER_MINOR))) {
80     CloseHandle(handle_);
81     AnytunError::throwErr() << "need a higher Version of TAP Driver (at least " << MIN_TAP_VER_MAJOR << "." << MIN_TAP_VER_MINOR << ")";
82   }
83
84   if(conf_.type_ == TYPE_TUN) {
85     u_long ep[3];
86     ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong());
87     ep[1] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong());
88     ep[2] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong());
89     err = performIoControl(TAP_IOCTL_CONFIG_TUN, ep, sizeof(ep), ep, sizeof(ep));
90     if(err != ERROR_SUCCESS) {
91       CloseHandle(handle_);
92       AnytunError::throwErr() << "Unable to set device tun mode: " << AnytunErrno(err);
93     }
94   }
95
96   if(ifcfg_addr != "") {
97     do_ifconfig();
98   }
99
100   int status = true;
101   err = performIoControl(TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status));
102   if(err != ERROR_SUCCESS) {
103     CloseHandle(handle_);
104     AnytunError::throwErr() << "Unable to set device media status: " << AnytunErrno(err);
105   }
106
107   roverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
108   woverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
109 }
110
111 bool TunDevice::getAdapter(std::string const& dev_name)
112 {
113   RegistryKey akey;
114   DWORD err = akey.open(HKEY_LOCAL_MACHINE, ADAPTER_KEY, KEY_ENUMERATE_SUB_KEYS);
115   if(err != ERROR_SUCCESS) {
116     AnytunError::throwErr() << "Unable to open registry key (HKLM\\" << ADAPTER_KEY << "): " << AnytunErrno(err);
117   }
118
119   bool found = false;
120   for(int i=0; ; ++i) {
121     RegistryKey ckey;
122     DWORD err = akey.getSubKey(i, ckey, KEY_QUERY_VALUE);
123     if(err == ERROR_NO_MORE_ITEMS) {
124       break;
125     }
126     if(err != ERROR_SUCCESS) {
127       continue;
128     }
129
130     try {
131       if(ckey["ComponentId"] != TAP_COMPONENT_ID) {
132         continue;
133       }
134       actual_node_ = ckey["NetCfgInstanceId"];
135
136       RegistryKey nkey;
137       std::stringstream keyname;
138       keyname << NETWORK_CONNECTIONS_KEY << "\\" << actual_node_ << "\\Connection";
139       err = nkey.open(HKEY_LOCAL_MACHINE, keyname.str().c_str(), KEY_QUERY_VALUE);;
140       if(err != ERROR_SUCCESS) {
141         continue;
142       }
143
144       actual_name_ = nkey["Name"];
145     } catch(AnytunErrno&) { continue; }
146
147     if(dev_name != "") {
148       if(dev_name == actual_name_) {
149         found = true;
150         break;
151       }
152     } else {
153       std::stringstream tapname;
154       tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX;
155       handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
156       if(handle_ == INVALID_HANDLE_VALUE) {
157         continue;
158       }
159       found = true;
160       break;
161     }
162   }
163   if(!found) {
164     actual_node_ = "";
165     actual_name_ = "";
166   }
167   return found;
168 }
169
170 DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, LPVOID outBuffer, DWORD outBufferSize)
171 {
172   OVERLAPPED overlapped;
173   overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
174   overlapped.Offset = 0;
175   overlapped.OffsetHigh = 0;
176
177   DWORD len;
178   if(!DeviceIoControl(handle_, controlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, &len, &overlapped)) {
179     DWORD err = GetLastError();
180     if(err == ERROR_IO_PENDING) {
181       WaitForSingleObject(overlapped.hEvent, INFINITE);
182       if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE)) {
183         return GetLastError();
184       }
185     } else {
186       return GetLastError();
187     }
188   }
189   return ERROR_SUCCESS;
190 }
191
192
193 TunDevice::~TunDevice()
194 {
195   if(handle_ != INVALID_HANDLE_VALUE) {
196     CloseHandle(handle_);
197   }
198   if(roverlapped_.hEvent != INVALID_HANDLE_VALUE) {
199     CloseHandle(roverlapped_.hEvent);
200   }
201   if(woverlapped_.hEvent != INVALID_HANDLE_VALUE) {
202     CloseHandle(woverlapped_.hEvent);
203   }
204 }
205
206 int TunDevice::fix_return(int ret, size_t pi_length) const
207 {
208   // nothing to be done here
209   return 0;
210 }
211
212 int TunDevice::read(uint8_t* buf, uint32_t len)
213 {
214   DWORD lenout;
215   roverlapped_.Offset = 0;
216   roverlapped_.OffsetHigh = 0;
217   ResetEvent(roverlapped_.hEvent);
218
219   if(!ReadFile(handle_, buf, len, &lenout, &roverlapped_)) {
220     DWORD err = GetLastError();
221     if(err == ERROR_IO_PENDING) {
222       WaitForSingleObject(roverlapped_.hEvent, INFINITE);
223       if(!GetOverlappedResult(handle_, &roverlapped_, &lenout, FALSE)) {
224         cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError());
225         return -1;
226       }
227     } else {
228       cLog.msg(Log::PRIO_ERROR) << "Error while reading from device: " << AnytunErrno(GetLastError());
229       return -1;
230     }
231   }
232   return lenout;
233 }
234
235 int TunDevice::write(uint8_t* buf, uint32_t len)
236 {
237   DWORD lenout;
238   woverlapped_.Offset = 0;
239   woverlapped_.OffsetHigh = 0;
240   ResetEvent(woverlapped_.hEvent);
241
242   if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) {
243     DWORD err = GetLastError();
244     if(err == ERROR_IO_PENDING) {
245       WaitForSingleObject(woverlapped_.hEvent, INFINITE);
246       if(!GetOverlappedResult(handle_, &woverlapped_, &lenout, FALSE)) {
247         cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError());
248         return -1;
249       }
250     } else {
251       cLog.msg(Log::PRIO_ERROR) << "Error while writing to device: " << AnytunErrno(GetLastError());
252       return -1;
253     }
254   }
255   return lenout;
256 }
257
258 void TunDevice::init_post()
259 {
260   // nothing to be done here
261 }
262
263 void TunDevice::do_ifconfig()
264 {
265   u_long ep[4];
266   ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong());
267   ep[1] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong());
268   ep[2] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong());
269   ep[3] = 365 * 24 * 3600;  // lease time in seconds
270   DWORD err = performIoControl(TAP_IOCTL_CONFIG_DHCP_MASQ, ep, sizeof(ep), ep, sizeof(ep));
271   if(err != ERROR_SUCCESS) {
272     CloseHandle(handle_);
273     AnytunError::throwErr() << "Unable to set device dhcp masq mode: " << AnytunErrno(err);
274   }
275
276   u_long mtu;
277   err = performIoControl(TAP_IOCTL_GET_MTU, &mtu, sizeof(mtu), &mtu, sizeof(mtu));
278   if(err != ERROR_SUCCESS) {
279     CloseHandle(handle_);
280     AnytunError::throwErr() << "Unable to get device mtu: " << AnytunErrno(err);
281   }
282   conf_.mtu_ = static_cast<uint16_t>(mtu);
283 }
284
285 void TunDevice::waitUntilReady()
286 {
287   // nothing to be done here
288 }