Move CABAL branch to its rightful place: the trunk.
[oweals/tinc.git] / src / mingw / 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.14 2003/10/08 11:37:53 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 REG_CONTROL_NET      "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
36
37 #define USERMODEDEVICEDIR "\\\\.\\"
38 #define USERDEVICEDIR "\\??\\"
39 #define TAPSUFFIX     ".tap"
40
41 #define TAP_CONTROL_CODE(request,method) CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD | 8000, request, method, FILE_ANY_ACCESS)
42
43 #define TAP_IOCTL_GET_LASTMAC           TAP_CONTROL_CODE(0, METHOD_BUFFERED)
44 #define TAP_IOCTL_GET_MAC               TAP_CONTROL_CODE(1, METHOD_BUFFERED)
45 #define TAP_IOCTL_SET_STATISTICS        TAP_CONTROL_CODE(2, METHOD_BUFFERED)
46 #define TAP_IOCTL_GET_VERSION           TAP_CONTROL_CODE(3, METHOD_BUFFERED)
47 #define TAP_IOCTL_GET_MTU               TAP_CONTROL_CODE(4, METHOD_BUFFERED)
48 #define TAP_IOCTL_GET_INFO              TAP_CONTROL_CODE(5, METHOD_BUFFERED)
49 #define TAP_IOCTL_CONFIG_POINT_TO_POINT TAP_CONTROL_CODE(6, METHOD_BUFFERED)
50 #define TAP_IOCTL_SET_MEDIA_STATUS      TAP_CONTROL_CODE(7, METHOD_BUFFERED)
51
52
53 int device_fd = 0;
54 HANDLE device_handle = INVALID_HANDLE_VALUE;
55 char *device = NULL;
56 char *iface = NULL;
57 char *device_info = NULL;
58
59 int device_total_in = 0;
60 int device_total_out = 0;
61
62 extern char *myport;
63
64 DWORD WINAPI tapreader(void *bla) {
65         int sock, err, status;
66         struct addrinfo *ai;
67         struct addrinfo hint = {
68                 .ai_family = AF_UNSPEC,
69                 .ai_socktype = SOCK_DGRAM,
70                 .ai_protocol = IPPROTO_UDP,
71                 .ai_flags = 0,
72         };
73         char buf[MTU];
74         long len;
75         OVERLAPPED overlapped;
76
77         /* Open a socket to the parent process */
78
79         err = getaddrinfo(NULL, myport, &hint, &ai);
80
81         if(err || !ai) {
82                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(errno));
83                 return -1;
84         }
85
86         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
87
88         freeaddrinfo(ai);
89
90         if(sock < 0) {
91                 logger(LOG_ERR, _("System call `%s' failed: %s"), "socket", strerror(errno));
92                 return -1;
93         }
94
95         if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
96                 logger(LOG_ERR, _("System call `%s' failed: %s"), "connect", strerror(errno));
97                 return -1;
98         }
99
100         logger(LOG_DEBUG, _("Tap reader running"));
101
102         /* Read from tap device and send to parent */
103
104         overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
105         
106         for(;;) {
107                 overlapped.Offset = 0;
108                 overlapped.OffsetHigh = 0;
109                 ResetEvent(overlapped.hEvent);
110
111                 status = ReadFile(device_handle, buf, sizeof(buf), &len, &overlapped);
112
113                 if(!status) {
114                         if(GetLastError() == ERROR_IO_PENDING) {
115                                 WaitForSingleObject(overlapped.hEvent, INFINITE);
116                                 if(!GetOverlappedResult(device_handle, &overlapped, &len, FALSE))
117                                         continue;
118                         } else {
119                                 logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
120                                            device, strerror(errno));
121                                 return -1;
122                         }
123                 }
124
125                 if(send(sock, buf, len, 0) <= 0)
126                         return -1;
127         }
128 }
129
130 bool setup_device(void)
131 {
132         HKEY key, key2;
133         int i;
134
135         char regpath[1024];
136         char adapterid[1024];
137         char adaptername[1024];
138         char tapname[1024];
139         long len;
140         unsigned long status;
141
142         bool found = false;
143
144         int sock, err;
145         HANDLE thread;
146
147         struct addrinfo *ai;
148         struct addrinfo hint = {
149                 .ai_family = AF_UNSPEC,
150                 .ai_socktype = SOCK_DGRAM,
151                 .ai_protocol = IPPROTO_UDP,
152                 .ai_flags = 0,
153         };
154
155         cp();
156
157         get_config_string(lookup_config(config_tree, "Device"), &device);
158         get_config_string(lookup_config(config_tree, "Interface"), &iface);
159
160         /* Open registry and look for network adapters */
161
162         if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_CONTROL_NET, 0, KEY_READ, &key)) {
163                 logger(LOG_ERR, _("Unable to read registry: %s"), winerror(GetLastError()));
164                 return false;
165         }
166
167         for (i = 0; ; i++) {
168                 len = sizeof(adapterid);
169                 if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
170                         break;
171
172                 /* Find out more about this adapter */
173
174                 snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", REG_CONTROL_NET, adapterid);
175
176                 if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
177                         continue;
178
179                 len = sizeof(adaptername);
180                 err = RegQueryValueEx(key2, "Name", 0, 0, adaptername, &len);
181
182                 RegCloseKey(key2);
183
184                 if(err)
185                         continue;
186
187                 if(device) {
188                         if(!strcmp(device, adapterid)) {
189                                 found = true;
190                                 break;
191                         } else
192                                 continue;
193                 }
194
195                 if(iface) {
196                         if(!strcmp(iface, adaptername)) {
197                                 found = true;
198                                 break;
199                         } else
200                                 continue;
201                 }
202
203                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
204                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
205                 if(device_handle != INVALID_HANDLE_VALUE) {
206                         found = true;
207                         break;
208                 }
209         }
210
211         RegCloseKey(key);
212
213         if(!found) {
214                 logger(LOG_ERR, _("No Windows tap device found!"));
215                 return false;
216         }
217
218         if(!device)
219                 device = xstrdup(adapterid);
220
221         if(!iface)
222                 iface = xstrdup(adaptername);
223
224         /* Try to open the corresponding tap device */
225
226         if(device_handle == INVALID_HANDLE_VALUE) {
227                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);
228                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
229         }
230         
231         if(device_handle == INVALID_HANDLE_VALUE) {
232                 logger(LOG_ERR, _("%s (%s) is not a usable Windows tap device: %s"), device, iface, winerror(GetLastError()));
233                 return false;
234         }
235
236         /* Get MAC address from tap device */
237
238         if(!DeviceIoControl(device_handle, TAP_IOCTL_GET_MAC, mymac.x, sizeof(mymac.x), mymac.x, sizeof(mymac.x), &len, 0)) {
239                 logger(LOG_ERR, _("Could not get MAC address from Windows tap device %s (%s): %s"), device, iface, winerror(GetLastError()));
240                 return false;
241         }
242
243         if(routing_mode == RMODE_ROUTER) {
244                 overwrite_mac = 1;
245         }
246
247         /* Create a listening socket */
248
249         err = getaddrinfo(NULL, myport, &hint, &ai);
250
251         if(err || !ai) {
252                 logger(LOG_ERR, _("System call `%s' failed: %s"), "getaddrinfo", gai_strerror(errno));
253                 return false;
254         }
255
256         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
257
258         if(sock < 0) {
259                 logger(LOG_ERR, _("System call `%s' failed: %s"), "socket", strerror(errno));
260                 return false;
261         }
262
263         if(bind(sock, ai->ai_addr, ai->ai_addrlen)) {
264                 logger(LOG_ERR, _("System call `%s' failed: %s"), "bind", strerror(errno));
265                 return false;
266         }
267
268         freeaddrinfo(ai);
269
270         if(listen(sock, 1)) {
271                 logger(LOG_ERR, _("System call `%s' failed: %s"), "listen", strerror(errno));
272                 return false;
273         }
274
275         /* Start the tap reader */
276
277         thread = CreateThread(NULL, 0, tapreader, NULL, 0, NULL);
278
279         if(!thread) {
280                 logger(LOG_ERR, _("System call `%s' failed: %s"), "CreateThread", winerror(GetLastError()));
281                 return false;
282         }
283
284         /* Wait for the tap reader to connect back to us */
285
286         if((device_fd = accept(sock, NULL, 0)) == -1) {
287                 logger(LOG_ERR, _("System call `%s' failed: %s"), "accept", strerror(errno));
288                 return false;
289         }
290
291         closesocket(sock);
292
293         /* Set media status for newer TAP-Win32 devices */
294
295         status = true;
296         DeviceIoControl(device_handle, TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status), &len, NULL);
297
298         device_info = _("Windows tap device");
299
300         logger(LOG_INFO, _("%s (%s) is a %s"), device, iface, device_info);
301
302         return true;
303 }
304
305 void close_device(void)
306 {
307         cp();
308
309         CloseHandle(device_handle);
310 }
311
312 bool read_packet(vpn_packet_t *packet)
313 {
314         int lenin;
315
316         cp();
317
318         if((lenin = recv(device_fd, packet->data, MTU, 0)) <= 0) {
319                 logger(LOG_ERR, _("Error while reading from %s %s: %s"), device_info,
320                            device, strerror(errno));
321                 return false;
322         }
323         
324         packet->len = lenin;
325
326         device_total_in += packet->len;
327
328         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Read packet of %d bytes from %s"), packet->len,
329                            device_info);
330
331         return true;
332 }
333
334 bool write_packet(vpn_packet_t *packet)
335 {
336         long lenout;
337         OVERLAPPED overlapped = {0};
338
339         cp();
340
341         ifdebug(TRAFFIC) logger(LOG_DEBUG, _("Writing packet of %d bytes to %s"),
342                            packet->len, device_info);
343
344         if(!WriteFile(device_handle, packet->data, packet->len, &lenout, &overlapped)) {
345                 logger(LOG_ERR, _("Error while writing to %s %s: %s"), device_info, device, winerror(GetLastError()));
346                 return false;
347         }
348
349         device_total_out += packet->len;
350
351         return true;
352 }
353
354 void dump_device_stats(void)
355 {
356         cp();
357
358         logger(LOG_DEBUG, _("Statistics for %s %s:"), device_info, device);
359         logger(LOG_DEBUG, _(" total bytes in:  %10d"), device_total_in);
360         logger(LOG_DEBUG, _(" total bytes out: %10d"), device_total_out);
361 }