lxc_container.c 28.8 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * Copyright (C) 2008-2011 Red Hat, Inc.
3
 * 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 "uuid.h"
E
Eric Blake 已提交
56
#include "virfile.h"
57
#include "command.h"
58

59 60
#define VIR_FROM_THIS VIR_FROM_LXC

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

#ifndef CLONE_NEWPID
67
# define CLONE_NEWPID  0x20000000
68 69
#endif
#ifndef CLONE_NEWUTS
70
# define CLONE_NEWUTS  0x04000000
71 72
#endif
#ifndef CLONE_NEWUSER
73
# define CLONE_NEWUSER 0x10000000
74 75
#endif
#ifndef CLONE_NEWIPC
76
# define CLONE_NEWIPC  0x08000000
77 78
#endif
#ifndef CLONE_NEWNET
79
# define CLONE_NEWNET  0x40000000 /* New network namespace */
80 81 82 83 84 85 86 87
#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 {
88
    virDomainDefPtr config;
89 90
    unsigned int nveths;
    char **veths;
91 92
    int monitor;
    char *ttyPath;
93
    int handshakefd;
94 95 96
};


97
/**
98
 * lxcContainerBuildInitCmd:
99
 * @vmDef: pointer to vm definition structure
100
 *
101
 * Build a virCommandPtr for launching the container 'init' process
102
 *
103
 * Returns a virCommandPtr
104
 */
105
static virCommandPtr lxcContainerBuildInitCmd(virDomainDefPtr vmDef)
106
{
107
    char uuidstr[VIR_UUID_STRING_BUFLEN];
108
    virCommandPtr cmd;
109 110 111

    virUUIDFormat(vmDef->uuid, uuidstr);

112 113 114 115 116 117 118
    cmd = virCommandNew(vmDef->os.init);

    virCommandAddEnvString(cmd, "PATH=/bin:/sbin");
    virCommandAddEnvString(cmd, "TERM=linux");
    virCommandAddEnvPair(cmd, "LIBVIRT_LXC_UUID", uuidstr);
    virCommandAddEnvPair(cmd, "LIBVIRT_LXC_NAME", vmDef->name);

119
    return cmd;
120 121 122
}

/**
123
 * lxcContainerSetStdio:
124 125
 * @control: control FD from parent
 * @ttyfd: FD of tty to set as the container console
126 127 128 129 130 131
 *
 * 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
 */
132
static int lxcContainerSetStdio(int control, int ttyfd, int handshakefd)
133 134
{
    int rc = -1;
135
    int open_max, i;
136 137

    if (setsid() < 0) {
138
        virReportSystemError(errno, "%s",
139
                             _("setsid failed"));
140
        goto cleanup;
141 142 143
    }

    if (ioctl(ttyfd, TIOCSCTTY, NULL) < 0) {
144
        virReportSystemError(errno, "%s",
145
                             _("ioctl(TIOCSTTY) failed"));
146 147 148
        goto cleanup;
    }

149 150 151 152
    /* 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++)
153
        if (i != ttyfd && i != control && i != handshakefd) {
154 155 156
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
157 158

    if (dup2(ttyfd, 0) < 0) {
159
        virReportSystemError(errno, "%s",
160
                             _("dup2(stdin) failed"));
161 162 163 164
        goto cleanup;
    }

    if (dup2(ttyfd, 1) < 0) {
165
        virReportSystemError(errno, "%s",
166
                             _("dup2(stdout) failed"));
167 168 169 170
        goto cleanup;
    }

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

    rc = 0;

cleanup:
179
    VIR_DEBUG("rc=%d", rc);
180 181 182 183
    return rc;
}

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

198 199 200
    writeCount = safewrite(control, &msg, sizeof(msg));
    if (writeCount != sizeof(msg)) {
        goto error_out;
201 202
    }

203 204 205
    rc = 0;
error_out:
    return rc;
206 207
}

208
/**
209
 * lxcContainerWaitForContinue:
210
 * @control: Control FD from parent
211 212 213 214 215 216 217
 *
 * 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
 */
218
int lxcContainerWaitForContinue(int control)
219 220 221 222
{
    lxc_message_t msg;
    int readLen;

223
    readLen = saferead(control, &msg, sizeof(msg));
224 225 226
    if (readLen != sizeof(msg) ||
        msg != LXC_CONTINUE_MSG) {
        return -1;
227 228
    }

229
    return 0;
230 231
}

232

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

251
    for (i = 0 ; i < nveths ; i++) {
252 253 254
        if (virAsprintf(&newname, "eth%d", i) < 0) {
            virReportOOMError();
            rc = -1;
255
            goto error_out;
256
        }
257

258
        VIR_DEBUG("Renaming %s to %s", veths[i], newname);
259
        rc = setInterfaceName(veths[i], newname);
260
        if (rc < 0)
261 262
            goto error_out;

263
        VIR_DEBUG("Enabling %s", newname);
264
        rc = vethInterfaceUpOrDown(newname, 1);
265
        if (rc < 0)
266
            goto error_out;
267

268
        VIR_FREE(newname);
269 270 271
    }

    /* enable lo device only if there were other net devices */
272
    if (veths)
273 274 275
        rc = vethInterfaceUpOrDown("lo", 1);

error_out:
276
    VIR_FREE(newname);
277 278 279
    return rc;
}

