lxc_container.c 25.4 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 "uuid.h"
56
#include "files.h"
57

58 59
#define VIR_FROM_THIS VIR_FROM_LXC

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

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


95
/**
96
 * lxcContainerExecInit:
97
 * @vmDef: pointer to vm definition structure
98
 *
99
 * Exec the container init string. The container init will replace then
100 101
 * be running in the current process
 *
102
 * Does not return
103
 */
104
static int lxcContainerExecInit(virDomainDefPtr vmDef)
105
{
106 107 108 109 110 111 112 113 114 115 116 117 118 119
    char *uuidenv, *nameenv;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vmDef->uuid, uuidstr);

    if (virAsprintf(&uuidenv, "LIBVIRT_LXC_UUID=%s", uuidstr) < 0) {
        virReportOOMError();
        return -1;
    }
    if (virAsprintf(&nameenv, "LIBVIRT_LXC_NAME=%s", vmDef->name) < 0) {
        virReportOOMError();
        return -1;
    }

120
    const char *const argv[] = {
121
        vmDef->os.init,
122 123
        NULL,
    };
124 125 126
    const char *const envp[] = {
        "PATH=/bin:/sbin",
        "TERM=linux",
127 128
        uuidenv,
        nameenv,
129 130
        NULL,
    };
131

132
    return execve(argv[0], (char **)argv,(char**)envp);
133 134 135
}

/**
136
 * lxcContainerSetStdio:
137 138
 * @control: control FD from parent
 * @ttyfd: FD of tty to set as the container console
139 140 141 142 143 144
 *
 * 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
 */
145
static int lxcContainerSetStdio(int control, int ttyfd)
146 147
{
    int rc = -1;
148
    int open_max, i;
149 150

    if (setsid() < 0) {
151
        virReportSystemError(errno, "%s",
152
                             _("setsid failed"));
153
        goto cleanup;
154 155 156
    }

    if (ioctl(ttyfd, TIOCSCTTY, NULL) < 0) {
157
        virReportSystemError(errno, "%s",
158
                             _("ioctl(TIOCSTTY) failed"));
159 160 161
        goto cleanup;
    }

162 163 164 165
    /* 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++)
166 167 168 169
        if (i != ttyfd && i != control) {
            int tmpfd = i;
            VIR_FORCE_CLOSE(tmpfd);
        }
170 171

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

    if (dup2(ttyfd, 1) < 0) {
178
        virReportSystemError(errno, "%s",
179
                             _("dup2(stdout) failed"));
180 181 182 183
        goto cleanup;
    }

    if (dup2(ttyfd, 2) < 0) {
184
        virReportSystemError(errno, "%s",
185
                             _("dup2(stderr) failed"));
186 187 188 189 190 191 192 193 194 195
        goto cleanup;
    }

    rc = 0;

cleanup:
    return rc;
}

/**
196
 * lxcContainerSendContinue:
197
 * @control: control FD to child
198
 *
199 200
 * Sends the continue message via the socket pair stored in the vm
 * structure.
201 202 203
 *
 * Returns 0 on success or -1 in case of error
 */
204
int lxcContainerSendContinue(int control)
205 206
{
    int rc = -1;
207 208
    lxc_message_t msg = LXC_CONTINUE_MSG;
    int writeCount = 0;
209

210 211
    writeCount = safewrite(control, &msg, sizeof(msg));
    if (writeCount != sizeof(msg)) {
212
        virReportSystemError(errno, "%s",
213
                             _("Unable to send container continue message"));
214
        goto error_out;
215 216
    }

217
    rc = 0;
218

219 220
error_out:
    return rc;
221 222
}

223
/**
224
 * lxcContainerWaitForContinue:
225
 * @control: Control FD from parent
226 227 228 229 230 231 232
 *
 * 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
 */
233
static int lxcContainerWaitForContinue(int control)
234 235 236 237
{
    lxc_message_t msg;
    int readLen;

238
    readLen = saferead(control, &msg, sizeof(msg));
239 240
    if (readLen != sizeof(msg) ||
        msg != LXC_CONTINUE_MSG) {
241
        virReportSystemError(errno, "%s",
242
                             _("Failed to read the container continue message"));
243
        return -1;
244
    }
245
    VIR_FORCE_CLOSE(control);
246

247
    VIR_DEBUG0("Received container continue message");
248

249
    return 0;
250 251
}

252

253
/**
254
 * lxcContainerRenameAndEnableInterfaces:
255 256
 * @nveths: number of interfaces
 * @veths: interface names
257
 *
258 259 260
 * This function will rename the interfaces to ethN
 * with id ascending order from zero and enable the
 * renamed interfaces for this container.
261 262 263
 *
 * Returns 0 on success or nonzero in case of error
 */
264 265
static int lxcContainerRenameAndEnableInterfaces(unsigned int nveths,
                                                 char **veths)
266 267
{
    int rc = 0;
268
    unsigned int i;
269
    char *newname = NULL;
270

271
    for (i = 0 ; i < nveths ; i++) {
272 273 274
        if (virAsprintf(&newname, "eth%d", i) < 0) {
            virReportOOMError();
            rc = -1;
275
            goto error_out;
276
        }
277

278
        VIR_DEBUG("Renaming %s to %s", veths[i], newname);
279
        rc = setInterfaceName(veths[i], newname);
280
        if (rc < 0)
281 282
            goto error_out;

283
        VIR_DEBUG("Enabling %s", newname);
284
        rc = vethInterfaceUpOrDown(newname, 1);
285
        if (rc < 0)
286
            goto error_out;
287

288
        VIR_FREE(newname);
289 290 291
    }

    /* enable lo device only if there were other net devices */
292
    if (veths)
293 294 295
        rc = vethInterfaceUpOrDown("lo", 1);

error_out:
296
    VIR_FREE(newname);
297 298 299
    return rc;
}

300

301
/*_syscall2(int, pivot_root, char *, newroot, const char *, oldroot)*/
302 303 304 305 306 307 308 309 310 311 312 313
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);
}

