lxc_container.c 24.2 KB
Newer Older
1
/*
2 3
 * Copyright (C) 2008-2010 Red Hat, Inc.
 * Copyright (C) 2008 IBM Corp.
4 5 6 7 8
 *
 * lxc_container.c: file description
 *
 * Authors:
 *  David L. Leskovec <dlesko at linux.vnet.ibm.com>
9
 *  Daniel P. Berrange <berrange@redhat.com>
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <config.h>

#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
31
#include <stdio.h>
32 33
#include <sys/ioctl.h>
#include <sys/mount.h>
34
#include <sys/wait.h>
35
#include <sys/stat.h>
36
#include <unistd.h>
37 38 39 40 41 42 43
#include <mntent.h>

/* Yes, we want linux private one, for _syscall2() macro */
#include <linux/unistd.h>

/* For MS_MOVE */
#include <linux/fs.h>
44

D
Daniel P. Berrange 已提交
45
#if HAVE_CAPNG
46
# include <cap-ng.h>
D
Daniel P. Berrange 已提交
47
#endif
48

49
#include "virterror_internal.h"
50
#include "logging.h"
51 52
#include "lxc_container.h"
#include "util.h"
53
#include "memory.h"
54
#include "veth.h"
55
#include "files.h"
56

57 58
#define VIR_FROM_THIS VIR_FROM_LXC

59 60 61 62 63 64
/*
 * GLibc headers are behind the kernel, so we define these
 * constants if they're not present already.
 */

#ifndef CLONE_NEWPID
65
# define CLONE_NEWPID  0x20000000
66 67
#endif
#ifndef CLONE_NEWUTS
68
# define CLONE_NEWUTS  0x04000000
69 70
#endif
#ifndef CLONE_NEWUSER
71
# define CLONE_NEWUSER 0x10000000
72 73
#endif
#ifndef CLONE_NEWIPC
74
# define CLONE_NEWIPC  0x08000000
75 76
#endif
#ifndef CLONE_NEWNET
77
# define CLONE_NEWNET  0x40000000 /* New network namespace */
78 79 80 81 82 83 84 85
#endif

/* messages between parent and container */
typedef char lxc_message_t;
#define LXC_CONTINUE_MSG 'c'

typedef struct __lxc_child_argv lxc_child_argv_t;
struct __lxc_child_argv {
86
    virDomainDefPtr config;
87 88
    unsigned int nveths;
    char **veths;
89 90 91 92 93
    int monitor;
    char *ttyPath;
};


94
/**
95
 * lxcContainerExecInit:
96
 * @vmDef: pointer to vm definition structure
97
 *
98
 * Exec the container init string. The container init will replace then
99 100
 * be running in the current process
 *
101
 * Does not return
102
 */
103
static int lxcContainerExecInit(virDomainDefPtr vmDef)
104
{
105
    const char *const argv[] = {
106
        vmDef->os.init,
107 108
        NULL,
    };
109 110 111 112 113
    const char *const envp[] = {
        "PATH=/bin:/sbin",
        "TERM=linux",
        NULL,
    };
114

115
    return execve(argv[0], (char **)argv,(char**)envp);
116 117 118
}

/**
119
 * lxcContainerSetStdio:
120 121
 * @control: control FD from parent
 * @ttyfd: FD of tty to set as the container console
122 123 124 125 126 127
 *
 * Sets the given tty as the primary conosole for the container as well as
 * stdout, stdin and stderr.
 *
 * Returns 0 on success or -1 in case of error
 */
128
static int lxcContainerSetStdio(int control, int ttyfd)
129 130
{
    int rc = -1;
131
    int open_max, i;
132 133

    if (setsid() < 0) {
134
        virReportSystemError(errno, "%s",
135
                             _("setsid failed"));
136
        goto cleanup;
137 138 139
    }

    if (ioctl(ttyfd, TIOCSCTTY, NULL) < 0) {
140
        virReportSystemError(errno, "%s",
141
                             _("ioctl(TIOCSTTY) failed"));
142 143 144
        goto cleanup;
    }

145 146 147 148
    /* Just in case someone forget to set FD_CLOEXEC, explicitly
     * close all FDs before executing the container */
    open_max = sysconf (_SC_OPEN_MAX);
    for (i = 0; i < open_max; i++)
149 150 151 152
        if (i != ttyfd && i != control) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
153 154

    if (dup2(ttyfd, 0) < 0) {
155
        virReportSystemError(errno, "%s",
156
                             _("dup2(stdin) failed"));
157 158 159 160
        goto cleanup;
    }

    if (dup2(ttyfd, 1) < 0) {
161
        virReportSystemError(errno, "%s",
162
                             _("dup2(stdout) failed"));
163 164 165 166
        goto cleanup;
    }

    if (dup2(ttyfd, 2) < 0) {
167
        virReportSystemError(errno, "%s",
168
                             _("dup2(stderr) failed"));
169 170 171 172 173 174 175 176 177 178
        goto cleanup;
    }

    rc = 0;

cleanup:
    return rc;
}

