lxc_container.c 24.3 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

56 57
#define VIR_FROM_THIS VIR_FROM_LXC

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

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


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

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

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

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

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

144 145 146 147
    /* 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++)
148
        if (i != ttyfd && i != control)
149
            close(i);
150 151

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

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

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

    rc = 0;

cleanup:
    return rc;
}

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

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

197
    rc = 0;
198

199 200
error_out:
    return rc;
201 202
}

203
/**
204
 * lxcContainerWaitForContinue:
205
 * @control: Control FD from parent
206 207 208 209 210 211 212
 *
 * 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
 */
213
static int lxcContainerWaitForContinue(int control)
214 215 216 217
{
    lxc_message_t msg;
    int readLen;

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

    DEBUG0("Received container continue message");

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
        rc = virAsprintf(&newname, "eth%d", i);
        if (rc < 0)
254
            goto error_out;
255 256 257

        DEBUG("Renaming %s to %s", veths[i], newname);
        rc = setInterfaceName(veths[i], newname);
258 259 260 261
        if (0 != rc) {
            VIR_ERROR(_("Failed to rename %s to %s (%d)"),
                      veths[i], newname, rc);
            rc = -1;
262
            goto error_out;
263
        }
264 265

        DEBUG("Enabling %s", newname);
266 267 268 269
        rc = vethInterfaceUpOrDown(newname, 1);
        if (0 != rc) {
            VIR_ERROR(_("Failed to enable %s (%d)"), newname, rc);
            rc = -1;
270
            goto error_out;
271
        }
272
        VIR_FREE(newname);
273 274 275
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

399 400

static int lxcContainerMountBasicFS(virDomainFSDefPtr root)
401 402
{
    const struct {
403 404 405 406 407 408 409 410 411 412
        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
413
    };
414
    int i, rc = -1;
415
    char *devpts;
416

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

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

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

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

    rc = 0;

 cleanup:
453 454
    VIR_FREE(devpts);

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

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

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

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

503 504 505 506 507 508 509 510 511
    /* 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;
    }
512

513 514 515 516 517 518
    return 0;
}


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

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

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

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

    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

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

719 720 721 722 723
    /* 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 已提交
724 725

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


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

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

758
    root = virDomainGetRootFilesystem(vmDef);
759

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

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

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

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

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

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

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

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

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

813 814
/**
 * lxcContainerStart:
815 816 817 818 819
 * @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
820 821 822 823 824
 *
 * Starts a container process by calling clone() with the namespace flags
 *
 * Returns PID of container on success or -1 in case of error
 */
825
int lxcContainerStart(virDomainDefPtr def,
826 827
                      unsigned int nveths,
                      char **veths,
828 829 830 831 832 833 834
                      int control,
                      char *ttyPath)
{
    pid_t pid;
    int flags;
    int stacksize = getpagesize() * 4;
    char *stack, *stacktop;
835
    lxc_child_argv_t args = { def, nveths, veths, control, ttyPath };
836 837 838

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

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

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

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

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

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

    return pid;
}

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

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

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

886 887 888 889 890 891 892 893 894 895 896 897 898
    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) {
899
        char ebuf[1024];
900
        DEBUG("clone call returned %s, container support is not enabled",
901
              virStrerror(errno, ebuf, sizeof ebuf));
902 903 904 905 906 907
        return -1;
    } else {
        waitpid(cpid, &childStatus, 0);
    }

    return 0;
908
}