A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
tap-fd-net-device-helper.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012 INRIA, 2012 University of Washington
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation;
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 */
17
19
20#include "encode-decode.h"
21
22#include "ns3/abort.h"
23#include "ns3/config.h"
24#include "ns3/fd-net-device.h"
25#include "ns3/log.h"
26#include "ns3/names.h"
27#include "ns3/object-factory.h"
28#include "ns3/packet.h"
29#include "ns3/simulator.h"
30#include "ns3/trace-helper.h"
31
32#include <arpa/inet.h>
33#include <errno.h>
34#include <iomanip>
35#include <iostream>
36#include <limits>
37#include <memory>
38#include <net/ethernet.h>
39#include <net/if.h>
40#include <netinet/in.h>
41#include <netpacket/packet.h>
42#include <stdlib.h>
43#include <string.h>
44#include <string>
45#include <sys/ioctl.h>
46#include <sys/socket.h>
47#include <sys/stat.h>
48#include <sys/un.h>
49#include <sys/wait.h>
50#include <time.h>
51#include <unistd.h>
52
53namespace ns3
54{
55
56NS_LOG_COMPONENT_DEFINE("TapFdNetDeviceHelper");
57
58#define TAP_MAGIC 95549
59
61{
62 m_deviceName = "";
63 m_modePi = false;
67 m_tapPrefix6 = 64;
69}
70
71void
73{
74 m_modePi = modePi;
75}
76
77void
79{
80 m_tapIp4 = address;
81}
82
83void
85{
86 m_tapMask4 = mask;
87}
88
89void
91{
92 m_tapIp6 = address;
93}
94
95void
97{
98 m_tapPrefix6 = prefix;
99}
100
101void
103{
104 m_tapMac = mac;
105}
106
109{
111 Ptr<FdNetDevice> device = d->GetObject<FdNetDevice>();
112
113 //
114 // We need to explicitly set the encapsulation mode for the traffic
115 // traversing the TAP device, so the FdNetDevice is able to know
116 // how to treat the traffic in a way that in compatible with the
117 // TAP device.
118 //
119 if (m_modePi)
120 {
121 device->SetEncapsulationMode(FdNetDevice::DIXPI);
122 }
123
124 SetFileDescriptor(device);
125 return device;
126}
127
128void
130{
131 NS_LOG_LOGIC("Creating TAP device");
132
133 //
134 // Call out to a separate process running as suid root in order to create a
135 // TAP device. We do this to avoid having the entire simulation running as root.
136 //
137 int fd = CreateFileDescriptor();
138 device->SetFileDescriptor(fd);
139}
140
141int
143{
144 NS_LOG_FUNCTION(this);
145
146 //
147 // We're going to fork and exec that program soon, but first we need to have
148 // a socket to talk to it with. So we create a local interprocess (Unix)
149 // socket for that purpose.
150 //
151 int sock = socket(PF_UNIX, SOCK_DGRAM, 0);
153 sock == -1,
154 "TapFdNetDeviceHelper::CreateFileDescriptor(): Unix socket creation error, errno = "
155 << strerror(errno));
156
157 //
158 // Bind to that socket and let the kernel allocate an endpoint
159 //
160 struct sockaddr_un un;
161 memset(&un, 0, sizeof(un));
162 un.sun_family = AF_UNIX;
163 int status = bind(sock, (struct sockaddr*)&un, sizeof(sa_family_t));
164 NS_ABORT_MSG_IF(status == -1,
165 "TapFdNetDeviceHelper::CreateFileDescriptor(): Could not bind(): errno = "
166 << strerror(errno));
167 NS_LOG_INFO("Created Unix socket");
168 NS_LOG_INFO("sun_family = " << un.sun_family);
169 NS_LOG_INFO("sun_path = " << un.sun_path);
170
171 //
172 // We have a socket here, but we want to get it there -- to the program we're
173 // going to exec. What we'll do is to do a getsockname and then encode the
174 // resulting address information as a string, and then send the string to the
175 // program as an argument. So we need to get the sock name.
176 //
177 socklen_t len = sizeof(un);
178 status = getsockname(sock, (struct sockaddr*)&un, &len);
180 status == -1,
181 "TapFdNetDeviceHelper::CreateFileDescriptor(): Could not getsockname(): errno = "
182 << strerror(errno));
183
184 //
185 // Now encode that socket name (family and path) as a string of hex digits
186 //
187 std::string path = BufferToString((uint8_t*)&un, len);
188 NS_LOG_INFO("Encoded Unix socket as \"" << path << "\"");
189
190 //
191 // Fork and exec the process to create our socket. If we're us (the parent)
192 // we wait for the child (the creator) to complete and read the socket it
193 // created and passed back using the ancillary data mechanism.
194 //
195 pid_t pid = ::fork();
196 if (pid == 0)
197 {
198 NS_LOG_DEBUG("Child process");
199
200 //
201 // build a command line argument from the encoded endpoint string that
202 // the socket creation process will use to figure out how to respond to
203 // the (now) parent process. We're going to have to give this program
204 // quite a bit of information.
205 //
206 // -d<device-name> The name of the tap device we want to create;
207 // -m<MAC-address> The MAC-48 address to assign to the new tap device;
208 // -i<IPv4-address> The IP v4 address to assign to the new tap device;
209 // -I<IPv6-address> The IP v6 address to assign to the new tap device;
210 // -n<network-IPv4-mask> The network IPv4 mask to assign to the new tap device;
211 // -N<network-IPv6-mask> The network IPv6 mask to assign to the new tap device;
212 // -t Set the IFF_TAP flag
213 // -h Set the IFF_NO_PI flag
214 // -p<path> the path to the unix socket described above.
215 //
216 // Example tap-creator -dnewdev -i1.2.3.1 -m08:00:2e:00:01:23 -n255.255.255.0 -t -h -pblah
217 //
218
219 //
220 // The device-name is something we may want the system to make up in
221 // every case. We also rely on it being configured via an Attribute
222 // through the helper. By default, it is set to the empty string
223 // which tells the system to make up a device name such as "tap123".
224 //
225 std::ostringstream ossDeviceName;
226 if (!m_deviceName.empty())
227 {
228 ossDeviceName << "-d" << m_deviceName;
229 }
230
231 std::ostringstream ossMac;
232 ossMac << "-m" << m_tapMac;
233
234 std::ostringstream ossIp4;
236 {
237 ossIp4 << "-i" << m_tapIp4;
238 }
239
240 std::ostringstream ossIp6;
242 {
243 ossIp6 << "-I" << m_tapIp6;
244 }
245
246 std::ostringstream ossNetmask4;
248 {
249 ossNetmask4 << "-n" << m_tapMask4;
250 }
251
252 std::ostringstream ossPrefix6;
253 ossPrefix6 << "-P" << m_tapPrefix6;
254
255 std::ostringstream ossMode;
256 ossMode << "-t";
257
258 std::ostringstream ossPI;
259 if (m_modePi)
260 {
261 ossPI << "-h";
262 }
263
264 std::ostringstream ossPath;
265 ossPath << "-p" << path;
266
267 //
268 // Execute the socket creation process image.
269 //
270 status = ::execlp(TAP_DEV_CREATOR,
271 TAP_DEV_CREATOR, // argv[0] (filename)
272 ossDeviceName.str().c_str(), // argv[1] (-d<device name>)
273 ossMac.str().c_str(), // argv[2] (-m<MAC address>
274 ossIp4.str().c_str(), // argv[3] (-i<IP v4 address>)
275 ossIp6.str().c_str(), // argv[4] (-I<IP v6 address>)
276 ossNetmask4.str().c_str(), // argv[5] (-n<IP v4 net mask>)
277 ossPrefix6.str().c_str(), // argv[6] (-P<IP v6 prefix>)
278 ossMode.str().c_str(), // argv[7] (-t <tap>)
279 ossPI.str().c_str(), // argv[8] (-h <pi>)
280 ossPath.str().c_str(), // argv[9] (-p<path>)
281 (char*)nullptr);
282
283 //
284 // If the execlp successfully completes, it never returns. If it returns it failed or the
285 // OS is broken. In either case, we bail.
286 //
287 NS_FATAL_ERROR("TapFdNetDeviceHelper::CreateFileDescriptor(): Back from execlp(), status = "
288 << status << ", errno = " << ::strerror(errno));
289 }
290 else
291 {
292 NS_LOG_DEBUG("Parent process");
293 //
294 // We're the process running the emu net device. We need to wait for the
295 // socket creator process to finish its job.
296 //
297 int st;
298 pid_t waited = waitpid(pid, &st, 0);
299 NS_ABORT_MSG_IF(waited == -1,
300 "TapFdNetDeviceHelper::CreateFileDescriptor(): waitpid() fails, errno = "
301 << strerror(errno));
302 NS_ASSERT_MSG(pid == waited, "TapFdNetDeviceHelper::CreateFileDescriptor(): pid mismatch");
303
304 //
305 // Check to see if the socket creator exited normally and then take a
306 // look at the exit code. If it bailed, so should we. If it didn't
307 // even exit normally, we bail too.
308 //
309 if (WIFEXITED(st))
310 {
311 int exitStatus = WEXITSTATUS(st);
312 NS_ABORT_MSG_IF(exitStatus != 0,
313 "TapFdNetDeviceHelper::CreateFileDescriptor(): socket creator exited "
314 "normally with status "
315 << exitStatus);
316 }
317 else
318 {
320 "TapFdNetDeviceHelper::CreateFileDescriptor(): socket creator exited abnormally");
321 }
322
323 //
324 // At this point, the socket creator has run successfully and should
325 // have created our tap device, initialized it with the information we
326 // passed and sent it back to the socket address we provided. A socket
327 // (fd) we can use to talk to this tap device should be waiting on the
328 // Unix socket we set up to receive information back from the creator
329 // program. We've got to do a bunch of grunt work to get at it, though.
330 //
331 // The struct iovec below is part of a scatter-gather list. It describes a
332 // buffer. In this case, it describes a buffer (an integer) that will
333 // get the data that comes back from the socket creator process. It will
334 // be a magic number that we use as a consistency/sanity check.
335 //
336 struct iovec iov;
337 uint32_t magic;
338 iov.iov_base = &magic;
339 iov.iov_len = sizeof(magic);
340
341 //
342 // The CMSG macros you'll see below are used to create and access control
343 // messages (which is another name for ancillary data). The ancillary
344 // data is made up of pairs of struct cmsghdr structures and associated
345 // data arrays.
346 //
347 // First, we're going to allocate a buffer on the stack to receive our
348 // data array (that contains the socket). Sometimes you'll see this called
349 // an "ancillary element" but the msghdr uses the control message termimology
350 // so we call it "control."
351 //
352 size_t msg_size = sizeof(int);
353 char control[CMSG_SPACE(msg_size)];
354
355 //
356 // There is a msghdr that is used to minimize the number of parameters
357 // passed to recvmsg (which we will use to receive our ancillary data).
358 // This structure uses terminology corresponding to control messages, so
359 // you'll see msg_control, which is the pointer to the ancillary data and
360 // controllen which is the size of the ancillary data array.
361 //
362 // So, initialize the message header that describes the ancillary/control
363 // data we expect to receive and point it to buffer.
364 //
365 struct msghdr msg;
366 msg.msg_name = nullptr;
367 msg.msg_namelen = 0;
368 msg.msg_iov = &iov;
369 msg.msg_iovlen = 1;
370 msg.msg_control = control;
371 msg.msg_controllen = sizeof(control);
372 msg.msg_flags = 0;
373
374 //
375 // Now we can actually receive the interesting bits from the tap
376 // creator process. Lots of pain to get four bytes.
377 //
378 ssize_t bytesRead = recvmsg(sock, &msg, 0);
380 bytesRead != sizeof(int),
381 "TapFdNetDeviceHelper::CreateFileDescriptor(): Wrong byte count from socket creator");
382
383 //
384 // There may be a number of message headers/ancillary data arrays coming in.
385 // Let's look for the one with a type SCM_RIGHTS which indicates it's the
386 // one we're interested in.
387 //
388 struct cmsghdr* cmsg;
389 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg))
390 {
391 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
392 {
393 //
394 // This is the type of message we want. Check to see if the magic
395 // number is correct and then pull out the socket we care about if
396 // it matches
397 //
398 if (magic == TAP_MAGIC)
399 {
400 NS_LOG_INFO("Got SCM_RIGHTS with correct magic " << magic);
401 int* rawSocket = (int*)CMSG_DATA(cmsg);
402 NS_LOG_INFO("Got the socket from the socket creator = " << *rawSocket);
403 return *rawSocket;
404 }
405 else
406 {
407 NS_LOG_INFO("Got SCM_RIGHTS, but with bad magic " << magic);
408 }
409 }
410 }
411 NS_FATAL_ERROR("Did not get the raw socket from the socket creator");
412 }
413 NS_FATAL_ERROR("Should be unreachable");
414 return 0; // Silence compiler warning about lack of return value
415}
416
417} // namespace ns3
std::string m_deviceName
The Unix/Linux name of the underlying device (e.g., eth0)
virtual Ptr< NetDevice > InstallPriv(Ptr< Node > node) const
This method creates an ns3::FdNetDevice and associates it to a node.
a NetDevice to read/write network traffic from/into a file descriptor.
Definition: fd-net-device.h:84
@ DIXPI
When using TAP devices, if flag IFF_NO_PI is not set on the device, IP packets will have an extra hea...
Definition: fd-net-device.h:99
Ipv4 addresses are stored in host order in this class.
Definition: ipv4-address.h:42
static Ipv4Address GetZero()
a class to represent an Ipv4 address mask
Definition: ipv4-address.h:257
static Ipv4Mask GetZero()
Describes an IPv6 address.
Definition: ipv6-address.h:49
static Ipv6Address GetZero()
Get the 0 (::) Ipv6Address.
an EUI-48 address
Definition: mac48-address.h:46
static Mac48Address Allocate()
Allocate a new Mac48Address.
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:77
int CreateFileDescriptor() const override
Call out to a separate process running as suid root in order to create a TAP device and obtain the fi...
void SetTapMacAddress(Mac48Address mac)
Set the MAC address for the TAP device.
bool m_modePi
The TAP device flag IFF_NO_PI.
void SetTapIpv6Prefix(int prefix)
Set the IPv6 network mask for the TAP device.
Ipv6Address m_tapIp6
The IPv6 address for the TAP device.
Ptr< NetDevice > InstallPriv(Ptr< Node > node) const override
This method creates an ns3::FdNetDevice attached to a virtual TAP network interface.
void SetTapIpv4Mask(Ipv4Mask mask)
Set the IPv4 network mask for the TAP device.
Ipv4Mask m_tapMask4
The network mask IPv4 for the TAP device.
Ipv4Address m_tapIp4
The IPv4 address for the TAP device.
TapFdNetDeviceHelper()
Construct a TapFdNetDeviceHelper.
Mac48Address m_tapMac
The TAP device MAC address.
int m_tapPrefix6
The network prefix IPv6 for the TAP device.
void SetTapIpv4Address(Ipv4Address address)
Set the device IPv4 address.
void SetModePi(bool pi)
Set flag IFF_NO_PI on the device.
void SetTapIpv6Address(Ipv6Address address)
Set the device IPv6 address.
void SetFileDescriptor(Ptr< FdNetDevice > device) const override
Sets a file descriptor on the FileDescriptorNetDevice.
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition: assert.h:86
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:179
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition: abort.h:108
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:268
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:282
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
Every class exported by the ns3 library is enclosed in the ns3 namespace.
std::string BufferToString(uint8_t *buffer, uint32_t len)
Convert a byte buffer to a string containing a hex representation of the buffer.
ns3::StringValue attribute value declarations.
#define TAP_MAGIC