lxc_container.c 24.1 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 254
        if (virAsprintf(&newname, "eth%d", i) < 0) {
            virReportOOMError();
            rc = -1;
255
            goto error_out;
256
        }
257 258 259

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

        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 282 283 284 285 286 287 288 289 290 291 292 293

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

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)
{
M
Mark McLoughlin 已提交
312
    int rc, 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
    }

L
Laine Stump 已提交
329
    if ((rc = virFileMakePath(oldroot)) != 0) {
330
        virReportSystemError(rc,
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;
    }

L
Laine Stump 已提交
351
    if ((rc = virFileMakePath(newroot)) != 0) {
352
        virReportSystemError(rc,
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 366 367
                             root->src);
        goto err;
    }

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

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

    /* CWD is undefined after pivot_root, so go to / */
383 384 385
    if (chdir("/") < 0)
        goto err;

M
Mark McLoughlin 已提交
386 387 388
    ret = 0;

err:
389 390 391
    VIR_FREE(oldroot);
    VIR_FREE(newroot);

M
Mark McLoughlin 已提交
392
    return ret;
393 394
}

395 396

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

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

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

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

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

    rc = 0;

 cleanup:
449 450
    VIR_FREE(devpts);

451
    return rc;
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
}

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" },
    };
470 471 472 473

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

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

499 500 501 502 503 504 505 506 507
    /* 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;
    }
508

509 510 511 512 513 514
    return 0;
}


static int lxcContainerMountNewFS(virDomainDefPtr vmDef)
{
515
    int i;
516 517

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

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

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

    return 0;
}


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

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

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

584 585 586
    if (mounts)
        qsort(mounts, nmounts, sizeof(mounts[0]),
              lxcContainerChildMountSort);
587 588

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

615 616
    /* Mounts the core /proc, /sys, /dev, /dev/pts filesystems */
    if (lxcContainerMountBasicFS(root) < 0)
617 618
        return -1;

619
    /* Populates device nodes in /dev/ */
620 621 622
    if (lxcContainerPopulateDevices() < 0)
        return -1;

623
    /* Sets up any non-root mounts from guest config */
624 625 626
    if (lxcContainerMountNewFS(vmDef) < 0)
        return -1;

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

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

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

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

    return 0;
}

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

D
Daniel P. Berrange 已提交
682 683 684 685 686 687 688

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

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

715 716 717 718 719
    /* 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 已提交
720 721

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


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

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

754
    root = virDomainGetRootFilesystem(vmDef);
755

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

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

778 779
    if (lxcContainerSetStdio(argv->monitor, ttyfd) < 0) {
        close(ttyfd);
780
        return -1;
781 782
    }
    close(ttyfd);
783

784 785 786
    if (lxcContainerSetupMounts(vmDef, root) < 0)
        return -1;

787
    /* Wait for interface devices to show up */
788 789
    if (lxcContainerWaitForContinue(argv->monitor) < 0)
        return -1;
790

791 792 793
    /* rename and enable interfaces */
    if (lxcContainerRenameAndEnableInterfaces(argv->nveths,
                                              argv->veths) < 0)
794
        return -1;
795

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

800
    /* this function will only return if an error occured */
801 802
    return lxcContainerExecInit(vmDef);
}
803

804 805 806 807 808
static int userns_supported(void)
{
    return lxcContainerAvailable(LXC_CONTAINER_FEATURE_USER) == 0;
}

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

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

840 841
    flags = CLONE_NEWPID|CLONE_NEWNS|CLONE_NEWUTS|CLONE_NEWIPC|SIGCHLD;

842 843
    if (userns_supported()) {
        DEBUG0("Enable user namespaces");
844
        flags |= CLONE_NEWUSER;
845
    }
846

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

    pid = clone(lxcContainerChild, stacktop, flags, &args);
    VIR_FREE(stack);
854
    DEBUG("clone() completed, new container PID is %d", pid);
855 856

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

    return pid;
}

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

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

879 880 881
    if (features & LXC_CONTAINER_FEATURE_USER)
        flags |= CLONE_NEWUSER;

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

    return 0;
904
}