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