1 /*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "common/libs/utils/network.h"
18
19 #include <linux/if.h>
20 #include <linux/if_tun.h>
21 #include <string.h>
22
23 #include "common/libs/glog/logging.h"
24
25 namespace cvd {
26 namespace {
27 // This should be the size of virtio_net_hdr_v1, from linux/virtio_net.h, but
28 // the version of that header that ships with android in Pie does not include
29 // that struct (it was added in Q).
30 // This is what that struct looks like:
31 // struct virtio_net_hdr_v1 {
32 // u8 flags;
33 // u8 gso_type;
34 // u16 hdr_len;
35 // u16 gso_size;
36 // u16 csum_start;
37 // u16 csum_offset;
38 // u16 num_buffers;
39 // };
40 static constexpr int SIZE_OF_VIRTIO_NET_HDR_V1 = 12;
41 } // namespace
42
OpenTapInterface(const std::string & interface_name)43 SharedFD OpenTapInterface(const std::string& interface_name) {
44 constexpr auto TUNTAP_DEV = "/dev/net/tun";
45
46 auto tap_fd = SharedFD::Open(TUNTAP_DEV, O_RDWR | O_NONBLOCK);
47 if (!tap_fd->IsOpen()) {
48 LOG(ERROR) << "Unable to open tun device: " << tap_fd->StrError();
49 return tap_fd;
50 }
51
52 struct ifreq ifr;
53 memset(&ifr, 0, sizeof(ifr));
54 ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
55 strncpy(ifr.ifr_name, interface_name.c_str(), IFNAMSIZ);
56
57 int err = tap_fd->Ioctl(TUNSETIFF, &ifr);
58 if (err < 0) {
59 LOG(ERROR) << "Unable to connect to " << interface_name
60 << " tap interface: " << tap_fd->StrError();
61 tap_fd->Close();
62 return cvd::SharedFD();
63 }
64
65 // The interface's configuration may have been modified or just not set
66 // correctly on creation. While qemu checks this and enforces the right
67 // configuration, crosvm does not, so it needs to be set before it's passed to
68 // it.
69 tap_fd->Ioctl(TUNSETOFFLOAD,
70 reinterpret_cast<void*>(TUN_F_CSUM | TUN_F_UFO | TUN_F_TSO4 |
71 TUN_F_TSO6));
72 int len = SIZE_OF_VIRTIO_NET_HDR_V1;
73 tap_fd->Ioctl(TUNSETVNETHDRSZ, &len);
74
75 return tap_fd;
76 }
77 } // namespace cvd
78