314
#ifndef MS_REC
315
# define MS_REC          16384
316 317 318
#endif

#ifndef MNT_DETACH
319
# define MNT_DETACH      0x00000002
320 321 322
#endif

#ifndef MS_PRIVATE
323
# define MS_PRIVATE              (1<<18)
324 325 326
#endif

#ifndef MS_SLAVE
327
# define MS_SLAVE                (1<<19)
328 329
#endif

330 331
static int lxcContainerPivotRoot(virDomainFSDefPtr root)
{
M
Mark McLoughlin 已提交
332
    int rc, ret;
333
    char *oldroot = NULL, *newroot = NULL;
334

M
Mark McLoughlin 已提交
335 336
    ret = -1;

337 338
    /* root->parent must be private, so make / private. */
    if (mount("", "/", NULL, MS_PRIVATE|MS_REC, NULL) < 0) {
339
        virReportSystemError(errno, "%s",
340
                             _("Failed to make root private"));
341
        goto err;
342 343
    }

344
    if (virAsprintf(&oldroot, "%s/.oldroot", root->src) < 0) {
345
        virReportOOMError();
346
        goto err;
347 348
    }

L
Laine Stump 已提交
349
    if ((rc = virFileMakePath(oldroot)) != 0) {
350
        virReportSystemError(rc,
351
                             _("Failed to create %s"),
352
                             oldroot);
353 354 355 356 357
        goto err;
    }

    /* Create a tmpfs root since old and new roots must be
     * on separate filesystems */
358
    if (mount("tmprootfs", oldroot, "tmpfs", 0, NULL) < 0) {
359
        virReportSystemError(errno,
360
                             _("Failed to mount empty tmpfs at %s"),
361 362 363
                             oldroot);
        goto err;
    }
M
Mark McLoughlin 已提交
364

365 366
    /* Create a directory called 'new' in tmpfs */
    if (virAsprintf(&newroot, "%s/new", oldroot) < 0) {
367
        virReportOOMError();
368 369 370
        goto err;
    }

L
Laine Stump 已提交
371
    if ((rc = virFileMakePath(newroot)) != 0) {
372
        virReportSystemError(rc,
373
                             _("Failed to create %s"),
374 375 376 377 378 379
                             newroot);
        goto err;
    }

    /* ... and mount our root onto it */
    if (mount(root->src, newroot, NULL, MS_BIND|MS_REC, NULL) < 0) {
380
        virReportSystemError(errno,
381
                             _("Failed to bind new root %s into tmpfs"),
382 383 384 385 386 387
                             root->src);
        goto err;
    }

    /* Now we chroot into the tmpfs, then pivot into the
     * root->src bind-mounted onto '/new' */
388
    if (chdir(newroot) < 0) {
389
        virReportSystemError(errno,
390
                             _("Failed to chroot into %s"), newroot);
391
        goto err;
392 393 394 395
    }

    /* The old root directory will live at /.oldroot after
     * this and will soon be unmounted completely */
396
    if (pivot_root(".", ".oldroot") < 0) {
397
        virReportSystemError(errno, "%s",
398
                             _("Failed to pivot root"));
399
        goto err;
400 401 402
    }

    /* CWD is undefined after pivot_root, so go to / */
403 404 405
    if (chdir("/") < 0)
        goto err;

M
Mark McLoughlin 已提交
406 407 408
    ret = 0;

err:
409 410 411
    VIR_FREE(oldroot);
    VIR_FREE(newroot);

M
Mark McLoughlin 已提交
412
    return ret;
413 414
}

