lxc_container.c 24.1 KB
Newer Older
1 2
/*
 * Copyright IBM Corp. 2008
3
 * Copyright Red Hat 2008-2009
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 258 259 260 261 262 263 264 265

        DEBUG("Renaming %s to %s", veths[i], newname);
        rc = setInterfaceName(veths[i], newname);
        if (0 != rc)
            goto error_out;

        DEBUG("Enabling %s", newname);
        rc =  vethInterfaceUpOrDown(newname, 1);
        if (0 != rc)
            goto error_out;
        VIR_FREE(newname);
266 267 268
    }

    /* enable lo device only if there were other net devices */
269
    if (veths)
270 271 272
        rc = vethInterfaceUpOrDown("lo", 1);

error_out:
273
    VIR_FREE(newname);
274 275 276
    return rc;
}

277 278 279 280 281 282 283 284 285 286 287 288 289 290

//_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);
}

291
#ifndef MS_REC
292
# define MS_REC          16384
293 294 295
#endif

#ifndef MNT_DETACH
296
# define MNT_DETACH      0x00000002
297 298 299
#endif

#ifndef MS_PRIVATE
300
# define MS_PRIVATE              (1<<18)
301 302 303
#endif

#ifndef MS_SLAVE
304
# define MS_SLAVE                (1<<19)
305 306
#endif

307 308
static int lxcContainerPivotRoot(virDomainFSDefPtr root)
{
M
Mark McLoughlin 已提交
309
    int rc, ret;
310
    char *oldroot = NULL, *newroot = NULL;
311

M
Mark McLoughlin 已提交
312 313
    ret = -1;

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

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

L
Laine Stump 已提交
326
    if ((rc = virFileMakePath(oldroot)) != 0) {
327
        virReportSystemError(rc,
328
                             _("Failed to create %s"),
329
                             oldroot);
330 331 332 333 334
        goto err;
    }

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

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

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

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

    /* Now we chroot into the tmpfs, then pivot into the
     * root->src bind-mounted onto '/new' */
365
    if (chdir(newroot) < 0) {
366
        virReportSystemError(errno,
367
                             _("Failed to chroot into %s"), newroot);
368
        goto err;
369 370 371 372
    }

    /* The old root directory will live at /.oldroot after
     * this and will soon be unmounted completely */
373
    if (pivot_root(".", ".oldroot") < 0) {
374
        virReportSystemError(errno, "%s",
375
                             _("Failed to pivot root"));
376
        goto err;
377 378 379
    }

    /* CWD is undefined after pivot_root, so go to / */
380 381 382
    if (chdir("/") < 0)
        goto err;

M
Mark McLoughlin 已提交
383 384 385
    ret = 0;

err:
386 387 388
    VIR_FREE(oldroot);
    VIR_FREE(newroot);

M
Mark McLoughlin 已提交
389
    return ret;
390 391
}

392 393

static int lxcContainerMountBasicFS(virDomainFSDefPtr root)
394 395
{
    const struct {
396 397 398 399 400 401 402 403 404 405
        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
406
    };
407
    int i, rc = -1;
408
    char *devpts;
409

410
    if (virAsprintf(&devpts, "/.oldroot%s/dev/pts", root->src) < 0) {
411
        virReportOOMError();
412
        return rc;
413
    }
414 415

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

L
Laine Stump 已提交
430
    if ((rc = virFileMakePath("/dev/pts") != 0)) {
431
        virReportSystemError(rc, "%s",
432
                             _("Cannot create /dev/pts"));
433
        goto cleanup;
434
    }
435 436 437

    VIR_DEBUG("Trying to move %s to %s", devpts, "/dev/pts");
    if ((rc = mount(devpts, "/dev/pts", NULL, MS_MOVE, NULL)) < 0) {
438
        virReportSystemError(errno, "%s",
439
                             _("Failed to mount /dev/pts in container"));
440
        goto cleanup;
441
    }
442 443 444 445

    rc = 0;

 cleanup:
446 447
    VIR_FREE(devpts);

448
    return rc;
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
}

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" },
    };
467 468 469 470

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

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

