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