280

281
/*_syscall2(int, pivot_root, char *, newroot, const char *, oldroot)*/
282 283 284 285 286 287 288 289 290 291 292 293
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);
}

294
#ifndef MS_REC
295
# define MS_REC          16384
296 297 298
#endif

#ifndef MNT_DETACH
299
# define MNT_DETACH      0x00000002
300 301 302
#endif

#ifndef MS_PRIVATE
303
# define MS_PRIVATE              (1<<18)
304 305 306
#endif

#ifndef MS_SLAVE
307
# define MS_SLAVE                (1<<19)
308 309
#endif

310 311
static int lxcContainerPivotRoot(virDomainFSDefPtr root)
{
312
    int ret;
313
    char *oldroot = NULL, *newroot = NULL;
314

M
Mark McLoughlin 已提交
315 316
    ret = -1;

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

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

329 330
    if (virFileMakePath(oldroot) < 0) {
        virReportSystemError(errno,
331
                             _("Failed to create %s"),
332
                             oldroot);
333 334 335 336 337
        goto err;
    }

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

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

351 352
    if (virFileMakePath(newroot) < 0) {
        virReportSystemError(errno,
353
                             _("Failed to create %s"),
354 355 356 357 358 359
                             newroot);
        goto err;
    }

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

366 367 368 369 370 371 372 373 374
    if (root->readonly) {
        if (mount(root->src, newroot, NULL, MS_BIND|MS_REC|MS_RDONLY|MS_REMOUNT, NULL) < 0) {
            virReportSystemError(errno,
                                 _("Failed to make new root %s readonly"),
                                 root->src);
            goto err;
        }
    }

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

    /* The old root directory will live at /.oldroot after
     * this and will soon be unmounted completely */
385
    if (pivot_root(".", ".oldroot") < 0) {
386
        virReportSystemError(errno, "%s",
387
                             _("Failed to pivot root"));
388
        goto err;
389 390 391
    }

    /* CWD is undefined after pivot_root, so go to / */
392 393 394
    if (chdir("/") < 0)
        goto err;

M
Mark McLoughlin 已提交
395 396 397
    ret = 0;

err:
398 399 400
    VIR_FREE(oldroot);
    VIR_FREE(newroot);

M
Mark McLoughlin 已提交
401
    return ret;
402 403
}

404

