235e0fd6d64ae0692cce26dbb3c16f7fe2c997a7
[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-2014 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 along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "../system.h"
22
23 #include <windows.h>
24 #include <winioctl.h>
25
26 #include "../conf.h"
27 #include "../device.h"
28 #include "../logger.h"
29 #include "../net.h"
30 #include "../route.h"
31 #include "../utils.h"
32 #include "../xalloc.h"
33
34 #include "common.h"
35
36 int device_fd = -1;
37 static HANDLE device_handle = INVALID_HANDLE_VALUE;
38 char *device = NULL;
39 char *iface = NULL;
40 static char *device_info = NULL;
41
42 static uint64_t device_total_in = 0;
43 static uint64_t device_total_out = 0;
44
45 extern char *myport;
46
47 static DWORD WINAPI tapreader(void *bla) {
48         int status;
49         DWORD len;
50         OVERLAPPED overlapped;
51         vpn_packet_t packet;
52         int errors = 0;
53
54         logger(LOG_DEBUG, "Tap reader running");
55
56         /* Read from tap device and send to parent */
57
58         overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
59
60         for(;;) {
61                 overlapped.Offset = 0;
62                 overlapped.OffsetHigh = 0;
63                 ResetEvent(overlapped.hEvent);
64
65                 status = ReadFile(device_handle, packet.data, MTU, &len, &overlapped);
66
67                 if(!status) {
68                         if(GetLastError() == ERROR_IO_PENDING) {
69                                 WaitForSingleObject(overlapped.hEvent, INFINITE);
70                                 if(!GetOverlappedResult(device_handle, &overlapped, &len, FALSE))
71                                         continue;
72                         } else {
73                                 logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
74                                            device, strerror(errno));
75                                 errors++;
76                                 if(errors >= 10) {
77                                         EnterCriticalSection(&mutex);
78                                         running = false;
79                                         LeaveCriticalSection(&mutex);
80                                 }
81                                 usleep(1000000);
82                                 continue;
83                         }
84                 }
85
86                 errors = 0;
87                 packet.len = len;
88                 packet.priority = 0;
89
90                 EnterCriticalSection(&mutex);
91                 route(myself, &packet);
92                 LeaveCriticalSection(&mutex);
93         }
94
95         return 0;
96 }
97
98 static bool setup_device(void) {
99         HKEY key, key2;
100         int i;
101
102         char regpath[1024];
103         char adapterid[1024];
104         char adaptername[1024];
105         char tapname[1024];
106         DWORD len;
107         unsigned long status;
108
109         bool found = false;
110
111         int err;
112         HANDLE thread;
113
114         get_config_string(lookup_config(config_tree, "Device"), &device);
115         get_config_string(lookup_config(config_tree, "Interface"), &iface);
116
117         /* Open registry and look for network adapters */
118
119         if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, NETWORK_CONNECTIONS_KEY, 0, KEY_READ, &key)) {
120                 logger(LOG_ERR, "Unable to read registry: %s", winerror(GetLastError()));
121                 return false;
122         }
123
124         for (i = 0; ; i++) {
125                 len = sizeof(adapterid);
126                 if(RegEnumKeyEx(key, i, adapterid, &len, 0, 0, 0, NULL))
127                         break;
128
129                 /* Find out more about this adapter */
130
131                 snprintf(regpath, sizeof(regpath), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, adapterid);
132
133                 if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, regpath, 0, KEY_READ, &key2))
134                         continue;
135
136                 len = sizeof(adaptername);
137                 err = RegQueryValueEx(key2, "Name", 0, 0, (LPBYTE)adaptername, &len);
138
139                 RegCloseKey(key2);
140
141                 if(err)
142                         continue;
143
144                 if(device) {
145                         if(!strcmp(device, adapterid)) {
146                                 found = true;
147                                 break;
148                         } else
149                                 continue;
150                 }
151
152                 if(iface) {
153                         if(!strcmp(iface, adaptername)) {
154                                 found = true;
155                                 break;
156                         } else
157                                 continue;
158                 }
159
160                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, adapterid);
161                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
162                 if(device_handle != INVALID_HANDLE_VALUE) {
163                         found = true;
164                         break;
165                 }
166         }
167
168         RegCloseKey(key);
169
170         if(!found) {
171                 logger(LOG_ERR, "No Windows tap device found!");
172                 return false;
173         }
174
175         if(!device)
176                 device = xstrdup(adapterid);
177
178         if(!iface)
179                 iface = xstrdup(adaptername);
180
181         /* Try to open the corresponding tap device */
182
183         if(device_handle == INVALID_HANDLE_VALUE) {
184                 snprintf(tapname, sizeof(tapname), USERMODEDEVICEDIR "%s" TAPSUFFIX, device);
185                 device_handle = CreateFile(tapname, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
186         }
187         
188         if(device_handle == INVALID_HANDLE_VALUE) {
189                 logger(LOG_ERR, "%s (%s) is not a usable Windows tap device: %s", device, iface, winerror(GetLastError()));
190                 return false;
191         }
192
193         /* Get MAC address from tap device */
194
195         if(!DeviceIoControl(device_handle, TAP_IOCTL_GET_MAC, mymac.x, sizeof(mymac.x), mymac.x, sizeof(mymac.x), &len, 0)) {
196                 logger(LOG_ERR, "Could not get MAC address from Windows tap device %s (%s): %s", device, iface, winerror(GetLastError()));
197                 return false;
198         }
199
200         if(routing_mode == RMODE_ROUTER) {
201                 overwrite_mac = 1;
202         }
203
204         /* Start the tap reader */
205
206         thread = CreateThread(NULL, 0, tapreader, NULL, 0, NULL);
207
208         if(!thread) {
209                 logger(LOG_ERR, "System call `%s' failed: %s", "CreateThread", winerror(GetLastError()));
210                 return false;
211         }
212
213         /* Set media status for newer TAP-Win32 devices */
214
215         status = true;
216         DeviceIoControl(device_handle, TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status), &len, NULL);
217
218         device_info = "Windows tap device";
219
220         logger(LOG_INFO, "%s (%s) is a %s", device, iface, device_info);
221
222         return true;
223 }
224
225 static void close_device(void) {
226         CloseHandle(device_handle);
227
228         free(device);
229         free(iface);
230 }
231
232 static bool read_packet(vpn_packet_t *packet) {
233         return false;
234 }
235
236 static bool write_packet(vpn_packet_t *packet) {
237         DWORD lenout;
238         OVERLAPPED overlapped = {0};
239
240         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
241                            packet->len, device_info);
242
243         if(!WriteFile(device_handle, packet->data, packet->len, &lenout, &overlapped)) {
244                 logger(LOG_ERR, "Error while writing to %s %s: %s", device_info, device, winerror(GetLastError()));
245                 return false;
246         }
247
248         device_total_out += packet->len;
249
250         return true;
251 }
252
253 static void dump_device_stats(void) {
254         logger(LOG_DEBUG, "Statistics for %s %s:", device_info, device);
255         logger(LOG_DEBUG, " total bytes in:  %10"PRIu64, device_total_in);
256         logger(LOG_DEBUG, " total bytes out: %10"PRIu64, device_total_out);
257 }
258
259 const devops_t os_devops = {
260         .setup = setup_device,
261         .close = close_device,
262         .read = read_packet,
263         .write = write_packet,
264         .dump_stats = dump_device_stats,
265 };