/**
179
 * lxcContainerSendContinue:
180
 * @control: control FD to child
181
 *
182 183
 * Sends the continue message via the socket pair stored in the vm
 * structure.
184 185 186
 *
 * Returns 0 on success or -1 in case of error
 */
187
int lxcContainerSendContinue(int control)
188 189
{
    int rc = -1;
190 191
    lxc_message_t msg = LXC_CONTINUE_MSG;
    int writeCount = 0;
192

193 194
    writeCount = safewrite(control, &msg, sizeof(msg));
    if (writeCount != sizeof(msg)) {
195
        virReportSystemError(errno, "%s",
196
                             _("Unable to send container continue message"));
197
        goto error_out;
198 199
    }

200
    rc = 0;
201

202 203
error_out:
    return rc;
204 205
}

206
/**
207
 * lxcContainerWaitForContinue:
208
 * @control: Control FD from parent
209 210 211 212 213 214 215
 *
 * This function will wait for the container continue message from the
 * parent process.  It will send this message on the socket pair stored in
 * the vm structure once it has completed the post clone container setup.
 *
 * Returns 0 on success or -1 in case of error
 */
216
static int lxcContainerWaitForContinue(int control)
217 218 219 220
{
    lxc_message_t msg;
    int readLen;

221
    readLen = saferead(control, &msg, sizeof(msg));
222 223
    if (readLen != sizeof(msg) ||
        msg != LXC_CONTINUE_MSG) {
224
        virReportSystemError(errno, "%s",
225
                             _("Failed to read the container continue message"));
226
        return -1;
227
    }
228
    VIR_FORCE_CLOSE(control);
229 230 231

    DEBUG0("Received container continue message");

232
    return 0;
233 234
}

235

236
/**
237
 * lxcContainerRenameAndEnableInterfaces:
238 239
 * @nveths: number of interfaces
 * @veths: interface names
240
 *
241 242 243
 * This function will rename the interfaces to ethN
 * with id ascending order from zero and enable the
 * renamed interfaces for this container.
244 245 246
 *
 * Returns 0 on success or nonzero in case of error
 */
247 248
static int lxcContainerRenameAndEnableInterfaces(unsigned int nveths,
                                                 char **veths)