415 416

static int lxcContainerMountBasicFS(virDomainFSDefPtr root)
417 418
{
    const struct {
419 420 421 422 423 424 425 426 427 428
        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
429
    };
430
    int i, rc = -1;
431
    char *devpts;
432

433
    if (virAsprintf(&devpts, "/.oldroot%s/dev/pts", root->src) < 0) {
434
        virReportOOMError();
435
        return rc;
436
    }
437 438

    for (i = 0 ; i < ARRAY_CARDINALITY(mnts) ; i++) {
L
Laine Stump 已提交
439
        if (virFileMakePath(mnts[i].dst) != 0) {
440
            virReportSystemError(errno,
441
                                 _("Failed to mkdir %s"),
442
                                 mnts[i].src);
443
            goto cleanup;
444 445
        }
        if (mount(mnts[i].src, mnts[i].dst, mnts[i].type, 0, NULL) < 0) {
446
            virReportSystemError(errno,
447
                                 _("Failed to mount %s on %s"),
448
                                 mnts[i].type, mnts[i].type);
449
            goto cleanup;
450
        }
451
    }
452

L
Laine Stump 已提交
453
    if ((rc = virFileMakePath("/dev/pts") != 0)) {
454
        virReportSystemError(rc, "%s",
455
                             _("Cannot create /dev/pts"));
456
        goto cleanup;
457
    }
458 459 460

    VIR_DEBUG("Trying to move %s to %s", devpts, "/dev/pts");
    if ((rc = mount(devpts, "/dev/pts", NULL, MS_MOVE, NULL)) < 0) {
461
        virReportSystemError(errno, "%s",
462
                             _("Failed to mount /dev/pts in container"));
463
        goto cleanup;
464
    }
465 466 467 468

    rc = 0;

 cleanup:
469 470
    VIR_FREE(devpts);

471
    return rc;
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
}

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" },
    };
