2 fd_device.c -- Interaction with Android tun fd
3 Copyright (C) 2001-2005 Ivo Timmermans,
4 2001-2016 Guus Sliepen <guus@tinc-vpn.org>
5 2009 Grzegorz Dymarek <gregd72002@googlemail.com>
6 2016 Pacien TRAN-GIRARD <pacien@pacien.net>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License along
19 with this program; if not, write to the Free Software Foundation, Inc.,
20 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
32 static inline bool check_config(void) {
33 if(routing_mode == RMODE_SWITCH) {
34 logger(DEBUG_ALWAYS, LOG_ERR, "Switch mode not supported (requires unsupported TAP device)!");
38 if(!get_config_int(lookup_config(config_tree, "Device"), &device_fd)) {
39 logger(DEBUG_ALWAYS, LOG_ERR, "Could not read fd from configuration!");
46 static bool setup_device(void) {
52 logger(DEBUG_ALWAYS, LOG_ERR, "Could not open %s: %s!", device, strerror(errno));
56 logger(DEBUG_ALWAYS, LOG_INFO, "fd/%d adapter set up.", device_fd);
61 static void close_device(void) {
66 static inline uint16_t get_ip_ethertype(vpn_packet_t *packet) {
67 switch(DATA(packet)[ETH_HLEN] >> 4) {
79 static inline void set_etherheader(vpn_packet_t *packet, uint16_t ethertype) {
80 memset(DATA(packet), 0, ETH_HLEN - ETHER_TYPE_LEN);
82 DATA(packet)[ETH_HLEN - ETHER_TYPE_LEN] = (ethertype >> 8) & 0xFF;
83 DATA(packet)[ETH_HLEN - ETHER_TYPE_LEN + 1] = ethertype & 0xFF;
86 static bool read_packet(vpn_packet_t *packet) {
87 int lenin = read(device_fd, DATA(packet) + ETH_HLEN, MTU - ETH_HLEN);
90 logger(DEBUG_ALWAYS, LOG_ERR, "Error while reading from fd/%d: %s!", device_fd, strerror(errno));
94 uint16_t ethertype = get_ip_ethertype(packet);
96 if(ethertype == ETH_P_MAX) {
97 logger(DEBUG_TRAFFIC, LOG_ERR, "Unknown IP version while reading packet from fd/%d!", device_fd);
101 set_etherheader(packet, ethertype);
102 packet->len = lenin + ETH_HLEN;
104 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Read packet of %d bytes from fd/%d.", packet->len, device_fd);
109 static bool write_packet(vpn_packet_t *packet) {
110 logger(DEBUG_TRAFFIC, LOG_DEBUG, "Writing packet of %d bytes to fd/%d.", packet->len, device_fd);
112 if(write(device_fd, DATA(packet) + ETH_HLEN, packet->len - ETH_HLEN) < 0) {
113 logger(DEBUG_ALWAYS, LOG_ERR, "Error while writing to fd/%d: %s!", device_fd, strerror(errno));
120 const devops_t fd_devops = {
121 .setup = setup_device,
122 .close = close_device,
124 .write = write_packet,