249 250
{
    int rc = 0;
251
    unsigned int i;
252
    char *newname = NULL;
253

254
    for (i = 0 ; i < nveths ; i++) {
255 256 257
        if (virAsprintf(&newname, "eth%d", i) < 0) {
            virReportOOMError();
            rc = -1;
258
            goto error_out;
259
        }
260 261 262

        DEBUG("Renaming %s to %s", veths[i], newname);
        rc = setInterfaceName(veths[i], newname);
263
        if (rc < 0)
264 265 266
            goto error_out;

        DEBUG("Enabling %s", newname);
267
        rc = vethInterfaceUpOrDown(newname, 1);
268
        if (rc < 0)
269
            goto error_out;
270

271
        VIR_FREE(newname);
272 273 274
    }

    /* enable lo device only if there were other net devices */
275
    if (veths)
276 277 278
        rc = vethInterfaceUpOrDown("lo", 1);

error_out:
279
    VIR_FREE(newname);
280 281 282
    return rc;
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296

//_syscall2(int, pivot_root, char *, newroot, const char *, oldroot)
extern int pivot_root(const char * new_root,const char * put_old);

static int lxcContainerChildMountSort(const void *a, const void *b)
{
  const char **sa = (const char**)a;
  const char **sb = (const char**)b;

  /* Delibrately reversed args - we need to unmount deepest
     children first */
  return strcmp(*sb, *sa);
}

297
#ifndef MS_REC
298
# define MS_REC          16384
299 300 301
#endif

#ifndef MNT_DETACH
302
# define MNT_DETACH      0x00000002
303 304 305
#endif

#ifndef MS_PRIVATE
306
# define MS_PRIVATE              (1<<18)
307 308 309
#endif

#ifndef MS_SLAVE
310
# define MS_SLAVE                (1<<19)
311 312
#endif

313 314
static int lxcContainerPivotRoot(virDomainFSDefPtr root)
{
M
Mark McLoughlin 已提交
315
    int rc, ret;
316
    char *oldroot = NULL, *newroot = NULL;
317

M
Mark McLoughlin 已提交
318 319
    ret = -1;

320 321
    /* root->parent must be private, so make / private. */
    if (mount("", "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0) {
322
        virReportSystemError(errno, "%s",
323
                             _("Failed to make root private"));
324
        goto err;
325 326
    }

327
    if (virAsprintf(&oldroot, "%s/.oldroot", root->src) < 0) {
328
        virReportOOMError();
329
        goto err;
330 331
    }

L
Laine Stump 已提交
332
    if ((rc = virFileMakePath(oldroot)) != 0) {
333
        virReportSystemError(rc,
334
                             _("Failed to create %s"),
335
                             oldroot);
336 337 338 339 340
        goto err;
    }

    /* Create a tmpfs root since old and new roots must be
     * on separate filesystems */
341
    if (mount("tmprootfs", oldroot, "tmpfs", 0, NULL) < 0) {
342
        virReportSystemError(errno,
343
                             _("Failed to mount empty tmpfs at %s"),
344 345 346
                             oldroot);
        goto err;
    }
M
Mark McLoughlin 已提交
347

348 349
    /* Create a directory called 'new' in tmpfs */
    if (virAsprintf(&newroot, "%s/new", oldroot) < 0) {
350
        virReportOOMError();
351 352 353
        goto err;
    }

L
Laine Stump 已提交
354
    if ((rc = virFileMakePath(newroot)) != 0) {
355
        virReportSystemError(rc,
356
                             _("Failed to create %s"),
357 358 359 360 361 362
                             newroot);
        goto err;
    }

    /* ... and mount our root onto it */
    if (mount(root->src, newroot, NULL, MS_BIND|MS_REC, NULL) < 0) {
363
        virReportSystemError(errno,
364
                             _("Failed to bind new root %s into tmpfs"),
365 366 367 368 369 370
                             root->src);
        goto err;
    }

    /* Now we chroot into the tmpfs, then pivot into the
     * root->src bind-mounted onto '/new' */
371
    if (chdir(newroot) < 0) {
372
        virReportSystemError(errno,
373
                             _("Failed to chroot into %s"), newroot);
374
        goto err;
375 376 377 378
    }

    /* The old root directory will live at /.oldroot after
     * this and will soon be unmounted completely */
379
    if (pivot_root(".", ".oldroot") < 0) {
380
        virReportSystemError(errno, "%s",
381
                             _("Failed to pivot root"));
382
        goto err;
383 384 385
    }

    /* CWD is undefined after pivot_root, so go to / */
386 387 388
    if (chdir("/") < 0)
        goto err;

M
Mark McLoughlin 已提交
389 390 391
    ret = 0;

err:
392 393 394
    VIR_FREE(oldroot);
    VIR_FREE(newroot);

M
Mark McLoughlin 已提交
395
    return ret;
396 397
}

398 399

static int lxcContainerMountBasicFS(virDomainFSDefPtr root)
400 401
{
    const struct {
402 403 404 405 406 407 408 409 410 411
        const char *src;
        const char *dst;
        const char *type;
    } mnts[] = {
        { "/dev", "/dev", "tmpfs" },
        { "/proc", "/proc", "proc" },
        { "/sys", "/sys", "sysfs" },
#if WITH_SELINUX
        { "none", "/selinux", "selinuxfs" },
#endif
412
    };
413
    int i, rc = -1;
414
    char *devpts;
415

416
    if (virAsprintf(&devpts, "/.oldroot%s/dev/pts", root->src) < 0) {
417
        virReportOOMError();
418
        return rc;
419
    }
420 421

    for (i = 0 ; i < ARRAY_CARDINALITY(mnts) ; i++) {
L
Laine Stump 已提交
422
        if (virFileMakePath(mnts[i].dst) != 0) {
423
            virReportSystemError(errno,
424
                                 _("Failed to mkdir %s"),
425
                                 mnts[i].src);
426
            goto cleanup;
427 428
        }
        if (mount(mnts[i].src, mnts[i].dst, mnts[i].type, 0, NULL) < 0) {
429
            virReportSystemError(errno,
430
                                 _("Failed to mount %s on %s"),
431
                                 mnts[i].type, mnts[i].type);
432
            goto cleanup;
433
        }
434
    }
435

L
Laine Stump 已提交
436
    if ((rc = virFileMakePath("/dev/pts") != 0)) {
437
        virReportSystemError(rc, "%s",
438
                             _("Cannot create /dev/pts"));
439
        goto cleanup;
440
    }
441 442 443

    VIR_DEBUG("Trying to move %s to %s", devpts, "/dev/pts");
    if ((rc = mount(devpts, "/dev/pts", NULL, MS_MOVE, NULL)) < 0) {
444
        virReportSystemError(errno, "%s",
445
                             _("Failed to mount /dev/pts in container"));
446
        goto cleanup;
447
    }
448 449 450 451

    rc = 0;

 cleanup:
452 453
    VIR_FREE(devpts);

454
    return rc;
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
}

static int lxcContainerPopulateDevices(void)
{
    int i;
    const struct {
        int maj;
        int min;
        mode_t mode;
        const char *path;
    } devs[] = {
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_NULL, 0666, "/dev/null" },
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_ZERO, 0666, "/dev/zero" },
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_FULL, 0666, "/dev/full" },
        { LXC_DEV_MAJ_TTY, LXC_DEV_MIN_CONSOLE, 0600, "/dev/console" },
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_RANDOM, 0666, "/dev/random" },
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_URANDOM, 0666, "/dev/urandom" },
    };
