1/* Enter a network namespace.
2 Copyright (C) 2016-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19#include <support/namespace.h>
20
21#include <net/if.h>
22#include <sched.h>
23#include <stdio.h>
24#include <string.h>
25#include <support/check.h>
26#include <sys/ioctl.h>
27#include <unistd.h>
28#include <xsocket.h>
29
30static bool in_uts_namespace;
31
32bool
33support_enter_network_namespace (void)
34{
35#ifdef CLONE_NEWUTS
36 if (unshare (CLONE_NEWUTS) == 0)
37 in_uts_namespace = true;
38 else
39 printf ("warning: unshare (CLONE_NEWUTS) failed: %m\n");
40#endif
41
42#ifdef CLONE_NEWNET
43 if (unshare (CLONE_NEWNET) == 0)
44 {
45 /* Bring up the loopback interface. */
46 int fd = xsocket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
47 struct ifreq req;
48 strcpy (req.ifr_name, "lo");
49 TEST_VERIFY_EXIT (ioctl (fd, SIOCGIFFLAGS, &req) == 0);
50 bool already_up = req.ifr_flags & IFF_UP;
51 if (already_up)
52 /* This means that we likely have not achieved isolation from
53 the parent namespace. */
54 printf ("warning: loopback interface already exists"
55 " in new network namespace\n");
56 else
57 {
58 req.ifr_flags |= IFF_UP | IFF_RUNNING;
59 TEST_VERIFY_EXIT (ioctl (fd, SIOCSIFFLAGS, &req) == 0);
60 }
61 close (fd);
62
63 return !already_up;
64 }
65#endif
66 printf ("warning: could not enter network namespace\n");
67 return false;
68}
69
70bool
71support_in_uts_namespace (void)
72{
73 return in_uts_namespace;
74}
75