lxc_container.c 24.5 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
/*_syscall2(int, pivot_root, char *, newroot, const char *, oldroot)*/
285 286 287 288 289 290 291 292 293 294 295 296
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
}

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_MEMORY, LXC_DEV_MIN_RANDOM, 0666, "/dev/random" },
        { LXC_DEV_MAJ_MEMORY, LXC_DEV_MIN_URANDOM, 0666, "/dev/urandom" },
    };
472 473 474 475

    /* 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);
476
        if (mknod(devs[i].path, S_IFCHR, dev) < 0 ||
477
            chmod(devs[i].path, devs[i].mode)) {
478
            virReportSystemError(errno,
479
                                 _("Failed to make device %s"),
480
                                 devs[i].path);
481 482 483 484
            return -1;
        }
    }

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

501 502 503 504 505 506 507 508 509
    /* 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;
    }
510 511 512 513 514
    if (symlink("/dev/pts/0", "/dev/console") < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to symlink /dev/pts/0 to /dev/console"));
        return -1;
    }
515

516 517 518 519 520 521
    return 0;
}


static int lxcContainerMountNewFS(virDomainDefPtr vmDef)
{
522
    int i;
523 524

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

533
        if (virAsprintf(&src, "/.oldroot/%s", vmDef->fss[i]->src) < 0) {
534
            virReportOOMError();
535 536 537
            return -1;
        }

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

    return 0;
}


static int lxcContainerUnmountOldFS(void)
{
561
    struct mntent mntent;
562 563 564 565
    char **mounts = NULL;
    int nmounts = 0;
    FILE *procmnt;
    int i;
566
    char mntbuf[1024];
567 568

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

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

591 592 593
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
594 595

    for (i = 0 ; i < nmounts ; i++) {
596
        VIR_DEBUG("Umount %s", mounts[i]);
597
        if (umount(mounts[i]) < 0) {
598
            virReportSystemError(errno,
599
                                 _("Failed to unmount '%s'"),
600
                                 mounts[i]);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
            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)
{
618
    /* Gives us a private root, leaving all parent OS mounts on /.oldroot */
619 620 621
    if (lxcContainerPivotRoot(root) < 0)
        return -1;

622 623
    /* Mounts the core /proc, /sys, /dev, /dev/pts filesystems */
    if (lxcContainerMountBasicFS(root) < 0)
624 625
        return -1;

626
    /* Populates device nodes in /dev/ */
627 628 629
    if (lxcContainerPopulateDevices() < 0)
        return -1;

630
    /* Sets up any non-root mounts from guest config */
631 632 633
    if (lxcContainerMountNewFS(vmDef) < 0)
        return -1;

634
    /* Gets rid of all remaining mounts from host OS, including /.oldroot itself */
635 636 637 638 639 640 641 642 643 644
    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)
{
645
    int i;
646

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

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

    /* mount /proc */
    if (mount("lxcproc", "/proc", "proc", 0, NULL) < 0) {
672
        virReportSystemError(errno, "%s",
673
                             _("Failed to mount /proc"));
674 675 676 677 678 679
        return -1;
    }

    return 0;
}

680 681
static int lxcContainerSetupMounts(virDomainDefPtr vmDef,
                                   virDomainFSDefPtr root)
682 683 684 685 686 687 688
{
    if (root)
        return lxcContainerSetupPivotRoot(vmDef, root);
    else
        return lxcContainerSetupExtraMounts(vmDef);
}

D
Daniel P. Berrange 已提交
689 690 691 692 693 694 695

/*
 * 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)
696
{
D
Daniel P. Berrange 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710
#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) {
711
        lxcError(VIR_ERR_INTERNAL_ERROR,
712
                 _("Failed to remove capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
713 714
        return -1;
    }
715

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

722 723 724 725 726
    /* 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 已提交
727 728

#else
729
    VIR_WARN0("libcap-ng support not compiled in, unable to clear capabilities");
D
Daniel Veillard 已提交
730
#endif
731 732 733 734
    return 0;
}


735
/**
736 737
 * lxcContainerChild:
 * @data: pointer to container arguments
738 739 740 741 742 743 744 745 746
 *
 * 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
 */