473 474 475 476

    /* Populate /dev/ with a few important bits */
    for (i = 0 ; i < ARRAY_CARDINALITY(devs) ; i++) {
        dev_t dev = makedev(devs[i].maj, devs[i].min);
477
        if (mknod(devs[i].path, S_IFCHR, dev) < 0 ||
478
            chmod(devs[i].path, devs[i].mode)) {
479
            virReportSystemError(errno,
480
                                 _("Failed to make device %s"),
481
                                 devs[i].path);
482 483 484 485
            return -1;
        }
    }

486 487
    if (access("/dev/pts/ptmx", W_OK) == 0) {
        if (symlink("/dev/pts/ptmx", "/dev/ptmx") < 0) {
488
            virReportSystemError(errno, "%s",
489
                                 _("Failed to create symlink /dev/ptmx to /dev/pts/ptmx"));
490 491 492 493
            return -1;
        }
    } else {
        dev_t dev = makedev(LXC_DEV_MAJ_TTY, LXC_DEV_MIN_PTMX);
494
        if (mknod("/dev/ptmx", S_IFCHR, dev) < 0 ||
495
            chmod("/dev/ptmx", 0666)) {
496
            virReportSystemError(errno, "%s",
497
                                 _("Failed to make device /dev/ptmx"));
498 499 500 501
            return -1;
        }
    }

502 503 504 505 506 507 508 509 510
    /* XXX we should allow multiple consoles per container
     * for tty2, tty3, etc, but the domain XML does not
     * handle this yet
     */
    if (symlink("/dev/pts/0", "/dev/tty1") < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to symlink /dev/pts/0 to /dev/tty1"));
        return -1;
    }
511

512 513 514 515 516 517
    return 0;
}