489 490 491 492

    /* 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);
493
        if (mknod(devs[i].path, S_IFCHR, dev) < 0 ||
494
            chmod(devs[i].path, devs[i].mode)) {
495
            virReportSystemError(errno,
496
                                 _("Failed to make device %s"),
497
                                 devs[i].path);
498 499 500 501
            return -1;
        }
    }

502 503
    if (access("/dev/pts/ptmx", W_OK) == 0) {
        if (symlink("/dev/pts/ptmx", "/dev/ptmx") < 0) {
504
            virReportSystemError(errno, "%s",
505
                                 _("Failed to create symlink /dev/ptmx to /dev/pts/ptmx"));
506 507 508 509
            return -1;
        }
    } else {
        dev_t dev = makedev(LXC_DEV_MAJ_TTY, LXC_DEV_MIN_PTMX);
510
        if (mknod("/dev/ptmx", S_IFCHR, dev) < 0 ||
511
            chmod("/dev/ptmx", 0666)) {
512
            virReportSystemError(errno, "%s",
513
                                 _("Failed to make device /dev/ptmx"));
514 515 516 517
            return -1;
        }
    }

518 519 520 521 522 523 524 525 526
    /* 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;
    }
527 528 529 530 531
    if (symlink("/dev/pts/0", "/dev/console") < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to symlink /dev/pts/0 to /dev/console"));
        return -1;
    }
532

533 534 535 536 537 538
    return 0;
}


static int lxcContainerMountNewFS(virDomainDefPtr vmDef)
{
539
    int i;
540 541

    /* Pull in rest of container's mounts */
542
    for (i = 0 ; i < vmDef->nfss ; i++) {
543
        char *src;
544
        if (STREQ(vmDef->fss[i]->dst, "/"))
545
            continue;
546
        /* XXX fix */
547
        if (vmDef->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
548 549
            continue;

550
        if (virAsprintf(&src, "/.oldroot/%s", vmDef->fss[i]->src) < 0) {
551
            virReportOOMError();
552 553 554
            return -1;
        }

L
Laine Stump 已提交
555
        if (virFileMakePath(vmDef->fss[i]->dst) != 0) {
556
            virReportSystemError(errno,
557
                                 _("Failed to create %s"),
558
                                 vmDef->fss[i]->dst);
559
            VIR_FREE(src);
560 561 562
            return -1;
        }
        if (mount(src, vmDef->fss[i]->dst, NULL, MS_BIND, NULL) < 0) {
563
            virReportSystemError(errno,
564 565 566
                                 _("Failed to mount %s at %s"),
                                 src, vmDef->fss[i]->dst);
            VIR_FREE(src);
567 568 569 570 571 572 573 574 575 576 577
            return -1;
        }
        VIR_FREE(src);
    }

    return 0;
}


