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