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