summaryrefslogtreecommitdiff
path: root/src/win32/tunDevice.cpp
blob: 8f91414a1a13954730ba4375c77d856e7534d6f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
 *  anytun
 *
 *  The secure anycast tunneling protocol (satp) defines a protocol used
 *  for communication between any combination of unicast and anycast
 *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
 *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
 *  ethernet, ip, arp ...). satp directly includes cryptography and
 *  message authentication based on the methodes used by SRTP.  It is
 *  intended to deliver a generic, scaleable and secure solution for
 *  tunneling and relaying of packets of any protocol.
 *
 *
 *  Copyright (C) 2007-2008 Othmar Gsenger, Erwin Nindl, 
 *                          Christian Pointner <satp@wirdorange.org>
 *
 *  This file is part of Anytun.
 *
 *  Anytun is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3 as
 *  published by the Free Software Foundation.
 *
 *  Anytun is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string.h>
#include <sstream>
#include <windows.h>
#include <winioctl.h>

#include "../endian.h"
#include "../tunDevice.h"
#include "../threadUtils.hpp"
#include "../log.h"

#include "common.h"

#define REG_KEY_LENGTH 256
#define REG_NAME_LENGTH 256

TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_lp, std::string ifcfg_rnmp) : conf_(dev_name, dev_type, ifcfg_lp, ifcfg_rnmp, 1400)
{
  if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP)
    throw std::runtime_error("unable to recognize type of device (tun or tap)");

  handle_ = INVALID_HANDLE_VALUE;
  if(!getAdapter(dev_name))
    throw std::runtime_error("can't find any suitable device");

  if(handle_ == INVALID_HANDLE_VALUE) {
    std::stringstream tapname;
	  tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX;
    handle_ = CreateFile(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
    if(handle_ == INVALID_HANDLE_VALUE) {
      std::stringstream msg;
      msg << "Unable to open device: " << actual_node_ << " (" << actual_name_ << "): " << LogErrno(GetLastError());
      throw std::runtime_error(msg.str());
	  }
  }

  DWORD err;
  if(conf_.type_ == TYPE_TUN) {
    u_long ep[2];
    ep[0] = htonl(conf_.local_.getNetworkAddressV4().to_ulong());
    ep[1] = htonl(conf_.remote_netmask_.getNetworkAddressV4().to_ulong());
    err = performIoControl(TAP_IOCTL_CONFIG_POINT_TO_POINT, ep, sizeof(ep), ep, sizeof(ep));
    if(err != ERROR_SUCCESS) {
      CloseHandle(handle_);
      std::stringstream msg;
      msg << "Unable to set device point-to-point mode: " << LogErrno(err);
      throw std::runtime_error(msg.str());
	  }
  }

  int status = true;
  err = performIoControl(TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status));
  if(err != ERROR_SUCCESS) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "Unable to set device media status: " << LogErrno(err);
    throw std::runtime_error(msg.str());
	}

//  if(ifcfg_lp != "" && ifcfg_rnmp != "")
//    do_ifconfig();

  roverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  woverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
}

bool TunDevice::getAdapter(std::string const& dev_name)
{
  HKEY key, key2;
  LONG err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_ENUMERATE_SUB_KEYS, &key);
  if(err != ERROR_SUCCESS) {
    std::stringstream msg;
    msg << "Unable to open registry key: " << LogErrno(err);
    throw std::runtime_error(msg.str());
  }

  bool found = false;
  DWORD len;
  char adapterid[REG_KEY_LENGTH];
  char adaptername[REG_NAME_LENGTH];
  for(int i=0; ; ++i) {
    len = sizeof(adapterid);
		err = RegEnumKeyEx(key, i, adapterid, &len, NULL, NULL, NULL, NULL);
    if(err == ERROR_NO_MORE_ITEMS)
			break;
    if(err != ERROR_SUCCESS) {
      RegCloseKey(key);
      std::stringstream msg;
      msg << "Unable to read registry: " << LogErrno(err);
      throw std::runtime_error(msg.str());
    }

    std::stringstream regpath;
    regpath << NETWORK_CONNECTIONS_KEY << "\\" << adapterid << "\\Connection";
    err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath.str().c_str(), 0, KEY_QUERY_VALUE, &key2);
    if(err != ERROR_SUCCESS)
      continue;

    len = sizeof(adaptername);
    err = RegQueryValueEx(key2, "Name", NULL, NULL, (LPBYTE)adaptername, &len);
		RegCloseKey(key2);
    if(err != ERROR_SUCCESS) // || len >= sizeof(adaptername))
      continue;
    if(adaptername[len-1] != 0) {
      if(len < sizeof(adaptername))
        adaptername[len++] = 0;
      else
        continue;
    }  
    if(dev_name != "") {
      if(!dev_name.compare(0, len-1, adaptername)) {
        found = true;
        break;
      }
    }
    else {
      std::stringstream tapname;
  	  tapname << USERMODEDEVICEDIR << adapterid << TAPSUFFIX;
      handle_ = CreateFile(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
      if(handle_ == INVALID_HANDLE_VALUE)
        continue;
      found = true;
      break;
    }
  }
  RegCloseKey(key);

  actual_node_ = adapterid;
  actual_name_ = adaptername;
  return found;
}

DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, LPVOID outBuffer, DWORD outBufferSize)
{
  OVERLAPPED overlapped;
  overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  overlapped.Offset = 0;
	overlapped.OffsetHigh = 0;
  
  DWORD len;
  if(!DeviceIoControl(handle_, controlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, &len, &overlapped)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(overlapped.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE))
        return GetLastError();
    }
    else
      return GetLastError();
  }
  return ERROR_SUCCESS;
}


TunDevice::~TunDevice()
{
  CloseHandle(handle_);
  CloseHandle(roverlapped_.hEvent);
  CloseHandle(woverlapped_.hEvent);
}

int TunDevice::fix_return(int ret, size_t pi_length)
{
// nothing to be done here
	return 0;
}

int TunDevice::read(u_int8_t* buf, u_int32_t len)
{
  DWORD lenout;
  roverlapped_.Offset = 0;
	roverlapped_.OffsetHigh = 0;
  ResetEvent(roverlapped_.hEvent);
  
  if(!ReadFile(handle_, buf, len, &lenout, &roverlapped_)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(roverlapped_.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &roverlapped_, &lenout, FALSE)) {
        cLog.msg(Log::PRIO_ERR) << "Error while trying to get overlapped result: " << LogErrno(GetLastError());
        return -1;
      }
    }
    else {
      cLog.msg(Log::PRIO_ERR) << "Error while reading from device: " << LogErrno(GetLastError());
      return -1;
    }
  }
  return lenout;
}

int TunDevice::write(u_int8_t* buf, u_int32_t len)
{
  DWORD lenout;
  woverlapped_.Offset = 0;
	woverlapped_.OffsetHigh = 0;
  ResetEvent(woverlapped_.hEvent);

	if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(woverlapped_.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &woverlapped_, &lenout, FALSE)) {
        cLog.msg(Log::PRIO_ERR) << "Error while trying to get overlapped result: " << LogErrno(GetLastError());
        return -1;
      }
    }
    else {
      cLog.msg(Log::PRIO_ERR) << "Error while writing to device: " << LogErrno(GetLastError());
      return -1;
    }
  }
  return lenout;	
}

void TunDevice::init_post()
{
// nothing to be done here
}

void TunDevice::do_ifconfig()
{

}