A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
tap-creator.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2009 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7#include "tap-encode-decode.h"
8
9#include "ns3/mac48-address.h"
10
11#include <cerrno>
12#include <cstdlib>
13#include <cstring> // for strerror
14#include <fcntl.h>
15#include <iomanip>
16#include <iostream>
17#include <linux/if_tun.h>
18#include <net/if.h>
19#include <net/route.h>
20#include <netinet/in.h>
21#include <sstream>
22#include <stdint.h>
23#include <string>
24#include <sys/ioctl.h>
25#include <sys/socket.h>
26#include <sys/types.h>
27#include <sys/un.h>
28#include <unistd.h>
29
30#define TAP_MAGIC 95549
31
32static bool gVerbose = false; // Set to true to turn on logging messages.
33
34#define LOG(msg) \
35 if (gVerbose) \
36 { \
37 std::cout << __FUNCTION__ << "(): " << msg << std::endl; \
38 }
39
40#define ABORT(msg, printErrno) \
41 std::cout << __FILE__ << ": fatal error at line " << __LINE__ << ": " << __FUNCTION__ \
42 << "(): " << msg << std::endl; \
43 if (printErrno) \
44 { \
45 std::cout << " errno = " << errno << " (" << std::strerror(errno) << ")" << std::endl; \
46 } \
47 std::exit(-1);
48
49#define ABORT_IF(cond, msg, printErrno) \
50 if (cond) \
51 { \
52 ABORT(msg, printErrno); \
53 }
54
55static sockaddr
57{
58 union {
59 struct sockaddr any_socket;
60 struct sockaddr_in si;
61 } s;
62
63 s.si.sin_family = AF_INET;
64 s.si.sin_port = 0; // unused
65 s.si.sin_addr.s_addr = htonl(networkOrder);
66 return s.any_socket;
67}
68
69static void
70SendSocket(const char* path, int fd)
71{
72 //
73 // Open a Unix (local interprocess) socket to call back to the tap bridge
74 //
75 LOG("Create Unix socket");
76 int sock = socket(PF_UNIX, SOCK_DGRAM, 0);
77 ABORT_IF(sock == -1, "Unable to open socket", 1);
78
79 //
80 // We have this string called path, which is really a hex representation
81 // of the endpoint that the tap bridge created. It used a forward encoding
82 // method (TapBufferToString) to take the sockaddr_un it made and passed
83 // the resulting string to us. So we need to take the inverse method
84 // (TapStringToBuffer) and build the same sockaddr_un over here.
85 //
86 socklen_t clientAddrLen;
87 struct sockaddr_un clientAddr;
88
89 LOG("Decode address " << path);
90 bool rc = ns3::TapStringToBuffer(path, (uint8_t*)&clientAddr, &clientAddrLen);
91 ABORT_IF(rc == false, "Unable to decode path", 0);
92
93 LOG("Connect");
94 int status = connect(sock, (struct sockaddr*)&clientAddr, clientAddrLen);
95 ABORT_IF(status == -1, "Unable to connect to tap bridge", 1);
96
97 LOG("Connected");
98
99 //
100 // This is arcane enough that a few words are worthwhile to explain what's
101 // going on here.
102 //
103 // The interesting information (the socket FD) is going to go back to the
104 // tap bridge as an integer of ancillary data. Ancillary data is bits
105 // that are not a part a socket payload (out-of-band data). We're also
106 // going to send one integer back. It's just initialized to a magic number
107 // we use to make sure that the tap bridge is talking to the tap socket
108 // creator and not some other creator process (emu, specifically)
109 //
110 // The struct iovec below is part of a scatter-gather list. It describes a
111 // buffer. In this case, it describes a buffer (an integer) containing the
112 // data that we're going to send back to the tap bridge (that magic number).
113 //
114 struct iovec iov;
115 uint32_t magic = TAP_MAGIC;
116 iov.iov_base = &magic;
117 iov.iov_len = sizeof(magic);
118
119 //
120 // The CMSG macros you'll see below are used to create and access control
121 // messages (which is another name for ancillary data). The ancillary
122 // data is made up of pairs of struct cmsghdr structures and associated
123 // data arrays.
124 //
125 // First, we're going to allocate a buffer on the stack to contain our
126 // data array (that contains the socket). Sometimes you'll see this called
127 // an "ancillary element" but the msghdr uses the control message termimology
128 // so we call it "control."
129 //
130 constexpr size_t msg_size = sizeof(int);
131 char control[CMSG_SPACE(msg_size)];
132
133 //
134 // There is a msghdr that is used to minimize the number of parameters
135 // passed to sendmsg (which we will use to send our ancillary data). This
136 // structure uses terminology corresponding to control messages, so you'll
137 // see msg_control, which is the pointer to the ancillary data and controllen
138 // which is the size of the ancillary data array.
139 //
140 // So, initialize the message header that describes our ancillary/control data
141 // and point it to the control message/ancillary data we just allocated space
142 // for.
143 //
144 struct msghdr msg;
145 msg.msg_name = nullptr;
146 msg.msg_namelen = 0;
147 msg.msg_iov = &iov;
148 msg.msg_iovlen = 1;
149 msg.msg_control = control;
150 msg.msg_controllen = sizeof(control);
151 msg.msg_flags = 0;
152
153 //
154 // A cmsghdr contains a length field that is the length of the header and
155 // the data. It has a cmsg_level field corresponding to the originating
156 // protocol. This takes values which are legal levels for getsockopt and
157 // setsockopt (here SOL_SOCKET). We're going to use the SCM_RIGHTS type of
158 // cmsg, that indicates that the ancillary data array contains access rights
159 // that we are sending back to the tap bridge.
160 //
161 // We have to put together the first (and only) cmsghdr that will describe
162 // the whole package we're sending.
163 //
164 struct cmsghdr* cmsg;
165 cmsg = CMSG_FIRSTHDR(&msg);
166 cmsg->cmsg_level = SOL_SOCKET;
167 cmsg->cmsg_type = SCM_RIGHTS;
168 cmsg->cmsg_len = CMSG_LEN(msg_size);
169 //
170 // We also have to update the controllen in case other stuff is actually
171 // in there we may not be aware of (due to macros).
172 //
173 msg.msg_controllen = cmsg->cmsg_len;
174
175 //
176 // Finally, we get a pointer to the start of the ancillary data array and
177 // put our file descriptor in.
178 //
179 int* fdptr = (int*)(CMSG_DATA(cmsg));
180 *fdptr = fd; //
181
182 //
183 // Actually send the file descriptor back to the tap bridge.
184 //
185 ssize_t len = sendmsg(sock, &msg, 0);
186 ABORT_IF(len == -1, "Could not send socket back to tap bridge", 1);
187
188 LOG("sendmsg complete");
189}
190
191static int
192CreateTap(const char* dev, const char* ip, const char* mac, const char* mode, const char* netmask)
193{
194 //
195 // Creation and management of Tap devices is done via the tun device
196 //
197 int tap = open("/dev/net/tun", O_RDWR);
198 ABORT_IF(tap == -1, "Could not open /dev/net/tun", true);
199
200 //
201 // Allocate a tap device, making sure that it will not send the tun_pi header.
202 // If we provide a null name to the ifr.ifr_name, we tell the kernel to pick
203 // a name for us (i.e., tapn where n = 0..255.
204 //
205 // If the device does not already exist, the system will create one.
206 //
207 struct ifreq ifr;
208 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
209 strcpy(ifr.ifr_name, dev);
210 int status = ioctl(tap, TUNSETIFF, (void*)&ifr);
211 ABORT_IF(status == -1, "Could not allocate tap device", true);
212
213 std::string tapDeviceName = (char*)ifr.ifr_name;
214 LOG("Allocated TAP device " << tapDeviceName);
215
216 //
217 // Operating mode "2" corresponds to USE_LOCAL and "3" to USE_BRIDGE mode.
218 // This means that we expect that the user will have named, created and
219 // configured a network tap that we are just going to use. So don't mess
220 // up his hard work by changing anything, just return the tap fd.
221 //
222 if (std::string(mode) == "2" || std::string(mode) == "3")
223 {
224 LOG("Returning precreated tap ");
225 return tap;
226 }
227
228 //
229 // Set the hardware (MAC) address of the new device
230 //
231 ifr.ifr_hwaddr.sa_family = 1; // this is ARPHRD_ETHER from if_arp.h
232 ns3::Mac48Address(mac).CopyTo((uint8_t*)ifr.ifr_hwaddr.sa_data);
233 status = ioctl(tap, SIOCSIFHWADDR, &ifr);
234 ABORT_IF(status == -1, "Could not set MAC address", true);
235 LOG("Set device MAC address to " << mac);
236
237 int fd = socket(AF_INET, SOCK_DGRAM, 0);
238
239 //
240 // Bring the interface up.
241 //
242 status = ioctl(fd, SIOCGIFFLAGS, &ifr);
243 ABORT_IF(status == -1, "Could not get flags for interface", true);
244 ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
245 status = ioctl(fd, SIOCSIFFLAGS, &ifr);
246 ABORT_IF(status == -1, "Could not bring interface up", true);
247 LOG("Device is up");
248
249 //
250 // Set the IP address of the new interface/device.
251 //
252 ifr.ifr_addr = CreateInetAddress(ns3::Ipv4Address(ip).Get());
253 status = ioctl(fd, SIOCSIFADDR, &ifr);
254 ABORT_IF(status == -1, "Could not set IP address", true);
255 LOG("Set device IP address to " << ip);
256
257 //
258 // Set the net mask of the new interface/device
259 //
260 ifr.ifr_netmask = CreateInetAddress(ns3::Ipv4Mask(netmask).Get());
261 status = ioctl(fd, SIOCSIFNETMASK, &ifr);
262 ABORT_IF(status == -1, "Could not set net mask", true);
263 LOG("Set device Net Mask to " << netmask);
264
265 return tap;
266}
267
268int
269main(int argc, char* argv[])
270{
271 int c;
272 char* dev = (char*)"";
273 char* ip = nullptr;
274 char* mac = nullptr;
275 char* netmask = nullptr;
276 char* operatingMode = nullptr;
277 char* path = nullptr;
278
279 opterr = 0;
280
281 while ((c = getopt(argc, argv, "vd:i:m:n:o:p:")) != -1)
282 {
283 switch (c)
284 {
285 case 'd':
286 dev = optarg; // name of the new tap device
287 break;
288 case 'i':
289 ip = optarg; // ip address of the new device
290 break;
291 case 'm':
292 mac = optarg; // mac address of the new device
293 break;
294 case 'n':
295 netmask = optarg; // net mask for the new device
296 break;
297 case 'o':
298 operatingMode = optarg; // operating mode of tap bridge
299 break;
300 case 'p':
301 path = optarg; // path back to the tap bridge
302 break;
303 case 'v':
304 gVerbose = true;
305 break;
306 }
307 }
308
309 //
310 // We have got to be able to coordinate the name of the tap device we are
311 // going to create and or open with the device that an external Linux host
312 // will use. If this name is provided we use it. If not we let the system
313 // create the device for us. This name is given in dev
314 //
315 LOG("Provided Device Name is \"" << dev << "\"");
316
317 //
318 // We have got to be able to assign an IP address to the tap device we are
319 // allocating. This address is allocated in the simulation and assigned to
320 // the tap bridge. This address is given in ip.
321 //
322 ABORT_IF(ip == nullptr, "IP Address is a required argument", 0);
323 LOG("Provided IP Address is \"" << ip << "\"");
324
325 //
326 // We have got to be able to assign a Mac address to the tap device we are
327 // allocating. This address is allocated in the simulation and assigned to
328 // the bridged device. This allows packets addressed to the bridged device
329 // to appear in the Linux host as if they were received there.
330 //
331 ABORT_IF(mac == nullptr, "MAC Address is a required argument", 0);
332 LOG("Provided MAC Address is \"" << mac << "\"");
333
334 //
335 // We have got to be able to assign a net mask to the tap device we are
336 // allocating. This mask is allocated in the simulation and given to
337 // the bridged device.
338 //
339 ABORT_IF(netmask == nullptr, "Net Mask is a required argument", 0);
340 LOG("Provided Net Mask is \"" << netmask << "\"");
341
342 //
343 // We have got to know whether or not to create the TAP.
344 //
345 ABORT_IF(operatingMode == nullptr, "Operating Mode is a required argument", 0);
346 LOG("Provided Operating Mode is \"" << operatingMode << "\"");
347
348 //
349 // This program is spawned by a tap bridge running in a simulation. It
350 // wants to create a socket as described below. We are going to do the
351 // work here since we're running suid root. Once we create the socket,
352 // we have to send it back to the tap bridge. We do that over a Unix
353 // (local interprocess) socket. The tap bridge created a socket to
354 // listen for our response on, and it is expected to have encoded the address
355 // information as a string and to have passed that string as an argument to
356 // us. We see it here as the "path" string. We can't do anything useful
357 // unless we have that string.
358 //
359 ABORT_IF(path == nullptr, "path is a required argument", 0);
360 LOG("Provided path is \"" << path << "\"");
361
362 //
363 // The whole reason for all of the hoops we went through to call out to this
364 // program will pay off here. We created this program to run as suid root
365 // in order to keep the main simulation program from having to be run with
366 // root privileges. We need root privileges to be able to futz with the
367 // Tap device underlying all of this. So all of these hoops are to allow
368 // us to execute the following code:
369 //
370 LOG("Creating Tap");
371 int sock = CreateTap(dev, ip, mac, operatingMode, netmask);
372 ABORT_IF(sock == -1, "main(): Unable to create tap socket", 1);
373
374 //
375 // Send the socket back to the tap net device so it can go about its business
376 //
377 SendSocket(path, sock);
378
379 return 0;
380}
Ipv4 addresses are stored in host order in this class.
a class to represent an Ipv4 address mask
an EUI-48 address
void CopyTo(uint8_t buffer[6]) const
bool TapStringToBuffer(std::string s, uint8_t *buffer, uint32_t *len)
Convert string encoded by the inverse function (TapBufferToString) back into a byte buffer.
mac
Definition third.py:81
static void SendSocket(const char *path, int fd)
#define LOG(msg)
static sockaddr CreateInetAddress(uint32_t networkOrder)
static bool gVerbose
#define ABORT_IF(cond, msg, printErrno)
static int CreateTap(const char *dev, const char *ip, const char *mac, const char *mode, const char *netmask)
#define TAP_MAGIC