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