747
static int lxcContainerChild( void *data )
748
{
749
    lxc_child_argv_t *argv = data;
750
    virDomainDefPtr vmDef = argv->config;
751
    int ttyfd;
752 753
    char *ttyPath;
    virDomainFSDefPtr root;
754 755

    if (NULL == vmDef) {
756
        lxcError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
757
                 "%s", _("lxcChild() passed invalid vm definition"));
758
        return -1;
759 760
    }

761
    root = virDomainGetRootFilesystem(vmDef);
762

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

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

785
    if (lxcContainerSetStdio(argv->monitor, ttyfd) < 0) {
786
        VIR_FORCE_CLOSE(ttyfd);
787
        return -1;
788
    }
789
    VIR_FORCE_CLOSE(ttyfd);
790

791 792 793
    if (lxcContainerSetupMounts(vmDef, root) < 0)
        return -1;

794
    /* Wait for interface devices to show up */
795 796
    if (lxcContainerWaitForContinue(argv->monitor) < 0)
        return -1;
797

798 799 800
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
                                              argv->veths) < 0)
801
        return -1;
802

803
    /* drop a set of root capabilities */
D
Daniel P. Berrange 已提交
804
    if (lxcContainerDropCapabilities() < 0)
805 806
        return -1;

807
    /* this function will only return if an error occured */
808 809
    return lxcContainerExecInit(vmDef);
}
810

811 812
static int userns_supported(void)
{
813 814 815 816 817 818
#if 1
    /*
     * put off using userns until uid mapping is implemented
     */
    return 0;
#else
819
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
820
#endif
821 822
}

823 824
/**
 * lxcContainerStart:
825 826 827 828 829
 * @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
830 831 832 833 834
 *
 * Starts a container process by calling clone() with the namespace flags
 *
 * Returns PID of container on success or -1 in case of error
 */
835
int lxcContainerStart(virDomainDefPtr def,
836 837
                      unsigned int nveths,
                      char **veths,
838 839 840 841 842 843 844
                      int control,
                      char *ttyPath)
{
    pid_t pid;
    int flags;
    int stacksize = getpagesize() * 4;
    char *stack, *stacktop;
845
    lxc_child_argv_t args = { def, nveths, veths, control, ttyPath };
846 847 848

    /* allocate a stack for the container */
    if (VIR_ALLOC_N(stack, stacksize) < 0) {
849
        virReportOOMError();
850 851 852 853
        return -1;
    }
    stacktop = stack + stacksize;

854 855
    flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;

856 857
    if (userns_supported()) {
        DEBUG0("Enable user namespaces");
858
        flags |= CLONE_NEWUSER;
859
    }
860

861 862
    if (def->nets != NULL) {
        DEBUG0("Enable network namespaces");
863
        flags |= CLONE_NEWNET;
864
    }
865 866 867

    pid = clone(lxcContainerChild, stacktop, flags, &args);
    VIR_FREE(stack);
868
    DEBUG("clone() completed, new container PID is %d", pid);
869 870

    if (pid < 0) {
871
        virReportSystemError(errno, "%s",
872
                             _("Failed to run clone container"));
873 874 875 876 877 878 879 880 881 882 883 884 885
        return -1;
    }

    return pid;
}

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

int lxcContainerAvailable(int features)
{
886
    int flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|
887 888 889 890 891 892
        CLONE_NEWIPC|SIGCHLD;
    int cpid;
    char *childStack;
    char *stack;
    int childStatus;

893 894 895
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

896 897 898 899 900 901 902 903 904 905 906 907 908
    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) {
909
        char ebuf[1024];
910
        DEBUG("clone call returned %s, container support is not enabled",
911
              virStrerror(errno, ebuf, sizeof ebuf));
912 913 914 915 916 917
        return -1;
    } else {
        waitpid(cpid, &childStatus, 0);
    }

    return 0;
918
}