d2675ef69fea63ebe533dbc192506df7ba3df90b
[tinc] / device.c
1 /*
2     device.c -- Interaction with Windows tap driver in a MinGW environment
3     Copyright (C) 2002-2003 Ivo Timmermans <ivo@o2w.nl>,
4                   2002-2003 Guus Sliepen <guus@sliepen.eu.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: device.c,v 1.1.2.9 2003/08/02 21:01:50 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include <windows.h>
26 #include <winioctl.h>
27
28 #include "conf.h"
29 #include "logger.h"
30 #include "net.h"
31 #include "route.h"
32 #include "utils.h"
33 #include "xalloc.h"
34
35 #define NETCARD_REG_KEY_2000 "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
36 #define NETCARD_REG_KEY      "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards"
37 #define REG_SERVICE_KEY      "SYSTEM\\CurrentControlSet\\Services"
38 #define REG_CONTROL_NET      "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
39
40 #define USERMODEDEVICEDIR "\\\\.\\"
41 #define SYSDEVICEDIR  "\\Device\\"
42 #define USERDEVICEDIR "\\??\\"
43 #define TAPSUFFIX     ".tap"
44
45 #define TAP_CONTROL_CODE(request,method) CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD | 8000, request, method, FILE_ANY_ACCESS)
46
47 #define TAP_IOCTL_GET_LASTMAC    TAP_CONTROL_CODE(0, METHOD_BUFFERED)
48 #define TAP_IOCTL_GET_MAC        TAP_CONTROL_CODE(1, METHOD_BUFFERED)
49 #define TAP_IOCTL_SET_STATISTICS TAP_CONTROL_CODE(2, METHOD_BUFFERED)
50
51 /* FIXME: This only works for Windows 2000 */
52 #define OSTYPE 5
53
54 int device_fd = 0;
55 HANDLE device_handle = INVALID_HANDLE_VALUE;
56 char *device = NULL;
57 char *iface = NULL;
58 char *device_info = NULL;
59
60 int device_total_in = 0;
61 int device_total_out = 0;
62
63 DWORD WINAPI tapreader(void *bla) {
64         int sock, err, status;
65         struct addrinfo *ai;
66         struct addrinfo hint = {
67                 .ai_family = AF_UNSPEC,
68                 .ai_socktype = SOCK_DGRAM,
69                 .ai_protocol = IPPROTO_UDP,
70                 .ai_flags = 0,
71         };
72         char buf[MTU];
73         long len;
74         OVERLAPPED overlapped;
75
76         /* Open a socket to the parent process */
77
78         err = getaddrinfo(NULL, "12345", &hint, &ai);
79
80         if(err || !ai) {
81                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(errno));
82                 return -1;
83         }
84
85         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
86
87         freeaddrinfo(ai);
88
89         if(sock < 0) {
90                 logger(LOG_ERR, _("System call `%s' failed: %s"), "socket", strerror(errno));
91                 return -1;
92         }
93
94         if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
95                 logger(LOG_ERR, _("System call `%s' failed: %s"), "connect", strerror(errno));
96                 return -1;
97         }
98
99         logger(LOG_DEBUG, _("Tap reader running"));
100
101         /* Read from tap device and send to parent */
102
103         overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
104         
105         for(;;) {
106                 overlapped.Offset = 0;
107                 overlapped.OffsetHigh = 0;
108                 ResetEvent(overlapped.hEvent);
109
110                 status = ReadFile(device_handle, buf, sizeof(buf), &len, &overlapped);
111
112                 if(!status) {
113                         if(GetLastError() == ERROR_IO_PENDING) {
114                                 WaitForSingleObject(overlapped.hEvent, INFINITE);
115                                 if(!GetOverlappedResult(device_handle, &overlapped, &len, FALSE))
116                                         continue;
117                         } else {
118                                 logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
119                                            device, strerror(errno));
120                                 return -1;
121                         }
122                 }
123
124                 if(send(sock, buf, len, 0) <= 0)
125                         return -1;
126         }
127 }
128
129 bool setup_device(void)
130 {
131         HKEY key, key2;
132         int i;
133
134         char regpath[1024];
135         char adapterid[1024];
136         char adaptername[1024];
137         char tapname[1024];
138         long len;
139
140         bool found = false;
141
142         int sock, err;
143         HANDLE thread;
144
145         struct addrinfo *ai;
146         struct addrinfo hint = {
147                 .ai_family = AF_UNSPEC,
148                 .ai_socktype = SOCK_DGRAM,
149                 .ai_protocol = IPPROTO_UDP,
150                 .ai_flags = AI_PASSIVE,
151         };
152
153         cp();
154
155         get_config_string(lookup_config(config_tree, "Device"), &device);
156         get_config_string(lookup_config(config_tree, "Interface"), &iface);
157
158         /* Open registry and look for network adapters */
159
160         if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_CONTROL_NET, 0, KEY_READ, &key)) {
161                 logger(LOG_ERR, _("Unable to read registry: %s"), winerror(GetLastError()));
162                 return false;
163         }
164
165         for (i = 0; ; i++) {
166                 len = sizeof(adapterid);
167                 if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
168                         break;
169
170                 /* Find out more about this adapter */
171
172                 snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", REG_CONTROL_NET, adapterid);
173
174                 if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
175                         continue;
176
177                 len = sizeof(adaptername);
178                 RegQueryValueEx(key2, "Name", 0, 0, adaptername, &len);
179
180                 RegCloseKey(key2);
181
182                 if(device) {
183                         if(!strcmp(device, adapterid)) {
184                                 found = true;
185                                 break;
186                         } else
187                                 continue;
188                 }
189
190                 if(iface) {
191                         if(!strcmp(iface, adaptername)) {
192                                 found = true;
193                                 break;
194                         } else
195                                 continue;
196                 }
197
198                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
199                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
200                 if(device_handle != INVALID_HANDLE_VALUE) {
201                         found = true;
202                         break;
203                 }
204         }
205
206         RegCloseKey(key);
207
208         if(!found) {
209                 logger(LOG_ERR, _("No Windows tap device found!"));
210                 return false;
211         }
212
213         if(!device)
214                 device = xstrdup(adapterid);
215
216         if(!iface)
217                 iface = xstrdup(adaptername);
218
219         /* Try to open the corresponding tap device */
220
221         if(device_handle == INVALID_HANDLE_VALUE) {
222                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);
223                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
224         }
225         
226         if(device_handle == INVALID_HANDLE_VALUE) {
227                 logger(LOG_ERR, _("%s (%s) is no a usable Windows tap device!"), device, iface);
228                 return false;
229         }
230
231         /* Get MAC address from tap device */
232
233         if(!DeviceIoControl(device_handle, TAP_IOCTL_GET_MAC, mymac.x, sizeof(mymac.x), mymac.x, sizeof(mymac.x), &len, 0)) {
234                 logger(LOG_ERR, _("Could not get MAC address from Windows tap device!"));
235                 return false;
236         }
237
238         if(routing_mode == RMODE_ROUTER) {
239                 overwrite_mac = 1;
240         }
241
242         /* Create a listening socket */
243
244         err = getaddrinfo(NULL, "12345", &hint, &ai);
245
246         if(err || !ai) {
247                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(errno));
248                 return false;
249         }
250
251         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
252
253         if(sock < 0) {
254                 logger(LOG_ERR, _("System call `%s' failed: %s"), "socket", strerror(errno));
255                 return false;
256         }
257
258         if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
259                 logger(LOG_ERR, _("System call `%s' failed: %s"), "bind", strerror(errno));
260                 return false;
261         }
262
263         freeaddrinfo(ai);
264
265         if(listen(sock, 1)) {
266                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen", strerror(errno));
267                 return false;
268         }
269
270         /* Start the tap reader */
271
272         thread = CreateThread(NULL, 0, tapreader, NULL, 0, NULL);
273
274         if(!thread) {
275                 logger(LOG_ERR, _("System call `%s' failed: %s"), "CreateThread", winerror(GetLastError()));
276                 return false;
277         }
278
279         /* Wait for the tap reader to connect back to us */
280
281         if((device_fd = accept(sock, NULL, 0)) == -1) {
282                 logger(LOG_ERR, _("System call `%s' failed: %s"), "accept", strerror(errno));
283                 return false;
284         }
285
286         closesocket(sock);
287
288         device_info = _("Windows tap device");
289
290         logger(LOG_INFO, _("%s (%s) is a %s"), device, iface, device_info);
291
292         return true;
293 }
294
295 void close_device(void)
296 {
297         cp();
298
299         CloseHandle(device_handle);
300 }
301
302 bool read_packet(vpn_packet_t *packet)
303 {
304         int lenin;
305
306         cp();
307
308         if((lenin = recv(device_fd, packet->data, MTU, 0)) <= 0) {
309                 logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
310                            device, strerror(errno));
311                 return false;
312         }
313         
314         packet->len = lenin;
315
316         device_total_in += packet->len;
317
318         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Read packet of %d bytes from %s"), packet->len,
319                            device_info);
320
321         return true;
322 }
323
324 bool write_packet(vpn_packet_t *packet)
325 {
326         long lenout;
327         OVERLAPPED overlapped = {0};
328
329         cp();
330
331         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Writing packet of %d bytes to %s"),
332                            packet->len, device_info);
333
334         if(!WriteFile(device_handle, packet->data, packet->len, &lenout, &overlapped)) {
335                 logger(LOG_ERR, _("Error while writing to %s %s: %s"), device_info, device, winerror(GetLastError()));
336                 return false;
337         }
338
339         device_total_out += packet->len;
340
341         return true;
342 }
343
344 void dump_device_stats(void)
345 {
346         cp();
347
348         logger(LOG_DEBUG, _("Statistics for %s %s:"), device_info, device);
349         logger(LOG_DEBUG, _(" total bytes in:  %10d"), device_total_in);
350         logger(LOG_DEBUG, _(" total bytes out: %10d"), device_total_out);
351 }