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