496 497 498 499 500 501 502 503 504
    /* 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;
    }
505

506 507 508 509 510 511
    return 0;
}


static int lxcContainerMountNewFS(virDomainDefPtr vmDef)
{
512
    int i;
513 514

    /* Pull in rest of container's mounts */
515
    for (i = 0 ; i < vmDef->nfss ; i++) {
516
        char *src;
517
        if (STREQ(vmDef->fss[i]->dst, "/"))
518 519
            continue;
        // XXX fix
520
        if (vmDef->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
521 522
            continue;

523
        if (virAsprintf(&src, "/.oldroot/%s", vmDef->fss[i]->src) < 0) {
524
            virReportOOMError();
525 526 527
            return -1;
        }

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

    return 0;
}


static int lxcContainerUnmountOldFS(void)
{
551
    struct mntent mntent;
552 553 554 555
    char **mounts = NULL;
    int nmounts = 0;
    FILE *procmnt;
    int i;
556
    char mntbuf[1024];
557 558

    if (!(procmnt = setmntent("/proc/mounts", "r"))) {
559
        virReportSystemError(errno, "%s",
560
                             _("Failed to read /proc/mounts"));
561 562
        return -1;
    }
563
    while (getmntent_r(procmnt, &mntent, mntbuf, sizeof(mntbuf)) != NULL) {
564
        VIR_DEBUG("Got %s", mntent.mnt_dir);
565
        if (!STRPREFIX(mntent.mnt_dir, "/.oldroot"))
566 567 568 569
            continue;

        if (VIR_REALLOC_N(mounts, nmounts+1) < 0) {
            endmntent(procmnt);
570
            virReportOOMError();
571 572
            return -1;
        }
573
        if (!(mounts[nmounts++] = strdup(mntent.mnt_dir))) {
574
            endmntent(procmnt);
575
            virReportOOMError();
576 577 578 579 580
            return -1;
        }
    }
    endmntent(procmnt);

581 582 583
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
584 585

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

612 613
    /* Mounts the core /proc, /sys, /dev, /dev/pts filesystems */
    if (lxcContainerMountBasicFS(root) < 0)
614 615
        return -1;

616
    /* Populates device nodes in /dev/ */
617 618 619
    if (lxcContainerPopulateDevices() < 0)
        return -1;

620
    /* Sets up any non-root mounts from guest config */
621 622 623
    if (lxcContainerMountNewFS(vmDef) < 0)
        return -1;

624
    /* Gets rid of all remaining mounts from host OS, including /.oldroot itself */
625 626 627 628 629 630 631 632 633 634
    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)
{
635
    int i;
636

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

647 648
        if (mount(vmDef->fss[i]->src,
                  vmDef->fss[i]->dst,
649 650 651
                  NULL,
                  MS_BIND,
                  NULL) < 0) {
652
            virReportSystemError(errno,
653
                                 _("Failed to mount %s at %s"),
654 655
                                 vmDef->fss[i]->src,
                                 vmDef->fss[i]->dst);
656 657 658 659 660 661
            return -1;
        }
    }

    /* mount /proc */
    if (mount("lxcproc", "/proc", "proc", 0, NULL) < 0) {
662
        virReportSystemError(errno, "%s",
663
                             _("Failed to mount /proc"));
664 665 666 667 668 669
        return -1;
    }

    return 0;
}

670 671
static int lxcContainerSetupMounts(virDomainDefPtr vmDef,
                                   virDomainFSDefPtr root)
672 673 674 675 676 677 678
{
    if (root)
        return lxcContainerSetupPivotRoot(vmDef, root);
    else
        return lxcContainerSetupExtraMounts(vmDef);
}

D
Daniel P. Berrange 已提交
679 680 681 682 683 684 685