static int lxcContainerUnmountOldFS(void)
{
578
    struct mntent mntent;
579 580 581 582
    char **mounts = NULL;
    int nmounts = 0;
    FILE *procmnt;
    int i;
583
    char mntbuf[1024];
584 585

    if (!(procmnt = setmntent("/proc/mounts", "r"))) {
586
        virReportSystemError(errno, "%s",
587
                             _("Failed to read /proc/mounts"));
588 589
        return -1;
    }
590
    while (getmntent_r(procmnt, &mntent, mntbuf, sizeof(mntbuf)) != NULL) {
591
        VIR_DEBUG("Got %s", mntent.mnt_dir);
592
        if (!STRPREFIX(mntent.mnt_dir, "/.oldroot"))
593 594 595 596
            continue;

        if (VIR_REALLOC_N(mounts, nmounts+1) < 0) {
            endmntent(procmnt);
597
            virReportOOMError();
598 599
            return -1;
        }
600
        if (!(mounts[nmounts++] = strdup(mntent.mnt_dir))) {
601
            endmntent(procmnt);
602
            virReportOOMError();
603 604 605 606 607
            return -1;
        }
    }
    endmntent(procmnt);

608 609 610
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
611 612

    for (i = 0 ; i < nmounts ; i++) {
613
        VIR_DEBUG("Umount %s", mounts[i]);
614
        if (umount(mounts[i]) < 0) {
615
            virReportSystemError(errno,
616
                                 _("Failed to unmount '%s'"),
617
                                 mounts[i]);
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
            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)
{
635
    /* Gives us a private root, leaving all parent OS mounts on /.oldroot */
636 637 638
    if (lxcContainerPivotRoot(root) < 0)
        return -1;

639 640
    /* Mounts the core /proc, /sys, /dev, /dev/pts filesystems */
    if (lxcContainerMountBasicFS(root) < 0)
641 642
        return -1;

643
    /* Populates device nodes in /dev/ */
644 645 646
    if (lxcContainerPopulateDevices() < 0)
        return -1;

647
    /* Sets up any non-root mounts from guest config */
648 649 650
    if (lxcContainerMountNewFS(vmDef) < 0)
        return -1;

651
    /* Gets rid of all remaining mounts from host OS, including /.oldroot itself */
652 653 654 655 656 657 658 659 660 661
    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)
{
662
    int i;
663

664
    if (mount("", "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
665
        virReportSystemError(errno, "%s",
666
                             _("Failed to make / slave"));
667 668
        return -1;
    }
669
    for (i = 0 ; i < vmDef->nfss ; i++) {
670
        /* XXX fix to support other mount types */
671
        if (vmDef->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
672 673
            continue;

674 675
        if (mount(vmDef->fss[i]->src,
                  vmDef->fss[i]->dst,
676 677 678
                  NULL,
                  MS_BIND,
                  NULL) < 0) {
679
            virReportSystemError(errno,
680
                                 _("Failed to mount %s at %s"),
681 682
                                 vmDef->fss[i]->src,
                                 vmDef->fss[i]->dst);
683 684 685 686 687 688
            return -1;
        }
    }

    /* mount /proc */
    if (mount("lxcproc", "/proc", "proc", 0, NULL) < 0) {
689
        virReportSystemError(errno, "%s",
690
                             _("Failed to mount /proc"));
691 692 693 694 695 696
        return -1;
    }

    return 0;
}

697 698
static int lxcContainerSetupMounts(virDomainDefPtr vmDef,
                                   virDomainFSDefPtr root)
699 700 701 702 703 704 705
{
    if (root)
        return lxcContainerSetupPivotRoot(vmDef, root);
    else
        return lxcContainerSetupExtraMounts(vmDef);
}

D
Daniel P. Berrange 已提交
706 707 708 709 710 711 712

/*
 * 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)
713
{
D
Daniel P. Berrange 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727
#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) {
728
        lxcError(VIR_ERR_INTERNAL_ERROR,
729
                 _("Failed to remove capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
730 731
        return -1;
    }
732

D
Daniel P. Berrange 已提交
733
    if ((ret = capng_apply(CAPNG_SELECT_BOTH)) < 0) {
734
        lxcError(VIR_ERR_INTERNAL_ERROR,
735
                 _("Failed to apply capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
736
        return -1;
737
    }
D
Daniel P. Berrange 已提交
738

739 740 741 742 743
    /* 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 已提交
744 745

#else
746
    VIR_WARN0("libcap-ng support not compiled in, unable to clear capabilities");
D
Daniel Veillard 已提交
747
#endif
748 749 750 751
    return 0;
}


752
/**
753 754
 * lxcContainerChild:
 * @data: pointer to container arguments
755 756 757 758 759 760 761 762 763
 *
 * 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
 */
764
static int lxcContainerChild( void *data )
765
{
766
    lxc_child_argv_t *argv = data;
767
    virDomainDefPtr vmDef = argv->config;
768
    int ttyfd;
769 770
    char *ttyPath;
    virDomainFSDefPtr root;
771 772

    if (NULL == vmDef) {
773
        lxcError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
774
                 "%s", _("lxcChild() passed invalid vm definition"));
775
        return -1;
776 777
    }

778
    root = virDomainGetRootFilesystem(vmDef);
779

780 781
    if (root) {
        if (virAsprintf(&ttyPath, "%s%s", root->src, argv->ttyPath) < 0) {
782
            virReportOOMError();
783 784 785 786
            return -1;
        }
    } else {
        if (!(ttyPath = strdup(argv->ttyPath))) {
787
            virReportOOMError();
788 789 790 791 792
            return -1;
        }
    }

    ttyfd = open(ttyPath, O_RDWR|O_NOCTTY);
793
    if (ttyfd < 0) {
794
        virReportSystemError(errno,
795
                             _("Failed to open tty %s"),
796
                             ttyPath);
797
        VIR_FREE(ttyPath);
798
        return -1;
799
    }
800
    VIR_FREE(ttyPath);
801

802
    if (lxcContainerSetStdio(argv->monitor, ttyfd) < 0) {
803
        VIR_FORCE_CLOSE(ttyfd);
804
        return -1;
805
    }
806
    VIR_FORCE_CLOSE(ttyfd);
807

808 809 810
    if (lxcContainerSetupMounts(vmDef, root) < 0)
        return -1;

811
    /* Wait for interface devices to show up */
812 813
    if (lxcContainerWaitForContinue(argv->monitor) < 0)
        return -1;
814

815 816 817
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
                                              argv->veths) < 0)
818
        return -1;
819

820
    /* drop a set of root capabilities */
D
Daniel P. Berrange 已提交
821
    if (lxcContainerDropCapabilities() < 0)
822 823
        return -1;

824
    /* this function will only return if an error occured */
825 826
    return lxcContainerExecInit(vmDef);
}
827

828 829
static int userns_supported(void)
{
830 831 832 833 834 835
#if 1
    /*
     * put off using userns until uid mapping is implemented
     */
    return 0;
#else
836
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
837
#endif
838 839
}

840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
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;
}