static int lxcContainerMountNewFS(virDomainDefPtr vmDef)
{
518
    int i;
519 520

    /* Pull in rest of container's mounts */
521
    for (i = 0 ; i < vmDef->nfss ; i++) {
522
        char *src;
523
        if (STREQ(vmDef->fss[i]->dst, "/"))
524 525
            continue;
        // XXX fix
526
        if (vmDef->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
527 528
            continue;

529
        if (virAsprintf(&src, "/.oldroot/%s", vmDef->fss[i]->src) < 0) {
530
            virReportOOMError();
531 532 533
            return -1;
        }

L
Laine Stump 已提交
534
        if (virFileMakePath(vmDef->fss[i]->dst) != 0) {
535
            virReportSystemError(errno,
536
                                 _("Failed to create %s"),
537
                                 vmDef->fss[i]->dst);
538
            VIR_FREE(src);
539 540 541
            return -1;
        }
        if (mount(src, vmDef->fss[i]->dst, NULL, MS_BIND, NULL) < 0) {
542
            virReportSystemError(errno,
543 544 545
                                 _("Failed to mount %s at %s"),
                                 src, vmDef->fss[i]->dst);
            VIR_FREE(src);
546 547 548 549 550 551 552 553 554 555 556
            return -1;
        }
        VIR_FREE(src);
    }

    return 0;
}


static int lxcContainerUnmountOldFS(void)
{
557
    struct mntent mntent;
558 559 560 561
    char **mounts = NULL;
    int nmounts = 0;
    FILE *procmnt;
    int i;
562
    char mntbuf[1024];
563 564

    if (!(procmnt = setmntent("/proc/mounts", "r"))) {
565
        virReportSystemError(errno, "%s",
566
                             _("Failed to read /proc/mounts"));
567 568
        return -1;
    }
569
    while (getmntent_r(procmnt, &mntent, mntbuf, sizeof(mntbuf)) != NULL) {
570
        VIR_DEBUG("Got %s", mntent.mnt_dir);
571
        if (!STRPREFIX(mntent.mnt_dir, "/.oldroot"))
572 573 574 575
            continue;

        if (VIR_REALLOC_N(mounts, nmounts+1) < 0) {
            endmntent(procmnt);
576
            virReportOOMError();
577 578
            return -1;
        }
579
        if (!(mounts[nmounts++] = strdup(mntent.mnt_dir))) {
580
            endmntent(procmnt);
581
            virReportOOMError();
582 583 584 585 586
            return -1;
        }
    }
    endmntent(procmnt);

587 588 589
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
590 591

    for (i = 0 ; i < nmounts ; i++) {
592
        VIR_DEBUG("Umount %s", mounts[i]);
593
        if (umount(mounts[i]) < 0) {
594
            virReportSystemError(errno,
595
                                 _("Failed to unmount '%s'"),
596
                                 mounts[i]);
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
            return -1;
        }
        VIR_FREE(mounts[i]);
    }
    VIR_FREE(mounts);

    return 0;
}


/* Got a FS mapped to /, we're going the pivot_root
 * approach to do a better-chroot-than-chroot
 * this is based on this thread http://lkml.org/lkml/2008/3/5/29
 */
static int lxcContainerSetupPivotRoot(virDomainDefPtr vmDef,
                                      virDomainFSDefPtr root)
{
614
    /* Gives us a private root, leaving all parent OS mounts on /.oldroot */
615 616 617
    if (lxcContainerPivotRoot(root) < 0)
        return -1;

618 619
    /* Mounts the core /proc, /sys, /dev, /dev/pts filesystems */
    if (lxcContainerMountBasicFS(root) < 0)
620 621
        return -1;

622
    /* Populates device nodes in /dev/ */
623 624 625
    if (lxcContainerPopulateDevices() < 0)
        return -1;

626
    /* Sets up any non-root mounts from guest config */
627 628 629
    if (lxcContainerMountNewFS(vmDef) < 0)
        return -1;

630
    /* Gets rid of all remaining mounts from host OS, including /.oldroot itself */
631 632 633 634 635 636 637 638 639 640
    if (lxcContainerUnmountOldFS() < 0)
        return -1;

    return 0;
}

/* Nothing mapped to /, we're using the main root,
   but with extra stuff mapped in */
static int lxcContainerSetupExtraMounts(virDomainDefPtr vmDef)
{
641
    int i;
642

643
    if (mount("", "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
644
        virReportSystemError(errno, "%s",
645
                             _("Failed to make / slave"));
646 647
        return -1;
    }
648
    for (i = 0 ; i < vmDef->nfss ; i++) {
649
        // XXX fix to support other mount types
650
        if (vmDef->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
651 652
            continue;

653 654
        if (mount(vmDef->fss[i]->src,
                  vmDef->fss[i]->dst,
655 656 657
                  NULL,
                  MS_BIND,
                  NULL) < 0) {
658
            virReportSystemError(errno,
659
                                 _("Failed to mount %s at %s"),
660 661
                                 vmDef->fss[i]->src,
                                 vmDef->fss[i]->dst);
662 663 664 665 666 667
            return -1;
        }
    }

    /* mount /proc */
    if (mount("lxcproc", "/proc", "proc", 0, NULL) < 0) {
668
        virReportSystemError(errno, "%s",
669
                             _("Failed to mount /proc"));
670 671 672 673 674 675
        return -1;
    }

    return 0;
}

676 677
static int lxcContainerSetupMounts(virDomainDefPtr vmDef,
                                   virDomainFSDefPtr root)
678 679 680 681 682 683 684
{
    if (root)
        return lxcContainerSetupPivotRoot(vmDef, root);
    else
        return lxcContainerSetupExtraMounts(vmDef);
}

D
Daniel P. Berrange 已提交
685 686 687 688 689 690 691

/*
 * This is running as the 'init' process insid the container.
 * It removes some capabilities that could be dangerous to
 * host system, since they are not currently "containerized"
 */
static int lxcContainerDropCapabilities(void)
692
{
D
Daniel P. Berrange 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706
#if HAVE_CAPNG
    int ret;

    capng_get_caps_process();

    if ((ret = capng_updatev(CAPNG_DROP,
                             CAPNG_EFFECTIVE | CAPNG_PERMITTED |
                             CAPNG_INHERITABLE | CAPNG_BOUNDING_SET,
                             CAP_SYS_BOOT, /* No use of reboot */
                             CAP_SYS_MODULE, /* No kernel module loading */
                             CAP_SYS_TIME, /* No changing the clock */
                             CAP_AUDIT_CONTROL, /* No messing with auditing status */
                             CAP_MAC_ADMIN, /* No messing with LSM config */
                             -1 /* sentinal */)) < 0) {
707
        lxcError(VIR_ERR_INTERNAL_ERROR,
708
                 _("Failed to remove capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
709 710
        return -1;
    }
711

D
Daniel P. Berrange 已提交
712
    if ((ret = capng_apply(CAPNG_SELECT_BOTH)) < 0) {
713
        lxcError(VIR_ERR_INTERNAL_ERROR,
714
                 _("Failed to apply capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
715
        return -1;
716
    }
D
Daniel P. Berrange 已提交
717

718 719 720 721 722
    /* We do not need to call capng_lock() in this case. The bounding
     * set restriction will prevent them reacquiring sys_boot/module/time,
     * etc which is all that matters for the container. Once inside the
     * container it is fine for SECURE_NOROOT / SECURE_NO_SETUID_FIXUP to
     * be unmasked  - they can never escape the bounding set. */
D
Daniel P. Berrange 已提交
723 724

#else
725
    VIR_WARN0("libcap-ng support not compiled in, unable to clear capabilities");
D
Daniel Veillard 已提交
726
#endif
727 728 729 730
    return 0;
}


731
/**
732 733
 * lxcContainerChild:
 * @data: pointer to container arguments
734 735 736 737 738 739 740 741 742
 *
 * This function is run in the process clone()'d in lxcStartContainer.
 * Perform a number of container setup tasks:
 *     Setup container file system
 *     mount container /proca
 * Then exec's the container init
 *
 * Returns 0 on success or -1 in case of error
 */
743
static int lxcContainerChild( void *data )
744
{
745
    lxc_child_argv_t *argv = data;
746
    virDomainDefPtr vmDef = argv->config;
747
    int ttyfd;
748 749
    char *ttyPath;
    virDomainFSDefPtr root;
750 751

    if (NULL == vmDef) {
752
        lxcError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
753
                 "%s", _("lxcChild() passed invalid vm definition"));
754
        return -1;
755 756
    }

757
    root = virDomainGetRootFilesystem(vmDef);
758

759 760
    if (root) {
        if (virAsprintf(&ttyPath, "%s%s", root->src, argv->ttyPath) < 0) {
761
            virReportOOMError();
762 763 764 765
            return -1;
        }
    } else {
        if (!(ttyPath = strdup(argv->ttyPath))) {
766
            virReportOOMError();
767 768 769 770 771
            return -1;
        }
    }

    ttyfd = open(ttyPath, O_RDWR|O_NOCTTY);
772
    if (ttyfd < 0) {
773
        virReportSystemError(errno,
774
                             _("Failed to open tty %s"),
775
                             ttyPath);
776
        VIR_FREE(ttyPath);
777
        return -1;
778
    }
779
    VIR_FREE(ttyPath);
780

781
    if (lxcContainerSetStdio(argv->monitor, ttyfd) < 0) {
782
        VIR_FORCE_CLOSE(ttyfd);
783
        return -1;
784
    }
785
    VIR_FORCE_CLOSE(ttyfd);
786

787 788 789
    if (lxcContainerSetupMounts(vmDef, root) < 0)
        return -1;

790
    /* Wait for interface devices to show up */
791 792
    if (lxcContainerWaitForContinue(argv->monitor) < 0)
        return -1;
793

794 795 796
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
                                              argv->veths) < 0)
797
        return -1;
798

799
    /* drop a set of root capabilities */
D
Daniel P. Berrange 已提交
800
    if (lxcContainerDropCapabilities() < 0)
801 802
        return -1;

803
    /* this function will only return if an error occured */
804 805
    return lxcContainerExecInit(vmDef);
}
806

807 808 809 810 811
static int userns_supported(void)
{
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
}

812 813
/**
 * lxcContainerStart:
814 815 816 817 818
 * @def: pointer to virtual machine structure
 * @nveths: number of interfaces
 * @veths: interface names
 * @control: control FD to the container
 * @ttyPath: path of tty to set as the container console
819 820 821 822 823
 *
 * Starts a container process by calling clone() with the namespace flags
 *
 * Returns PID of container on success or -1 in case of error
 */
824
int lxcContainerStart(virDomainDefPtr def,
825 826
                      unsigned int nveths,
                      char **veths,
827 828 829 830 831 832 833
                      int control,
                      char *ttyPath)
{
    pid_t pid;
    int flags;
    int stacksize = getpagesize() * 4;
    char *stack, *stacktop;
834
    lxc_child_argv_t args = { def, nveths, veths, control, ttyPath };
835 836 837

    /* allocate a stack for the container */
    if (VIR_ALLOC_N(stack, stacksize) < 0) {
838
        virReportOOMError();
839 840 841 842
        return -1;
    }
    stacktop = stack + stacksize;

843 844
    flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;

845 846
    if (userns_supported()) {
        DEBUG0("Enable user namespaces");
847
        flags |= CLONE_NEWUSER;
848
    }
849

850 851
    if (def->nets != NULL) {
        DEBUG0("Enable network namespaces");
852
        flags |= CLONE_NEWNET;
853
    }
854 855 856

    pid = clone(lxcContainerChild, stacktop, flags, &args);
    VIR_FREE(stack);
857
    DEBUG("clone() completed, new container PID is %d", pid);
858 859

    if (pid < 0) {
860
        virReportSystemError(errno, "%s",
861
                             _("Failed to run clone container"));
862 863 864 865 866 867 868 869 870 871 872 873 874
        return -1;
    }

    return pid;
}

static int lxcContainerDummyChild(void *argv ATTRIBUTE_UNUSED)
{
    _exit(0);
}

int lxcContainerAvailable(int features)
{
875
    int flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|
876 877 878 879 880 881
        CLONE_NEWIPC|SIGCHLD;
    int cpid;
    char *childStack;
    char *stack;
    int childStatus;

882 883 884
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

885 886 887 888 889 890 891 892 893 894 895 896 897
    if (features & LXC_CONTAINER_FEATURE_NET)
        flags |= CLONE_NEWNET;

    if (VIR_ALLOC_N(stack, getpagesize() * 4) < 0) {
        DEBUG0("Unable to allocate stack");
        return -1;
    }

    childStack = stack + (getpagesize() * 4);

    cpid = clone(lxcContainerDummyChild, childStack, flags, NULL);
    VIR_FREE(stack);
    if (cpid < 0) {
898
        char ebuf[1024];
899
        DEBUG("clone call returned %s, container support is not enabled",
900
              virStrerror(errno, ebuf, sizeof ebuf));
901 902 903 904 905 906
        return -1;
    } else {
        waitpid(cpid, &childStatus, 0);
    }

    return 0;
907
}