BTap.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /**
  2. * @file BTap.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <string.h>
  30. #include <stdio.h>
  31. #ifdef BADVPN_USE_WINAPI
  32. #include <windows.h>
  33. #include <winioctl.h>
  34. #include <objbase.h>
  35. #include <wtypes.h>
  36. #include "wintap-common.h"
  37. #include <tuntap/tapwin32-funcs.h>
  38. #else
  39. #include <fcntl.h>
  40. #include <unistd.h>
  41. #include <errno.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/types.h>
  44. #include <sys/stat.h>
  45. #include <sys/socket.h>
  46. #include <net/if.h>
  47. #include <net/if_arp.h>
  48. #ifdef BADVPN_LINUX
  49. #include <linux/if_tun.h>
  50. #endif
  51. #ifdef BADVPN_FREEBSD
  52. #include <net/if_tun.h>
  53. #include <net/if_tap.h>
  54. #endif
  55. #endif
  56. #include <base/BLog.h>
  57. #include <tuntap/BTap.h>
  58. #include <generated/blog_channel_BTap.h>
  59. static void report_error (BTap *o);
  60. static void output_handler_recv (BTap *o, uint8_t *data);
  61. #ifdef BADVPN_USE_WINAPI
  62. static void recv_olap_handler (BTap *o, int event, DWORD bytes)
  63. {
  64. DebugObject_Access(&o->d_obj);
  65. ASSERT(o->output_packet)
  66. ASSERT(event == BREACTOR_IOCP_EVENT_SUCCEEDED || event == BREACTOR_IOCP_EVENT_FAILED)
  67. // set no output packet
  68. o->output_packet = NULL;
  69. if (event == BREACTOR_IOCP_EVENT_FAILED) {
  70. BLog(BLOG_ERROR, "read operation failed");
  71. report_error(o);
  72. return;
  73. }
  74. ASSERT(bytes >= 0)
  75. ASSERT(bytes <= o->frame_mtu)
  76. // done
  77. PacketRecvInterface_Done(&o->output, bytes);
  78. }
  79. #else
  80. static void fd_handler (BTap *o, int events)
  81. {
  82. DebugObject_Access(&o->d_obj);
  83. DebugError_AssertNoError(&o->d_err);
  84. if (events&(BREACTOR_ERROR|BREACTOR_HUP)) {
  85. BLog(BLOG_WARNING, "device fd reports error?");
  86. }
  87. if (events&BREACTOR_READ) do {
  88. ASSERT(o->output_packet)
  89. // try reading into the buffer
  90. int bytes = read(o->fd, o->output_packet, o->frame_mtu);
  91. if (bytes < 0) {
  92. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  93. // retry later
  94. break;
  95. }
  96. // report fatal error
  97. report_error(o);
  98. return;
  99. }
  100. ASSERT_FORCE(bytes <= o->frame_mtu)
  101. // set no output packet
  102. o->output_packet = NULL;
  103. // update events
  104. o->poll_events &= ~BREACTOR_READ;
  105. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  106. // inform receiver we finished the packet
  107. PacketRecvInterface_Done(&o->output, bytes);
  108. } while (0);
  109. }
  110. #endif
  111. void report_error (BTap *o)
  112. {
  113. DEBUGERROR(&o->d_err, o->handler_error(o->handler_error_user));
  114. }
  115. void output_handler_recv (BTap *o, uint8_t *data)
  116. {
  117. DebugObject_Access(&o->d_obj);
  118. DebugError_AssertNoError(&o->d_err);
  119. ASSERT(data)
  120. ASSERT(!o->output_packet)
  121. #ifdef BADVPN_USE_WINAPI
  122. memset(&o->recv_olap.olap, 0, sizeof(o->recv_olap.olap));
  123. // read
  124. BOOL res = ReadFile(o->device, data, o->frame_mtu, NULL, &o->recv_olap.olap);
  125. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  126. BLog(BLOG_ERROR, "ReadFile failed (%u)", GetLastError());
  127. report_error(o);
  128. return;
  129. }
  130. o->output_packet = data;
  131. #else
  132. // attempt read
  133. int bytes = read(o->fd, data, o->frame_mtu);
  134. if (bytes < 0) {
  135. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  136. // retry later in fd_handler
  137. // remember packet
  138. o->output_packet = data;
  139. // update events
  140. o->poll_events |= BREACTOR_READ;
  141. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  142. return;
  143. }
  144. // report fatal error
  145. report_error(o);
  146. return;
  147. }
  148. ASSERT_FORCE(bytes <= o->frame_mtu)
  149. PacketRecvInterface_Done(&o->output, bytes);
  150. #endif
  151. }
  152. int BTap_Init (BTap *o, BReactor *reactor, char *devname, BTap_handler_error handler_error, void *handler_error_user, int tun)
  153. {
  154. ASSERT(tun == 0 || tun == 1)
  155. // init arguments
  156. o->reactor = reactor;
  157. o->handler_error = handler_error;
  158. o->handler_error_user = handler_error_user;
  159. #ifdef BADVPN_USE_WINAPI
  160. // parse device specification
  161. if (!devname) {
  162. BLog(BLOG_ERROR, "no device specification provided");
  163. goto fail0;
  164. }
  165. char *device_component_id;
  166. char *device_name;
  167. uint32_t tun_addrs[3];
  168. if (tun) {
  169. if (!tapwin32_parse_tun_spec(devname, &device_component_id, &device_name, tun_addrs)) {
  170. BLog(BLOG_ERROR, "failed to parse TUN device specification");
  171. goto fail0;
  172. }
  173. } else {
  174. if (!tapwin32_parse_tap_spec(devname, &device_component_id, &device_name)) {
  175. BLog(BLOG_ERROR, "failed to parse TAP device specification");
  176. goto fail0;
  177. }
  178. }
  179. // locate device path
  180. char device_path[TAPWIN32_MAX_REG_SIZE];
  181. BLog(BLOG_INFO, "Looking for TAP-Win32 with component ID %s, name %s", device_component_id, device_name);
  182. if (!tapwin32_find_device(device_component_id, device_name, &device_path)) {
  183. BLog(BLOG_ERROR, "Could not find device");
  184. goto fail1;
  185. }
  186. // open device
  187. BLog(BLOG_INFO, "Opening device %s", device_path);
  188. o->device = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED, 0);
  189. if (o->device == INVALID_HANDLE_VALUE) {
  190. BLog(BLOG_ERROR, "CreateFile failed");
  191. goto fail1;
  192. }
  193. // set TUN if needed
  194. DWORD len;
  195. if (tun) {
  196. if (!DeviceIoControl(o->device, TAP_IOCTL_CONFIG_TUN, tun_addrs, sizeof(tun_addrs), tun_addrs, sizeof(tun_addrs), &len, NULL)) {
  197. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_CONFIG_TUN) failed");
  198. goto fail2;
  199. }
  200. }
  201. // get MTU
  202. ULONG umtu;
  203. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  204. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  205. goto fail2;
  206. }
  207. if (tun) {
  208. o->frame_mtu = umtu;
  209. } else {
  210. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  211. }
  212. // set connected
  213. ULONG upstatus = TRUE;
  214. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  215. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  216. goto fail2;
  217. }
  218. BLog(BLOG_INFO, "Device opened");
  219. // associate device with IOCP
  220. if (!CreateIoCompletionPort(o->device, BReactor_GetIOCPHandle(o->reactor), 0, 0)) {
  221. BLog(BLOG_ERROR, "CreateIoCompletionPort failed");
  222. goto fail2;
  223. }
  224. // init send olap
  225. BReactorIOCPOverlapped_Init(&o->send_olap, o->reactor, o, NULL);
  226. // init recv olap
  227. BReactorIOCPOverlapped_Init(&o->recv_olap, o->reactor, o, (BReactorIOCPOverlapped_handler)recv_olap_handler);
  228. free(device_name);
  229. free(device_component_id);
  230. goto success;
  231. fail2:
  232. ASSERT_FORCE(CloseHandle(o->device))
  233. fail1:
  234. free(device_name);
  235. free(device_component_id);
  236. fail0:
  237. return 0;
  238. #endif
  239. #if defined(BADVPN_LINUX) || defined(BADVPN_FREEBSD)
  240. char devname_real[IFNAMSIZ];
  241. #ifdef BADVPN_LINUX
  242. // open device
  243. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  244. BLog(BLOG_ERROR, "error opening device");
  245. goto fail0;
  246. }
  247. // configure device
  248. struct ifreq ifr;
  249. memset(&ifr, 0, sizeof(ifr));
  250. ifr.ifr_flags |= IFF_NO_PI;
  251. if (tun) {
  252. ifr.ifr_flags |= IFF_TUN;
  253. } else {
  254. ifr.ifr_flags |= IFF_TAP;
  255. }
  256. if (devname) {
  257. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", devname);
  258. }
  259. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  260. BLog(BLOG_ERROR, "error configuring device");
  261. goto fail1;
  262. }
  263. strcpy(devname_real, ifr.ifr_name);
  264. #endif
  265. #ifdef BADVPN_FREEBSD
  266. if (tun) {
  267. BLog(BLOG_ERROR, "TUN not supported on FreeBSD");
  268. goto fail0;
  269. }
  270. if (!devname) {
  271. BLog(BLOG_ERROR, "no device specified");
  272. goto fail0;
  273. }
  274. // open device
  275. char devnode[10 + IFNAMSIZ];
  276. snprintf(devnode, sizeof(devnode), "/dev/%s", devname);
  277. if ((o->fd = open(devnode, O_RDWR)) < 0) {
  278. BLog(BLOG_ERROR, "error opening device");
  279. goto fail0;
  280. }
  281. // get name
  282. struct ifreq ifr;
  283. memset(&ifr, 0, sizeof(ifr));
  284. if (ioctl(o->fd, TAPGIFNAME, (void *)&ifr) < 0) {
  285. BLog(BLOG_ERROR, "error configuring device");
  286. goto fail1;
  287. }
  288. strcpy(devname_real, ifr.ifr_name);
  289. #endif
  290. // get MTU
  291. // open dummy socket for ioctls
  292. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  293. if (sock < 0) {
  294. BLog(BLOG_ERROR, "socket failed");
  295. goto fail1;
  296. }
  297. memset(&ifr, 0, sizeof(ifr));
  298. strcpy(ifr.ifr_name, devname_real);
  299. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  300. BLog(BLOG_ERROR, "error getting MTU");
  301. close(sock);
  302. goto fail1;
  303. }
  304. if (tun) {
  305. o->frame_mtu = ifr.ifr_mtu;
  306. } else {
  307. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  308. }
  309. close(sock);
  310. // set non-blocking
  311. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  312. BLog(BLOG_ERROR, "cannot set non-blocking");
  313. goto fail1;
  314. }
  315. // init file descriptor object
  316. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  317. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  318. BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  319. goto fail1;
  320. }
  321. o->poll_events = 0;
  322. goto success;
  323. fail1:
  324. ASSERT_FORCE(close(o->fd) == 0)
  325. fail0:
  326. return 0;
  327. #endif
  328. success:
  329. // init output
  330. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  331. // set no output packet
  332. o->output_packet = NULL;
  333. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  334. DebugObject_Init(&o->d_obj);
  335. return 1;
  336. }
  337. void BTap_Free (BTap *o)
  338. {
  339. DebugObject_Free(&o->d_obj);
  340. DebugError_Free(&o->d_err);
  341. // free output
  342. PacketRecvInterface_Free(&o->output);
  343. #ifdef BADVPN_USE_WINAPI
  344. // cancel I/O
  345. ASSERT_FORCE(CancelIo(o->device))
  346. // wait receiving to finish
  347. if (o->output_packet) {
  348. BLog(BLOG_DEBUG, "waiting for receiving to finish");
  349. BReactorIOCPOverlapped_Wait(&o->recv_olap, NULL, NULL);
  350. }
  351. // free recv olap
  352. BReactorIOCPOverlapped_Free(&o->recv_olap);
  353. // free send olap
  354. BReactorIOCPOverlapped_Free(&o->send_olap);
  355. // close device
  356. ASSERT_FORCE(CloseHandle(o->device))
  357. #else
  358. // free BFileDescriptor
  359. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  360. // close file descriptor
  361. ASSERT_FORCE(close(o->fd) == 0)
  362. #endif
  363. }
  364. int BTap_GetMTU (BTap *o)
  365. {
  366. DebugObject_Access(&o->d_obj);
  367. return o->frame_mtu;
  368. }
  369. void BTap_Send (BTap *o, uint8_t *data, int data_len)
  370. {
  371. DebugObject_Access(&o->d_obj);
  372. DebugError_AssertNoError(&o->d_err);
  373. ASSERT(data_len >= 0)
  374. ASSERT(data_len <= o->frame_mtu)
  375. #ifdef BADVPN_USE_WINAPI
  376. // ignore frames without an Ethernet header, or we get errors in WriteFile
  377. if (data_len < 14) {
  378. return;
  379. }
  380. memset(&o->send_olap.olap, 0, sizeof(o->send_olap.olap));
  381. // write
  382. BOOL res = WriteFile(o->device, data, data_len, NULL, &o->send_olap.olap);
  383. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  384. BLog(BLOG_ERROR, "WriteFile failed (%u)", GetLastError());
  385. return;
  386. }
  387. // wait
  388. int succeeded;
  389. DWORD bytes;
  390. BReactorIOCPOverlapped_Wait(&o->send_olap, &succeeded, &bytes);
  391. if (!succeeded) {
  392. BLog(BLOG_ERROR, "write operation failed");
  393. } else {
  394. ASSERT(bytes >= 0)
  395. ASSERT(bytes <= data_len)
  396. if (bytes < data_len) {
  397. BLog(BLOG_ERROR, "write operation didn't write everything");
  398. }
  399. }
  400. #else
  401. int bytes = write(o->fd, data, data_len);
  402. if (bytes < 0) {
  403. // malformed packets will cause errors, ignore them and act like
  404. // the packet was accepeted
  405. } else {
  406. if (bytes != data_len) {
  407. BLog(BLOG_WARNING, "written %d expected %d", bytes, data_len);
  408. }
  409. }
  410. #endif
  411. }
  412. PacketRecvInterface * BTap_GetOutput (BTap *o)
  413. {
  414. DebugObject_Access(&o->d_obj);
  415. return &o->output;
  416. }