861 862
/**
 * lxcContainerStart:
863 864 865 866 867
 * @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
868 869 870 871 872
 *
 * Starts a container process by calling clone() with the namespace flags
 *
 * Returns PID of container on success or -1 in case of error
 */
873
int lxcContainerStart(virDomainDefPtr def,
874 875
                      unsigned int nveths,
                      char **veths,
876 877 878 879 880 881 882
                      int control,
                      char *ttyPath)
{
    pid_t pid;
    int flags;
    int stacksize = getpagesize() * 4;
    char *stack, *stacktop;
883
    lxc_child_argv_t args = { def, nveths, veths, control, ttyPath };
884 885 886

    /* allocate a stack for the container */
    if (VIR_ALLOC_N(stack, stacksize) < 0) {
887
        virReportOOMError();
888 889 890 891
        return -1;
    }
    stacktop = stack + stacksize;

892 893
    flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;

894
    if (userns_supported()) {
895
        VIR_DEBUG0("Enable user namespaces");
896
        flags |= CLONE_NEWUSER;
897
    }
898

899
    if (def->nets != NULL) {
900
        VIR_DEBUG0("Enable network namespaces");
901
        flags |= CLONE_NEWNET;
902
    }
903 904 905

    pid = clone(lxcContainerChild, stacktop, flags, &args);
    VIR_FREE(stack);
906
    VIR_DEBUG("clone() completed, new container PID is %d", pid);
907 908

    if (pid < 0) {
909
        virReportSystemError(errno, "%s",
910
                             _("Failed to run clone container"));
911 912 913 914 915 916
        return -1;
    }

    return pid;
}

917 918
ATTRIBUTE_NORETURN static int
lxcContainerDummyChild(void *argv ATTRIBUTE_UNUSED)
919 920 921 922 923 924
{
    _exit(0);
}

int lxcContainerAvailable(int features)
{
925
    int flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|
926 927 928 929 930 931
        CLONE_NEWIPC|SIGCHLD;
    int cpid;
    char *childStack;
    char *stack;
    int childStatus;

932 933 934
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

935 936 937 938
    if (features & LXC_CONTAINER_FEATURE_NET)
        flags |= CLONE_NEWNET;

    if (VIR_ALLOC_N(stack, getpagesize() * 4) < 0) {
939
        VIR_DEBUG0("Unable to allocate stack");
940 941 942 943 944 945 946 947
        return -1;
    }

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

    cpid = clone(lxcContainerDummyChild, childStack, flags, NULL);
    VIR_FREE(stack);
    if (cpid < 0) {
948
        char ebuf[1024];
949
        VIR_DEBUG("clone call returned %s, container support is not enabled",
950
              virStrerror(errno, ebuf, sizeof ebuf));
951 952 953 954 955 956
        return -1;
    } else {
        waitpid(cpid, &childStatus, 0);
    }

    return 0;
957
}