405
static int lxcContainerMountBasicFS(const char *srcprefix)
406 407
{
    const struct {
408
        bool needPrefix;
409 410 411
        const char *src;
        const char *dst;
        const char *type;
412 413
        const char *opts;
        int mflags;
414
    } mnts[] = {
415 416 417 418 419 420
        /* When we want to make a bind mount readonly, for unknown reasons,
         * it is currently neccessary to bind it once, and then remount the
         * bind with the readonly flag. If this is not done, then the original
         * mount point in the main OS becomes readonly too which si not what
         * we want. Hence some things have two entries here.
         */
421 422 423
        { false, "devfs", "/dev", "tmpfs", "mode=755", MS_NOSUID },
        { false, "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV },
        { false, "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND },
424
        { false, "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY },
425
        { true, "/sys", "/sys", NULL, NULL, MS_BIND },
426
        { true, "/sys", "/sys", NULL, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY },
427
        { true, "/selinux", "/selinux", NULL, NULL, MS_BIND },
428
        { true, "/selinux", "/selinux", NULL, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY },
429
    };
430
    int i, rc = -1;
431 432

    for (i = 0 ; i < ARRAY_CARDINALITY(mnts) ; i++) {
433 434
        char *src = NULL;
        const char *srcpath = NULL;
435
        if (virFileMakePath(mnts[i].dst) < 0) {
436
            virReportSystemError(errno,
437
                                 _("Failed to mkdir %s"),
438
                                 mnts[i].src);
439
            goto cleanup;
440
        }
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

        if (mnts[i].needPrefix && srcprefix) {
            if (virAsprintf(&src, "%s%s", srcprefix, mnts[i].src) < 0) {
                virReportOOMError();
                goto cleanup;
            }
            srcpath = src;
        } else {
            srcpath = mnts[i].src;
        }

        /* Skip if mount doesn't exist in source */
        if ((srcpath[0] == '/') &&
            (access(srcpath, R_OK) < 0))
            continue;

        if (mount(srcpath, mnts[i].dst, mnts[i].type, mnts[i].mflags, mnts[i].opts) < 0) {
            VIR_FREE(src);
459
            virReportSystemError(errno,
460 461
                                 _("Failed to mount %s on %s type %s"),
                                 mnts[i].src, mnts[i].dst, NULLSTR(mnts[i].type));
462
            goto cleanup;
463
        }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        VIR_FREE(src);
    }

    rc = 0;

cleanup:
    VIR_DEBUG("rc=%d", rc);
    return rc;
}


static int lxcContainerMountDevFS(virDomainFSDefPtr root)
{
    char *devpts = NULL;
    int rc = -1;

    if (virAsprintf(&devpts, "/.oldroot%s/dev/pts", root->src) < 0) {
        virReportOOMError();
        goto cleanup;
483
    }
484

485 486
    if (virFileMakePath("/dev/pts") < 0) {
        virReportSystemError(errno, "%s",
487
                             _("Cannot create /dev/pts"));
488
        goto cleanup;
489
    }
490 491 492

    VIR_DEBUG("Trying to move %s to %s", devpts, "/dev/pts");
    if ((rc = mount(devpts, "/dev/pts", NULL, MS_MOVE, NULL)) < 0) {
493
        virReportSystemError(errno, "%s",
494
                             _("Failed to mount /dev/pts in container"));
495
        goto cleanup;
496
    }
497 498 499 500

    rc = 0;

 cleanup:
501 502
    VIR_FREE(devpts);

503
    return rc;
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
}

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" },
    };
521 522 523 524

    /* 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);
525
        if (mknod(devs[i].path, S_IFCHR, dev) < 0 ||
526
            chmod(devs[i].path, devs[i].mode)) {
527
            virReportSystemError(errno,
528
                                 _("Failed to make device %s"),
529
                                 devs[i].path);
530 531 532 533
            return -1;
        }
    }

534 535
    if (access("/dev/pts/ptmx", W_OK) == 0) {
        if (symlink("/dev/pts/ptmx", "/dev/ptmx") < 0) {
536
            virReportSystemError(errno, "%s",
537
                                 _("Failed to create symlink /dev/ptmx to /dev/pts/ptmx"));
538 539 540 541
            return -1;
        }
    } else {
        dev_t dev = makedev(LXC_DEV_MAJ_TTY, LXC_DEV_MIN_PTMX);
542
        if (mknod("/dev/ptmx", S_IFCHR, dev) < 0 ||
543
            chmod("/dev/ptmx", 0666)) {
544
            virReportSystemError(errno, "%s",
545
                                 _("Failed to make device /dev/ptmx"));
546 547 548 549
            return -1;
        }
    }

550 551 552 553 554 555 556 557 558
    /* 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;
    }
559 560 561 562 563
    if (symlink("/dev/pts/0", "/dev/console") < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to symlink /dev/pts/0 to /dev/console"));
        return -1;
    }
564

565 566 567 568
    return 0;
}


569 570
static int lxcContainerMountFSBind(virDomainFSDefPtr fs,
                                   const char *srcprefix)
571
{
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    char *src = NULL;
    int ret = -1;

    if (virAsprintf(&src, "%s%s", srcprefix, fs->src) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (virFileMakePath(fs->dst) < 0) {
        virReportSystemError(errno,
                             _("Failed to create %s"),
                             fs->dst);
        goto cleanup;
    }

    if (mount(src, fs->dst, NULL, MS_BIND, NULL) < 0) {
        virReportSystemError(errno,
                             _("Failed to bind mount directory %s to %s"),
                             src, fs->dst);
        goto cleanup;
    }

594 595 596 597 598 599 600 601 602 603 604
    if (fs->readonly) {
        VIR_DEBUG("Binding %s readonly", fs->dst);
        if (mount(fs->dst, fs->dst, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY, NULL) < 0) {
            virReportSystemError(errno,
                                 _("Failed to make directory %s readonly"),
                                 fs->dst);
            goto cleanup;
        }

    }

605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    ret = 0;

    VIR_DEBUG("Done mounting filesystem ret=%d", ret);

cleanup:
    VIR_FREE(src);
    return ret;
}


static int lxcContainerMountFS(virDomainFSDefPtr fs,
                               const char *srcprefix)
{
    switch (fs->type) {
    case VIR_DOMAIN_FS_TYPE_MOUNT:
        if (lxcContainerMountFSBind(fs, srcprefix) < 0)
            return -1;
        break;
    default:
        lxcError(VIR_ERR_CONFIG_UNSUPPORTED,
                 _("Cannot mount filesystem type %s"),
                 virDomainFSTypeToString(fs->type));
        break;
    }
    return 0;
}


static int lxcContainerMountAllFS(virDomainDefPtr vmDef,
                                  const char *dstprefix,
                                  bool skipRoot)
{
    size_t i;
    VIR_DEBUG("Mounting %s %d", dstprefix, skipRoot);
639 640

    /* Pull in rest of container's mounts */
641
    for (i = 0 ; i < vmDef->nfss ; i++) {
642 643
        if (skipRoot &&
            STREQ(vmDef->fss[i]->dst, "/"))
644 645
            continue;

646
        if (lxcContainerMountFS(vmDef->fss[i], dstprefix) < 0)
647 648 649
            return -1;
    }

650
    VIR_DEBUG("Mounted all filesystems");
651 652 653 654 655 656
    return 0;
}


static int lxcContainerUnmountOldFS(void)
{
657
    struct mntent mntent;
658 659 660 661
    char **mounts = NULL;
    int nmounts = 0;
    FILE *procmnt;
    int i;
662
    char mntbuf[1024];
663 664

    if (!(procmnt = setmntent("/proc/mounts", "r"))) {
665
        virReportSystemError(errno, "%s",
666
                             _("Failed to read /proc/mounts"));
667 668
        return -1;
    }
669
    while (getmntent_r(procmnt, &mntent, mntbuf, sizeof(mntbuf)) != NULL) {
670
        VIR_DEBUG("Got %s", mntent.mnt_dir);
671
        if (!STRPREFIX(mntent.mnt_dir, "/.oldroot"))
672 673 674 675
            continue;

        if (VIR_REALLOC_N(mounts, nmounts+1) < 0) {
            endmntent(procmnt);
676
            virReportOOMError();
677 678
            return -1;
        }
679
        if (!(mounts[nmounts++] = strdup(mntent.mnt_dir))) {
680
            endmntent(procmnt);
681
            virReportOOMError();
682 683 684 685 686
            return -1;
        }
    }
    endmntent(procmnt);

687 688 689
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
690 691

    for (i = 0 ; i < nmounts ; i++) {
692
        VIR_DEBUG("Umount %s", mounts[i]);
693
        if (umount(mounts[i]) < 0) {
694
            virReportSystemError(errno,
695
                                 _("Failed to unmount '%s'"),
696
                                 mounts[i]);
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
            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)
{
714
    /* Gives us a private root, leaving all parent OS mounts on /.oldroot */
715 716 717
    if (lxcContainerPivotRoot(root) < 0)
        return -1;

718 719 720 721 722 723
    /* Mounts the core /proc, /sys, etc filesystems */
    if (lxcContainerMountBasicFS("/.oldroot") < 0)
        return -1;

    /* Mounts /dev and /dev/pts */
    if (lxcContainerMountDevFS(root) < 0)
724 725
        return -1;

726
    /* Populates device nodes in /dev/ */
727 728 729
    if (lxcContainerPopulateDevices() < 0)
        return -1;

730
    /* Sets up any non-root mounts from guest config */
731
    if (lxcContainerMountAllFS(vmDef, "/.oldroot", true) < 0)
732 733
        return -1;

734
    /* Gets rid of all remaining mounts from host OS, including /.oldroot itself */
735 736 737 738 739 740
    if (lxcContainerUnmountOldFS() < 0)
        return -1;

    return 0;
}

741

742 743 744 745
/* Nothing mapped to /, we're using the main root,
   but with extra stuff mapped in */
static int lxcContainerSetupExtraMounts(virDomainDefPtr vmDef)
{
746 747 748 749 750 751
    VIR_DEBUG("def=%p", vmDef);
    /*
     * This makes sure that any new filesystems in the
     * host OS propagate to the container, but any
     * changes in the container are private
     */
752
    if (mount("", "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
753
        virReportSystemError(errno, "%s",
754
                             _("Failed to make / slave"));
755 756
        return -1;
    }
757

758
    VIR_DEBUG("Mounting config FS");
759 760
    if (lxcContainerMountAllFS(vmDef, "", false) < 0)
        return -1;
761

762 763 764
    /* Mounts the core /proc, /sys, etc filesystems */
    VIR_DEBUG("Mounting basic FS");
    if (lxcContainerMountBasicFS(NULL) < 0)
765 766
        return -1;

767
    VIR_DEBUG("Mounting completed");
768 769 770
    return 0;
}

771 772
static int lxcContainerSetupMounts(virDomainDefPtr vmDef,
                                   virDomainFSDefPtr root)
773 774 775 776 777 778 779
{
    if (root)
        return lxcContainerSetupPivotRoot(vmDef, root);
    else
        return lxcContainerSetupExtraMounts(vmDef);
}

D
Daniel P. Berrange 已提交
780 781 782 783 784 785 786

/*
 * 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)
787
{
D
Daniel P. Berrange 已提交
788 789 790 791 792 793 794 795 796 797 798 799 800 801
#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) {
802
        lxcError(VIR_ERR_INTERNAL_ERROR,
803
                 _("Failed to remove capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
804 805
        return -1;
    }
806

D
Daniel P. Berrange 已提交
807
    if ((ret = capng_apply(CAPNG_SELECT_BOTH)) < 0) {
808
        lxcError(VIR_ERR_INTERNAL_ERROR,
809
                 _("Failed to apply capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
810
        return -1;
811
    }
D
Daniel P. Berrange 已提交
812

813 814 815 816 817
    /* 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 已提交
818 819

#else
820
    VIR_WARN("libcap-ng support not compiled in, unable to clear capabilities");
D
Daniel Veillard 已提交
821
#endif
822 823 824 825
    return 0;
}


826
/**
827 828
 * lxcContainerChild:
 * @data: pointer to container arguments
829 830 831 832 833 834 835 836 837
 *
 * 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
 */
838
static int lxcContainerChild( void *data )
839
{
840
    lxc_child_argv_t *argv = data;
841
    virDomainDefPtr vmDef = argv->config;
842
    int ttyfd = -1;
843
    int ret = -1;
844
    char *ttyPath = NULL;
845
    virDomainFSDefPtr root;
846
    virCommandPtr cmd = NULL;
847 848

    if (NULL == vmDef) {
849
        lxcError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
850
                 "%s", _("lxcChild() passed invalid vm definition"));
851
        goto cleanup;
852 853
    }

854 855 856
    cmd = lxcContainerBuildInitCmd(vmDef);
    virCommandWriteArgLog(cmd, 1);

857
    root = virDomainGetRootFilesystem(vmDef);
858

859 860
    if (root) {
        if (virAsprintf(&ttyPath, "%s%s", root->src, argv->ttyPath) < 0) {
861
            virReportOOMError();
862
            goto cleanup;
863 864 865
        }
    } else {
        if (!(ttyPath = strdup(argv->ttyPath))) {
866
            virReportOOMError();
867
            goto cleanup;
868 869
        }
    }
870
    VIR_DEBUG("Container TTY path: %s", ttyPath);
871 872

    ttyfd = open(ttyPath, O_RDWR|O_NOCTTY);
873
    if (ttyfd < 0) {
874
        virReportSystemError(errno,
875
                             _("Failed to open tty %s"),
876
                             ttyPath);
877
        goto cleanup;
878
    }
879

880
    if (lxcContainerSetupMounts(vmDef, root) < 0)
881
        goto cleanup;
882

883 884 885 886 887 888 889
    if (!virFileExists(vmDef->os.init)) {
        virReportSystemError(errno,
                    _("cannot find init path '%s' relative to container root"),
                    vmDef->os.init);
        goto cleanup;
    }

890
    /* Wait for interface devices to show up */
891 892 893
    if (lxcContainerWaitForContinue(argv->monitor) < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to read the container continue message"));
894
        goto cleanup;
895 896
    }
    VIR_DEBUG("Received container continue message");
897

898 899
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
900
                                              argv->veths) < 0) {
901
        goto cleanup;
902
    }
903

904
    /* drop a set of root capabilities */
D
Daniel P. Berrange 已提交
905
    if (lxcContainerDropCapabilities() < 0)
906
        goto cleanup;
907

908 909 910 911 912 913 914
    if (lxcContainerSendContinue(argv->handshakefd) < 0) {
        virReportSystemError(errno, "%s",
                            _("failed to send continue signal to controller"));
        goto cleanup;
    }

    if (lxcContainerSetStdio(argv->monitor, ttyfd, argv->handshakefd) < 0) {
915 916
        goto cleanup;
    }
917

918
    ret = 0;
919
cleanup:
920 921
    VIR_FREE(ttyPath);
    VIR_FORCE_CLOSE(ttyfd);
922
    VIR_FORCE_CLOSE(argv->monitor);
923
    VIR_FORCE_CLOSE(argv->handshakefd);
924 925 926 927 928 929

    if (ret == 0) {
        /* this function will only return if an error occured */
        ret = virCommandExec(cmd);
    }

930 931
    virCommandFree(cmd);
    return ret;
932
}
933

934 935
static int userns_supported(void)
{
936 937 938 939 940 941
#if 1
    /*
     * put off using userns until uid mapping is implemented
     */
    return 0;
#else
942
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
943
#endif
944 945
}

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
const char *lxcContainerGetAlt32bitArch(const char *arch)
{
    /* Any Linux 64bit arch which has a 32bit
     * personality available should be listed here */
    if (STREQ(arch, "x86_64"))
        return "i686";
    if (STREQ(arch, "s390x"))
        return "s390";
    if (STREQ(arch, "ppc64"))
        return "ppc";
    if (STREQ(arch, "parisc64"))
        return "parisc";
    if (STREQ(arch, "sparc64"))
        return "sparc";
    if (STREQ(arch, "mips64"))
        return "mips";

    return NULL;
}


967 968
/**
 * lxcContainerStart:
969 970 971 972 973
 * @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
974 975 976 977 978
 *
 * Starts a container process by calling clone() with the namespace flags
 *
 * Returns PID of container on success or -1 in case of error
 */
979
int lxcContainerStart(virDomainDefPtr def,
980 981
                      unsigned int nveths,
                      char **veths,
982
                      int control,
983
                      int handshakefd,
984 985 986
                      char *ttyPath)
{
    pid_t pid;
E
Eric Blake 已提交
987
    int cflags;
988 989
    int stacksize = getpagesize() * 4;
    char *stack, *stacktop;
990 991
    lxc_child_argv_t args = { def, nveths, veths, control, ttyPath,
                              handshakefd};
992 993 994

    /* allocate a stack for the container */
    if (VIR_ALLOC_N(stack, stacksize) < 0) {
995
        virReportOOMError();
996 997 998 999
        return -1;
    }
    stacktop = stack + stacksize;

E
Eric Blake 已提交
1000
    cflags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;
1001

1002
    if (userns_supported()) {
1003
        VIR_DEBUG("Enable user namespaces");
E
Eric Blake 已提交
1004
        cflags |= CLONE_NEWUSER;
1005
    }
1006

1007
    if (def->nets != NULL) {
1008
        VIR_DEBUG("Enable network namespaces");
E
Eric Blake 已提交
1009
        cflags |= CLONE_NEWNET;
1010
    }
1011

E
Eric Blake 已提交
1012
    pid = clone(lxcContainerChild, stacktop, cflags, &args);
1013
    VIR_FREE(stack);
1014
    VIR_DEBUG("clone() completed, new container PID is %d", pid);
1015 1016

    if (pid < 0) {
1017
        virReportSystemError(errno, "%s",
1018
                             _("Failed to run clone container"));
1019 1020 1021 1022 1023 1024
        return -1;
    }

    return pid;
}

1025 1026
ATTRIBUTE_NORETURN static int
lxcContainerDummyChild(void *argv ATTRIBUTE_UNUSED)
1027 1028 1029 1030 1031 1032
{
    _exit(0);
}

int lxcContainerAvailable(int features)
{
1033
    int flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|
1034 1035 1036 1037 1038 1039
        CLONE_NEWIPC|SIGCHLD;
    int cpid;
    char *childStack;
    char *stack;
    int childStatus;

1040 1041 1042
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

1043 1044 1045 1046
    if (features & LXC_CONTAINER_FEATURE_NET)
        flags |= CLONE_NEWNET;

    if (VIR_ALLOC_N(stack, getpagesize() * 4) < 0) {
1047
        VIR_DEBUG("Unable to allocate stack");
1048 1049 1050 1051 1052 1053 1054 1055
        return -1;
    }

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

    cpid = clone(lxcContainerDummyChild, childStack, flags, NULL);
    VIR_FREE(stack);
    if (cpid < 0) {
1056
        char ebuf[1024];
1057
        VIR_DEBUG("clone call returned %s, container support is not enabled",
1058
              virStrerror(errno, ebuf, sizeof ebuf));
1059 1060 1061 1062 1063
        return -1;
    } else {
        waitpid(cpid, &childStatus, 0);
    }

1064
    VIR_DEBUG("Mounted all filesystems");
1065
    return 0;
1066
}