/*
 * 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)
686
{
D
Daniel P. Berrange 已提交
687 688 689 690 691 692 693 694 695 696 697 698 699 700
#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) {
701
        lxcError(VIR_ERR_INTERNAL_ERROR,
702
                 _("Failed to remove capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
703 704
        return -1;
    }
705

D
Daniel P. Berrange 已提交
706
    if ((ret = capng_apply(CAPNG_SELECT_BOTH)) < 0) {
707
        lxcError(VIR_ERR_INTERNAL_ERROR,
708
                 _("Failed to apply capabilities: %d"), ret);
D
Daniel P. Berrange 已提交
709
        return -1;
710
    }
D
Daniel P. Berrange 已提交
711

712 713 714 715 716
    /* 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 已提交
717 718 719

#else
    VIR_WARN0(_("libcap-ng support not compiled in, unable to clear capabilities"));
D
Daniel Veillard 已提交
720
#endif
721 722 723 724
    return 0;
}


725
/**
726 727
 * lxcContainerChild:
 * @data: pointer to container arguments
728 729 730 731 732 733 734 735 736
 *
 * 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
 */
737
static int lxcContainerChild( void *data )
738
{
739
    lxc_child_argv_t *argv = data;
740
    virDomainDefPtr vmDef = argv->config;
741
    int ttyfd;
742 743
    char *ttyPath;
    virDomainFSDefPtr root;
744 745

    if (NULL == vmDef) {
746
        lxcError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
747
                 "%s", _("lxcChild() passed invalid vm definition"));
748
        return -1;
749 750
    }

751
    root = virDomainGetRootFilesystem(vmDef);
752

753 754
    if (root) {
        if (virAsprintf(&ttyPath, "%s%s", root->src, argv->ttyPath) < 0) {
755
            virReportOOMError();
756 757 758 759
            return -1;
        }
    } else {
        if (!(ttyPath = strdup(argv->ttyPath))) {
760
            virReportOOMError();
761 762 763 764 765
            return -1;
        }
    }

    ttyfd = open(ttyPath, O_RDWR|O_NOCTTY);
766
    if (ttyfd < 0) {
767
        virReportSystemError(errno,
768
                             _("Failed to open tty %s"),
769
                             ttyPath);
770
        VIR_FREE(ttyPath);
771
        return -1;
772
    }
773
    VIR_FREE(ttyPath);
774

775 776
    if (lxcContainerSetStdio(argv->monitor, ttyfd) < 0) {
        close(ttyfd);
777
        return -1;
778 779
    }
    close(ttyfd);
780

781 782 783
    if (lxcContainerSetupMounts(vmDef, root) < 0)
        return -1;

784
    /* Wait for interface devices to show up */
785 786
    if (lxcContainerWaitForContinue(argv->monitor) < 0)
        return -1;
787

788 789 790
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
                                              argv->veths) < 0)
791
        return -1;
792

793
    /* drop a set of root capabilities */
D
Daniel P. Berrange 已提交
794
    if (lxcContainerDropCapabilities() < 0)
795 796
        return -1;

797
    /* this function will only return if an error occured */
798 799
    return lxcContainerExecInit(vmDef);
}
800

801 802 803 804 805
static int userns_supported(void)
{
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
}

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

    /* allocate a stack for the container */
    if (VIR_ALLOC_N(stack, stacksize) < 0) {
832
        virReportOOMError();
833 834 835 836
        return -1;
    }
    stacktop = stack + stacksize;

837 838
    flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;

839 840
    if (userns_supported()) {
        DEBUG0("Enable user namespaces");
841
        flags |= CLONE_NEWUSER;
842
    }
843

844 845
    if (def->nets != NULL) {
        DEBUG0("Enable network namespaces");
846
        flags |= CLONE_NEWNET;
847
    }
848 849 850

    pid = clone(lxcContainerChild, stacktop, flags, &args);
    VIR_FREE(stack);
851
    DEBUG("clone() completed, new container PID is %d", pid);
852 853

    if (pid < 0) {
854
        virReportSystemError(errno, "%s",
855
                             _("Failed to run clone container"));
856 857 858 859 860 861 862 863 864 865 866 867 868
        return -1;
    }

    return pid;
}

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

int lxcContainerAvailable(int features)
{
869
    int flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|
870 871 872 873 874 875
        CLONE_NEWIPC|SIGCHLD;
    int cpid;
    char *childStack;
    char *stack;
    int childStatus;

876 877 878
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

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

    return 0;
901
}