virutil.c 46.4 KB
Newer Older
1
/*
2
 * virutil.c: common, generic utility functions
3
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * Copyright (C) 2006 Daniel P. Berrange
 * Copyright (C) 2006, 2007 Binary Karma
 * Copyright (C) 2006 Shuveb Hussain
 *
 * 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
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22 23
 */

24
#include <config.h>
25

26 27
#include <unistd.h>
#include <fcntl.h>
C
Cole Robinson 已提交
28
#include <poll.h>
29
#include <sys/stat.h>
30 31 32 33 34 35 36

#ifdef MAJOR_IN_MKDEV
# include <sys/mkdev.h>
#elif MAJOR_IN_SYSMACROS
# include <sys/sysmacros.h>
#endif

37
#include <sys/types.h>
E
Eric Blake 已提交
38
#include <termios.h>
39

40
#if WITH_DEVMAPPER
41 42
# include <libdevmapper.h>
#endif
43

44
#include <netdb.h>
45
#ifdef HAVE_GETPWUID_R
46 47
# include <pwd.h>
# include <grp.h>
48
#endif
49
#if WITH_CAPNG
50
# include <cap-ng.h>
51
# include <sys/prctl.h>
52
#endif
53

54
#ifdef WIN32
55 56 57
# ifdef HAVE_WINSOCK2_H
#  include <winsock2.h>
# endif
58 59 60 61
# include <windows.h>
# include <shlobj.h>
#endif

62 63 64 65
#ifdef HAVE_SYS_UN_H
# include <sys/un.h>
#endif

66
#include "c-ctype.h"
E
Eric Blake 已提交
67
#include "mgetgroups.h"
68
#include "virerror.h"
69
#include "virlog.h"
70
#include "virbuffer.h"
71
#include "viralloc.h"
E
Eric Blake 已提交
72
#include "verify.h"
73 74 75 76 77 78
#include "virfile.h"
#include "vircommand.h"
#include "nonblocking.h"
#include "virprocess.h"
#include "virstring.h"
#include "virutil.h"
79

80 81
verify(sizeof(gid_t) <= sizeof(unsigned int) &&
       sizeof(uid_t) <= sizeof(unsigned int));
82

83
#define VIR_FROM_THIS VIR_FROM_NONE
84

85 86
VIR_LOG_INIT("util.util");

87
#ifndef WIN32
88

89 90
int virSetInherit(int fd, bool inherit)
{
91 92
    int fflags;
    if ((fflags = fcntl(fd, F_GETFD)) < 0)
93
        return -1;
94 95 96 97 98
    if (inherit)
        fflags &= ~FD_CLOEXEC;
    else
        fflags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, fflags)) < 0)
99
        return -1;
100 101 102
    return 0;
}

103
#else /* WIN32 */
104

J
Ján Tomko 已提交
105
int virSetInherit(int fd G_GNUC_UNUSED, bool inherit G_GNUC_UNUSED)
106
{
107 108 109 110 111
    /* FIXME: Currently creating child processes is not supported on
     * Win32, so there is no point in failing calls that are only relevant
     * when creating child processes. So just pretend that we changed the
     * inheritance property of the given fd as requested. */
    return 0;
112 113
}

114
#endif /* WIN32 */
115

116 117
int virSetBlocking(int fd, bool blocking)
{
118
    return set_nonblocking_flag(fd, !blocking);
119 120
}

121 122
int virSetNonBlock(int fd)
{
123
    return virSetBlocking(fd, false);
124
}
125

126
int virSetCloseExec(int fd)
127
{
128
    return virSetInherit(fd, false);
129 130
}

131
#ifdef WIN32
J
Ján Tomko 已提交
132
int virSetSockReuseAddr(int fd G_GNUC_UNUSED, bool fatal G_GNUC_UNUSED)
133 134 135 136 137 138 139 140 141 142 143 144 145 146
{
    /*
     * SO_REUSEADDR on Windows is actually akin to SO_REUSEPORT
     * on Linux/BSD. ie it allows 2 apps to listen to the same
     * port at once which is certainly not what we want here.
     *
     * Win32 sockets have Linux/BSD-like SO_REUSEADDR behaviour
     * by default, so we can be a no-op.
     *
     * http://msdn.microsoft.com/en-us/library/windows/desktop/ms740621.aspx
     */
    return 0;
}
#else
147
int virSetSockReuseAddr(int fd, bool fatal)
148 149
{
    int opt = 1;
150 151 152 153 154 155 156 157
    int ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    if (ret < 0 && fatal) {
        virReportSystemError(errno, "%s",
                             _("Unable to set socket reuse addr flag"));
    }

    return ret;
158 159 160
}
#endif

161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
/* Convert C from hexadecimal character to integer.  */
int
virHexToBin(unsigned char c)
{
    switch (c) {
    default: return c - '0';
    case 'a': case 'A': return 10;
    case 'b': case 'B': return 11;
    case 'c': case 'C': return 12;
    case 'd': case 'D': return 13;
    case 'e': case 'E': return 14;
    case 'f': case 'F': return 15;
    }
}

177 178 179 180 181 182 183 184 185 186 187 188 189 190
/* Scale an integer VALUE in-place by an optional case-insensitive
 * SUFFIX, defaulting to SCALE if suffix is NULL or empty (scale is
 * typically 1 or 1024).  Recognized suffixes include 'b' or 'bytes',
 * as well as power-of-two scaling via binary abbreviations ('KiB',
 * 'MiB', ...) or their one-letter counterpart ('k', 'M', ...), and
 * power-of-ten scaling via SI abbreviations ('KB', 'MB', ...).
 * Ensure that the result does not exceed LIMIT.  Return 0 on success,
 * -1 with error message raised on failure.  */
int
virScaleInteger(unsigned long long *value, const char *suffix,
                unsigned long long scale, unsigned long long limit)
{
    if (!suffix || !*suffix) {
        if (!scale) {
191 192
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("invalid scale %llu"), scale);
193 194 195 196 197 198 199 200 201 202 203 204 205 206
            return -1;
        }
        suffix = "";
    } else if (STRCASEEQ(suffix, "b") || STRCASEEQ(suffix, "byte") ||
               STRCASEEQ(suffix, "bytes")) {
        scale = 1;
    } else {
        int base;

        if (!suffix[1] || STRCASEEQ(suffix + 1, "iB")) {
            base = 1024;
        } else if (c_tolower(suffix[1]) == 'b' && !suffix[2]) {
            base = 1000;
        } else {
207
            virReportError(VIR_ERR_INVALID_ARG,
208
                           _("unknown suffix '%s'"), suffix);
209 210 211 212 213 214
            return -1;
        }
        scale = 1;
        switch (c_tolower(*suffix)) {
        case 'e':
            scale *= base;
215
            G_GNUC_FALLTHROUGH;
216 217
        case 'p':
            scale *= base;
218
            G_GNUC_FALLTHROUGH;
219 220
        case 't':
            scale *= base;
221
            G_GNUC_FALLTHROUGH;
222 223
        case 'g':
            scale *= base;
224
            G_GNUC_FALLTHROUGH;
225 226
        case 'm':
            scale *= base;
227
            G_GNUC_FALLTHROUGH;
228 229 230 231
        case 'k':
            scale *= base;
            break;
        default:
232 233
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unknown suffix '%s'"), suffix);
234 235 236 237
            return -1;
        }
    }

G
Guannan Ren 已提交
238
    if (*value && *value > (limit / scale)) {
239 240
        virReportError(VIR_ERR_OVERFLOW, _("value too large: %llu%s"),
                       *value, suffix);
241 242 243 244 245 246
        return -1;
    }
    *value *= scale;
    return 0;
}

E
Eric Blake 已提交
247

248 249 250 251
/**
 * virParseVersionString:
 * @str: const char pointer to the version string
 * @version: unsigned long pointer to output the version number
252 253
 * @allowMissing: true to treat 3 like 3.0.0, false to error out on
 * missing minor or micro
254 255 256 257 258 259 260 261 262 263 264
 *
 * Parse an unsigned version number from a version string. Expecting
 * 'major.minor.micro' format, ignoring an optional suffix.
 *
 * The major, minor and micro numbers are encoded into a single version number:
 *
 *   1000000 * major + 1000 * minor + micro
 *
 * Returns the 0 for success, -1 for error.
 */
int
265 266
virParseVersionString(const char *str, unsigned long *version,
                      bool allowMissing)
267
{
268
    unsigned int major, minor = 0, micro = 0;
269 270
    char *tmp;

271
    if (virStrToLong_ui(str, &tmp, 10, &major) < 0)
272 273
        return -1;

274 275 276
    if (!allowMissing && *tmp != '.')
        return -1;

277
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &minor) < 0)
278 279
        return -1;

280 281 282
    if (!allowMissing && *tmp != '.')
        return -1;

283
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &micro) < 0)
284 285
        return -1;

286 287 288
    if (major > UINT_MAX / 1000000 || minor > 999 || micro > 999)
        return -1;

289 290 291 292 293
    *version = 1000000 * major + 1000 * minor + micro;

    return 0;
}

D
Daniel P. Berrange 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
/**
 * Format @val as a base-10 decimal number, in the
 * buffer @buf of size @buflen. To allocate a suitable
 * sized buffer, the INT_BUFLEN(int) macro should be
 * used
 *
 * Returns pointer to start of the number in @buf
 */
char *
virFormatIntDecimal(char *buf, size_t buflen, int val)
{
    char *p = buf + buflen - 1;
    *p = '\0';
    if (val >= 0) {
        do {
            *--p = '0' + (val % 10);
            val /= 10;
        } while (val != 0);
    } else {
        do {
            *--p = '0' - (val % 10);
            val /= 10;
        } while (val != 0);
        *--p = '-';
    }
    return p;
}


323 324 325 326 327 328 329 330
/**
 * virFormatIntPretty
 *
 * @val: Value in bytes to be shortened
 * @unit: unit to be used
 *
 * Similar to vshPrettyCapacity, but operates on integers and not doubles
 *
331 332 333 334
 * NB: Since using unsigned long long, we are limited to at most a "PiB"
 *     to make pretty. This is because a PiB is 1152921504606846976 bytes,
 *     but that value * 1024 > ULLONG_MAX value 18446744073709551615 bytes.
 *
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
 * Returns shortened value that can be used with @unit.
 */
unsigned long long
virFormatIntPretty(unsigned long long val,
                   const char **unit)
{
    unsigned long long limit = 1024;

    if (val % limit || val == 0) {
        *unit = "B";
        return val;
    }
    limit *= 1024;
    if (val % limit) {
        *unit = "KiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val % limit) {
        *unit = "MiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val % limit) {
        *unit = "GiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
    if (val % limit) {
        *unit = "TiB";
        return val / (limit / 1024);
    }
    limit *= 1024;
368
    *unit = "PiB";
369 370 371 372
    return val / (limit / 1024);
}


373
/* Translates a device name of the form (regex) /^[fhv]d[a-z]+[0-9]*$/
374 375
 * into the corresponding index and partition number
 * (e.g. sda0 => (0,0), hdz2 => (25,2), vdaa12 => (26,12))
376
 * @param name The name of the device
377 378 379
 * @param disk The disk index to be returned
 * @param partition The partition index to be returned
 * @return 0 on success, or -1 on failure
380
 */
381
int virDiskNameParse(const char *name, int *disk, int *partition)
382
{
383
    const char *ptr = NULL;
384
    char *rem;
385
    int idx = 0;
386
    static char const* const drive_prefix[] = {"fd", "hd", "vd", "sd", "xvd", "ubd"};
387
    size_t i;
388

389
    for (i = 0; i < G_N_ELEMENTS(drive_prefix); i++) {
390 391
        if (STRPREFIX(name, drive_prefix[i])) {
            ptr = name + strlen(drive_prefix[i]);
392
            break;
393
        }
394 395
    }

396
    if (!ptr || !c_islower(*ptr))
397 398
        return -1;

D
Daniel Veillard 已提交
399
    for (i = 0; *ptr; i++) {
J
Jim Meyering 已提交
400
        if (!c_islower(*ptr))
401
            break;
402

403
        idx = (idx + (i < 1 ? 0 : 1)) * 26;
404 405 406 407
        idx += *ptr - 'a';
        ptr++;
    }

408 409 410 411 412
    /* Count the trailing digits.  */
    size_t n_digits = strspn(ptr, "0123456789");
    if (ptr[n_digits] != '\0')
        return -1;

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    *disk = idx;

    /* Convert trailing digits into our partition index */
    if (partition) {
        *partition = 0;

        /* Shouldn't start by zero */
        if (n_digits > 1 && *ptr == '0')
            return -1;

        if (n_digits && virStrToLong_i(ptr, &rem, 10, partition) < 0)
            return -1;
    }

    return 0;
}

/* Translates a device name of the form (regex) /^[fhv]d[a-z]+[0-9]*$/
 * into the corresponding index (e.g. sda => 0, hdz => 25, vdaa => 26)
 * Note that any trailing string of digits is simply ignored.
 * @param name The name of the device
 * @return name's index, or -1 on failure
 */
int virDiskNameToIndex(const char *name)
{
    int idx;

440
    if (virDiskNameParse(name, &idx, NULL) < 0)
441 442
        idx = -1;

443 444
    return idx;
}
G
Guido Günther 已提交
445

446 447 448
char *virIndexToDiskName(int idx, const char *prefix)
{
    char *name = NULL;
449 450 451
    size_t i;
    int ctr;
    int offset;
452 453

    if (idx < 0) {
454 455
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Disk index %d is negative"), idx);
456 457 458
        return NULL;
    }

459
    for (i = 0, ctr = idx; ctr >= 0; ++i, ctr = ctr / 26 - 1) { }
460 461 462

    offset = strlen(prefix);

463
    if (VIR_ALLOC_N(name, offset + i + 1))
464 465 466 467 468
        return NULL;

    strcpy(name, prefix);
    name[offset + i] = '\0';

469
    for (i = i - 1, ctr = idx; ctr >= 0; --i, ctr = ctr / 26 - 1)
470
        name[offset + i] = 'a' + (ctr % 26);
471 472 473 474

    return name;
}

475
#ifndef AI_CANONIDN
476
# define AI_CANONIDN 0
477 478
#endif

479 480 481 482
#ifndef HOST_NAME_MAX
# define HOST_NAME_MAX 256
#endif

C
Chris Lalancette 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
/* Who knew getting a hostname could be so delicate.  In Linux (and Unices
 * in general), many things depend on "hostname" returning a value that will
 * resolve one way or another.  In the modern world where networks frequently
 * come and go this is often being hard-coded to resolve to "localhost".  If
 * it *doesn't* resolve to localhost, then we would prefer to have the FQDN.
 * That leads us to 3 possibilities:
 *
 * 1)  gethostname() returns an FQDN (not localhost) - we return the string
 *     as-is, it's all of the information we want
 * 2)  gethostname() returns "localhost" - we return localhost; doing further
 *     work to try to resolve it is pointless
 * 3)  gethostname() returns a shortened hostname - in this case, we want to
 *     try to resolve this to a fully-qualified name.  Therefore we pass it
 *     to getaddrinfo().  There are two possible responses:
 *     a)  getaddrinfo() resolves to a FQDN - return the FQDN
498
 *     b)  getaddrinfo() fails or resolves to localhost - in this case, the
499 500 501
 *         data we got from gethostname() is actually more useful than what
 *         we got from getaddrinfo().  Return the value from gethostname()
 *         and hope for the best.
C
Chris Lalancette 已提交
502
 */
503 504
static char *
virGetHostnameImpl(bool quiet)
505 506
{
    int r;
507
    char hostname[HOST_NAME_MAX+1], *result = NULL;
C
Chris Lalancette 已提交
508
    struct addrinfo hints, *info;
509

510
    r = gethostname(hostname, sizeof(hostname));
511
    if (r == -1) {
512 513 514
        if (!quiet)
            virReportSystemError(errno,
                                 "%s", _("failed to determine host name"));
515
        return NULL;
516
    }
517 518
    NUL_TERMINATE(hostname);

C
Chris Lalancette 已提交
519 520 521 522 523 524 525
    if (STRPREFIX(hostname, "localhost") || strchr(hostname, '.')) {
        /* in this case, gethostname returned localhost (meaning we can't
         * do any further canonicalization), or it returned an FQDN (and
         * we don't need to do any further canonicalization).  Return the
         * string as-is; it's up to callers to check whether "localhost"
         * is allowed.
         */
526
        result = g_strdup(hostname);
527
        goto cleanup;
C
Chris Lalancette 已提交
528 529 530 531 532 533
    }

    /* otherwise, it's a shortened, non-localhost, hostname.  Attempt to
     * canonicalize the hostname by running it through getaddrinfo
     */

534 535 536 537
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_CANONNAME|AI_CANONIDN;
    hints.ai_family = AF_UNSPEC;
    r = getaddrinfo(hostname, NULL, &hints, &info);
538
    if (r != 0) {
539 540 541
        if (!quiet)
            VIR_WARN("getaddrinfo failed for '%s': %s",
                     hostname, gai_strerror(r));
542
        result = g_strdup(hostname);
543
        goto cleanup;
544
    }
545

546
    /* Tell static analyzers about getaddrinfo semantics.  */
547
    sa_assert(info);
548

C
Chris Lalancette 已提交
549 550 551 552 553 554
    if (info->ai_canonname == NULL ||
        STRPREFIX(info->ai_canonname, "localhost"))
        /* in this case, we tried to canonicalize and we ended up back with
         * localhost.  Ignore the canonicalized name and just return the
         * original hostname
         */
555
        result = g_strdup(hostname);
C
Chris Lalancette 已提交
556 557
    else
        /* Caller frees this string. */
558
        result = g_strdup(info->ai_canonname);
559

C
Chris Lalancette 已提交
560
    freeaddrinfo(info);
561

562
 cleanup:
563 564
    if (!result)
        virReportOOMError();
565 566 567
    return result;
}

D
Dan Walsh 已提交
568

569 570 571 572 573 574 575 576 577 578 579 580 581 582
char *
virGetHostname(void)
{
    return virGetHostnameImpl(false);
}


char *
virGetHostnameQuiet(void)
{
    return virGetHostnameImpl(true);
}


D
Dan Walsh 已提交
583 584 585 586 587 588 589
char *
virGetUserDirectory(void)
{
    return virGetUserDirectoryByUID(geteuid());
}


590
#ifdef HAVE_GETPWUID_R
E
Eric Blake 已提交
591
/* Look up fields from the user database for the given user.  On
592 593
 * error, set errno, report the error if not instructed otherwise via @quiet,
 * and return -1.  */
E
Eric Blake 已提交
594
static int
595
virGetUserEnt(uid_t uid, char **name, gid_t *group, char **dir, char **shell, bool quiet)
596 597 598
{
    char *strbuf;
    struct passwd pwbuf;
599
    struct passwd *pw = NULL;
600 601
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
602
    int rc;
E
Eric Blake 已提交
603 604 605 606 607 608
    int ret = -1;

    if (name)
        *name = NULL;
    if (dir)
        *dir = NULL;
609 610
    if (shell)
        *shell = NULL;
611

612 613 614
    /* sysconf is a hint; if it fails, fall back to a reasonable size */
    if (val < 0)
        strbuflen = 1024;
615

616
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
E
Eric Blake 已提交
617
        return -1;
618

619 620 621 622 623 624 625
    /*
     * From the manpage (terrifying but true):
     *
     * ERRORS
     *  0 or ENOENT or ESRCH or EBADF or EPERM or ...
     *        The given name or uid was not found.
     */
626
    while ((rc = getpwuid_r(uid, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
627
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
E
Eric Blake 已提交
628
            goto cleanup;
629
    }
630

631
    if (rc != 0) {
632 633 634
        if (quiet)
            goto cleanup;

635
        virReportSystemError(rc,
E
Eric Blake 已提交
636 637
                             _("Failed to find user record for uid '%u'"),
                             (unsigned int) uid);
E
Eric Blake 已提交
638
        goto cleanup;
639
    } else if (pw == NULL) {
640 641 642
        if (quiet)
            goto cleanup;

643 644 645 646
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Failed to find user record for uid '%u'"),
                       (unsigned int) uid);
        goto cleanup;
E
Eric Blake 已提交
647 648
    }

649 650
    if (name)
        *name = g_strdup(pw->pw_name);
E
Eric Blake 已提交
651 652
    if (group)
        *group = pw->pw_gid;
653 654 655 656
    if (dir)
        *dir = g_strdup(pw->pw_dir);
    if (shell)
        *shell = g_strdup(pw->pw_shell);
657

E
Eric Blake 已提交
658
    ret = 0;
659
 cleanup:
660 661 662 663 664 665 666 667
    if (ret < 0) {
        if (name)
            VIR_FREE(*name);
        if (dir)
            VIR_FREE(*dir);
        if (shell)
            VIR_FREE(*shell);
    }
668 669 670
    VIR_FREE(strbuf);
    return ret;
}
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685
static char *virGetGroupEnt(gid_t gid)
{
    char *strbuf;
    char *ret;
    struct group grbuf;
    struct group *gr = NULL;
    long val = sysconf(_SC_GETGR_R_SIZE_MAX);
    size_t strbuflen = val;
    int rc;

    /* sysconf is a hint; if it fails, fall back to a reasonable size */
    if (val < 0)
        strbuflen = 1024;

686
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
        return NULL;

    /*
     * From the manpage (terrifying but true):
     *
     * ERRORS
     *  0 or ENOENT or ESRCH or EBADF or EPERM or ...
     *        The given name or gid was not found.
     */
    while ((rc = getgrgid_r(gid, &grbuf, strbuf, strbuflen, &gr)) == ERANGE) {
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0) {
            VIR_FREE(strbuf);
            return NULL;
        }
    }
    if (rc != 0 || gr == NULL) {
703 704 705 706 707 708 709 710 711 712
        if (rc != 0) {
            virReportSystemError(rc,
                                 _("Failed to find group record for gid '%u'"),
                                 (unsigned int) gid);
        } else {
            virReportError(VIR_ERR_SYSTEM_ERROR,
                           _("Failed to find group record for gid '%u'"),
                           (unsigned int) gid);
        }

713 714 715 716
        VIR_FREE(strbuf);
        return NULL;
    }

717
    ret = g_strdup(gr->gr_name);
718 719 720 721
    VIR_FREE(strbuf);
    return ret;
}

D
Dan Walsh 已提交
722 723 724

char *
virGetUserDirectoryByUID(uid_t uid)
725
{
E
Eric Blake 已提交
726
    char *ret;
727
    virGetUserEnt(uid, NULL, NULL, &ret, NULL, false);
728 729 730 731 732 733 734
    return ret;
}


char *virGetUserShell(uid_t uid)
{
    char *ret;
735
    virGetUserEnt(uid, NULL, NULL, NULL, &ret, false);
E
Eric Blake 已提交
736
    return ret;
737 738
}

D
Dan Walsh 已提交
739

740
static char *virGetXDGDirectory(const char *xdgenvname, const char *xdgdefdir)
741
{
742
    const char *path = getenv(xdgenvname);
743
    char *ret = NULL;
744
    char *home = NULL;
745 746

    if (path && path[0]) {
747
        ret = g_strdup_printf("%s/libvirt", path);
748
    } else {
E
Eric Blake 已提交
749 750
        home = virGetUserDirectory();
        if (home)
751
            ret = g_strdup_printf("%s/%s/libvirt", home, xdgdefdir);
752 753 754 755 756 757
    }

    VIR_FREE(home);
    return ret;
}

758
char *virGetUserConfigDirectory(void)
759
{
760
    return virGetXDGDirectory("XDG_CONFIG_HOME", ".config");
761 762
}

763
char *virGetUserCacheDirectory(void)
764
{
765
    return virGetXDGDirectory("XDG_CACHE_HOME", ".cache");
766 767
}

768
char *virGetUserRuntimeDirectory(void)
769
{
770
    const char *path = getenv("XDG_RUNTIME_DIR");
771 772

    if (!path || !path[0]) {
773
        return virGetUserCacheDirectory();
774 775 776
    } else {
        char *ret;

777
        ret = g_strdup_printf("%s/libvirt", path);
778 779 780 781
        return ret;
    }
}

782
char *virGetUserName(uid_t uid)
783
{
E
Eric Blake 已提交
784
    char *ret;
785
    virGetUserEnt(uid, &ret, NULL, NULL, NULL, false);
E
Eric Blake 已提交
786
    return ret;
787 788
}

789 790 791 792 793
char *virGetGroupName(gid_t gid)
{
    return virGetGroupEnt(gid);
}

794 795
/* Search in the password database for a user id that matches the user name
 * `name`. Returns 0 on success, -1 on failure or 1 if name cannot be found.
796 797
 *
 * Warns if @missing_ok is false
798 799
 */
static int
800
virGetUserIDByName(const char *name, uid_t *uid, bool missing_ok)
801
{
802
    char *strbuf = NULL;
803 804
    struct passwd pwbuf;
    struct passwd *pw = NULL;
805 806
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
807
    int rc;
808
    int ret = -1;
809

810 811 812
    /* sysconf is a hint; if it fails, fall back to a reasonable size */
    if (val < 0)
        strbuflen = 1024;
813

814
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
815
        goto cleanup;
816

817
    while ((rc = getpwnam_r(name, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
818
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
819
            goto cleanup;
820
    }
821 822

    if (!pw) {
823
        if (rc != 0 && !missing_ok) {
824 825 826 827
            char buf[1024];
            /* log the possible error from getpwnam_r. Unfortunately error
             * reporting from this function is bad and we can't really
             * rely on it, so we just report that the user wasn't found */
828
            VIR_WARN("User record for user '%s' was not found: %s",
829 830 831
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

832 833
        ret = 1;
        goto cleanup;
834 835
    }

836 837
    if (uid)
        *uid = pw->pw_uid;
838
    ret = 0;
839

840
 cleanup:
841 842
    VIR_FREE(strbuf);

843
    return ret;
844 845
}

846 847 848 849 850 851 852 853 854 855 856 857 858 859
/* Try to match a user id based on `user`. The default behavior is to parse
 * `user` first as a user name and then as a user id. However if `user`
 * contains a leading '+', the rest of the string is always parsed as a uid.
 *
 * Returns 0 on success and -1 otherwise.
 */
int
virGetUserID(const char *user, uid_t *uid)
{
    unsigned int uint_uid;

    if (*user == '+') {
        user++;
    } else {
860
        int rc = virGetUserIDByName(user, uid, false);
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
        if (rc <= 0)
            return rc;
    }

    if (virStrToLong_ui(user, NULL, 10, &uint_uid) < 0 ||
        ((uid_t) uint_uid) != uint_uid) {
        virReportError(VIR_ERR_INVALID_ARG, _("Failed to parse user '%s'"),
                       user);
        return -1;
    }

    *uid = uint_uid;

    return 0;
}
876

877 878
/* Search in the group database for a group id that matches the group name
 * `name`. Returns 0 on success, -1 on failure or 1 if name cannot be found.
879 880
 *
 * Warns if @missing_ok is false
881 882
 */
static int
883
virGetGroupIDByName(const char *name, gid_t *gid, bool missing_ok)
884
{
885
    char *strbuf = NULL;
886 887
    struct group grbuf;
    struct group *gr = NULL;
888 889
    long val = sysconf(_SC_GETGR_R_SIZE_MAX);
    size_t strbuflen = val;
890
    int rc;
891
    int ret = -1;
892

893 894 895
    /* sysconf is a hint; if it fails, fall back to a reasonable size */
    if (val < 0)
        strbuflen = 1024;
896

897
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
898
        goto cleanup;
899

900
    while ((rc = getgrnam_r(name, &grbuf, strbuf, strbuflen, &gr)) == ERANGE) {
901
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
902
            goto cleanup;
903
    }
904 905

    if (!gr) {
906
        if (rc != 0 && !missing_ok) {
907 908 909 910
            char buf[1024];
            /* log the possible error from getgrnam_r. Unfortunately error
             * reporting from this function is bad and we can't really
             * rely on it, so we just report that the user wasn't found */
911
            VIR_WARN("Group record for user '%s' was not found: %s",
912 913 914
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

915 916
        ret = 1;
        goto cleanup;
917 918
    }

919 920
    if (gid)
        *gid = gr->gr_gid;
921
    ret = 0;
922

923
 cleanup:
924 925
    VIR_FREE(strbuf);

926
    return ret;
927
}
928

929 930 931 932 933 934 935 936 937 938 939 940 941 942
/* Try to match a group id based on `group`. The default behavior is to parse
 * `group` first as a group name and then as a group id. However if `group`
 * contains a leading '+', the rest of the string is always parsed as a guid.
 *
 * Returns 0 on success and -1 otherwise.
 */
int
virGetGroupID(const char *group, gid_t *gid)
{
    unsigned int uint_gid;

    if (*group == '+') {
        group++;
    } else {
943
        int rc = virGetGroupIDByName(group, gid, false);
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
        if (rc <= 0)
            return rc;
    }

    if (virStrToLong_ui(group, NULL, 10, &uint_gid) < 0 ||
        ((gid_t) uint_gid) != uint_gid) {
        virReportError(VIR_ERR_INVALID_ARG, _("Failed to parse group '%s'"),
                       group);
        return -1;
    }

    *gid = uint_gid;

    return 0;
}
L
Laine Stump 已提交
959

960 961 962
/* Silently checks if User @name exists.
 * Returns if the user exists and fallbacks to false on error.
 */
963
bool
964 965 966 967 968 969 970 971
virDoesUserExist(const char *name)
{
    return virGetUserIDByName(name, NULL, true) == 0;
}

/* Silently checks if Group @name exists.
 * Returns if the group exists and fallbacks to false on error.
 */
972
bool
973 974 975 976 977
virDoesGroupExist(const char *name)
{
    return virGetGroupIDByName(name, NULL, true) == 0;
}

E
Eric Blake 已提交
978

979 980
/* Compute the list of primary and supplementary groups associated
 * with @uid, and including @gid in the list (unless it is -1),
981 982 983 984 985 986
 * storing a malloc'd result into @list. If uid is -1 or doesn't exist in the
 * system database querying of the supplementary groups is skipped.
 *
 * Returns the size of the list on success, or -1 on failure with error
 * reported and errno set. May not be called between fork and exec.
 * */
E
Eric Blake 已提交
987 988 989
int
virGetGroupList(uid_t uid, gid_t gid, gid_t **list)
{
990
    int ret = 0;
E
Eric Blake 已提交
991
    char *user = NULL;
992
    gid_t primary;
E
Eric Blake 已提交
993 994 995

    *list = NULL;

996 997 998 999 1000 1001 1002 1003 1004
    /* invalid users have no supplementary groups */
    if (uid != (uid_t)-1 &&
        virGetUserEnt(uid, &user, &primary, NULL, NULL, true) >= 0) {
        if ((ret = mgetgroups(user, primary, list)) < 0) {
            virReportSystemError(errno,
                                 _("cannot get group list for '%s'"), user);
            ret = -1;
            goto cleanup;
        }
1005 1006 1007
    }

    if (gid != (gid_t)-1) {
E
Eric Blake 已提交
1008
        size_t i;
1009

E
Eric Blake 已提交
1010
        for (i = 0; i < ret; i++) {
1011 1012 1013
            if ((*list)[i] == gid)
                goto cleanup;
        }
E
Eric Blake 已提交
1014
        if (VIR_APPEND_ELEMENT(*list, i, gid) < 0) {
1015 1016 1017 1018
            ret = -1;
            VIR_FREE(*list);
            goto cleanup;
        } else {
E
Eric Blake 已提交
1019
            ret = i;
1020 1021 1022
        }
    }

1023
 cleanup:
E
Eric Blake 已提交
1024 1025 1026 1027 1028
    VIR_FREE(user);
    return ret;
}


1029 1030 1031 1032
/* Set the real and effective uid and gid to the given values, as well
 * as all the supplementary groups, so that the process has all the
 * assumed group membership of that uid. Return 0 on success, -1 on
 * failure (the original system error remains in errno).
L
Laine Stump 已提交
1033 1034
 */
int
J
Ján Tomko 已提交
1035 1036
virSetUIDGID(uid_t uid, gid_t gid, gid_t *groups G_GNUC_UNUSED,
             int ngroups G_GNUC_UNUSED)
L
Laine Stump 已提交
1037
{
1038 1039 1040 1041 1042
    if (gid != (gid_t)-1 && setregid(gid, gid) < 0) {
        virReportSystemError(errno,
                             _("cannot change to '%u' group"),
                             (unsigned int) gid);
        return -1;
L
Laine Stump 已提交
1043 1044
    }

1045
# if HAVE_SETGROUPS
1046
    if (gid != (gid_t)-1 && setgroups(ngroups, groups) < 0) {
1047 1048 1049 1050
        virReportSystemError(errno, "%s",
                             _("cannot set supplemental groups"));
        return -1;
    }
L
Laine Stump 已提交
1051
# endif
1052 1053 1054 1055 1056 1057

    if (uid != (uid_t)-1 && setreuid(uid, uid) < 0) {
        virReportSystemError(errno,
                             _("cannot change to uid to '%u'"),
                             (unsigned int) uid);
        return -1;
L
Laine Stump 已提交
1058
    }
1059

L
Laine Stump 已提交
1060 1061 1062
    return 0;
}

1063 1064
#else /* ! HAVE_GETPWUID_R */

E
Eric Blake 已提交
1065
int
J
Ján Tomko 已提交
1066
virGetGroupList(uid_t uid G_GNUC_UNUSED, gid_t gid G_GNUC_UNUSED,
E
Eric Blake 已提交
1067 1068 1069 1070 1071 1072
                gid_t **list)
{
    *list = NULL;
    return 0;
}

1073
bool
J
Ján Tomko 已提交
1074
virDoesUserExist(const char *name G_GNUC_UNUSED)
1075
{
1076
    return false;
1077 1078
}

1079
bool
J
Ján Tomko 已提交
1080
virDoesGroupExist(const char *name G_GNUC_UNUSED)
1081
{
1082
    return false;
1083 1084
}

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
# ifdef WIN32
/* These methods are adapted from GLib2 under terms of LGPLv2+ */
static int
virGetWin32SpecialFolder(int csidl, char **path)
{
    char buf[MAX_PATH+1];
    LPITEMIDLIST pidl = NULL;
    int ret = 0;

    *path = NULL;

    if (SHGetSpecialFolderLocation(NULL, csidl, &pidl) == S_OK) {
1097 1098
        if (SHGetPathFromIDList(pidl, buf))
            *path = g_strdup(buf);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        CoTaskMemFree(pidl);
    }
    return ret;
}

static int
virGetWin32DirectoryRoot(char **path)
{
    char windowsdir[MAX_PATH];

    *path = NULL;

1111
    if (GetWindowsDirectory(windowsdir, G_N_ELEMENTS(windowsdir))) {
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        const char *tmp;
        /* Usually X:\Windows, but in terminal server environments
         * might be an UNC path, AFAIK.
         */
        tmp = virFileSkipRoot(windowsdir);
        if (VIR_FILE_IS_DIR_SEPARATOR(tmp[-1]) &&
            tmp[-2] != ':')
            tmp--;

        windowsdir[tmp - windowsdir] = '\0';
    } else {
        strcpy(windowsdir, "C:\\");
    }

1126 1127
    *path = g_strdup(windowsdir);
    return 0;
1128 1129 1130 1131 1132
}



char *
J
Ján Tomko 已提交
1133
virGetUserDirectoryByUID(uid_t uid G_GNUC_UNUSED)
1134
{
D
Dan Walsh 已提交
1135 1136 1137
    /* Since Windows lacks setuid binaries, and since we already fake
     * geteuid(), we can safely assume that this is only called when
     * querying about the current user */
1138 1139 1140
    const char *dir;
    char *ret;

1141
    dir = getenv("HOME");
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

    /* Only believe HOME if it is an absolute path and exists */
    if (dir) {
        if (!virFileIsAbsPath(dir) ||
            !virFileExists(dir))
            dir = NULL;
    }

    /* In case HOME is Unix-style (it happens), convert it to
     * Windows style.
     */
    if (dir) {
        char *p;
1155
        while ((p = strchr(dir, '/')) != NULL)
1156 1157 1158 1159 1160
            *p = '\\';
    }

    if (!dir)
        /* USERPROFILE is probably the closest equivalent to $HOME? */
1161
        dir = getenv("USERPROFILE");
1162

1163
    ret = g_strdup(dir);
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    if (!ret &&
        virGetWin32SpecialFolder(CSIDL_PROFILE, &ret) < 0)
        return NULL;

    if (!ret &&
        virGetWin32DirectoryRoot(&ret) < 0)
        return NULL;

    if (!ret) {
1174 1175
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine home directory"));
1176 1177 1178 1179 1180 1181
        return NULL;
    }

    return ret;
}

1182
char *
J
Ján Tomko 已提交
1183
virGetUserShell(uid_t uid G_GNUC_UNUSED)
1184 1185 1186 1187 1188 1189 1190
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserShell is not available"));

    return NULL;
}

1191 1192 1193 1194 1195 1196
char *
virGetUserConfigDirectory(void)
{
    char *ret;
    if (virGetWin32SpecialFolder(CSIDL_LOCAL_APPDATA, &ret) < 0)
        return NULL;
1197

1198
    if (!ret) {
1199 1200
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        return NULL;
    }
    return ret;
}

char *
virGetUserCacheDirectory(void)
{
    char *ret;
    if (virGetWin32SpecialFolder(CSIDL_INTERNET_CACHE, &ret) < 0)
        return NULL;

    if (!ret) {
1214 1215
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        return NULL;
    }
    return ret;
}

char *
virGetUserRuntimeDirectory(void)
{
    return virGetUserCacheDirectory();
}
E
Eric Blake 已提交
1226

1227
# else /* !HAVE_GETPWUID_R && !WIN32 */
1228
char *
J
Ján Tomko 已提交
1229
virGetUserDirectoryByUID(uid_t uid G_GNUC_UNUSED)
1230
{
1231 1232
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserDirectory is not available"));
1233 1234 1235 1236

    return NULL;
}

1237
char *
J
Ján Tomko 已提交
1238
virGetUserShell(uid_t uid G_GNUC_UNUSED)
1239 1240 1241 1242 1243 1244 1245
{
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserShell is not available"));

    return NULL;
}

1246 1247 1248
char *
virGetUserConfigDirectory(void)
{
1249 1250
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserConfigDirectory is not available"));
1251 1252 1253 1254 1255 1256 1257

    return NULL;
}

char *
virGetUserCacheDirectory(void)
{
1258 1259
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserCacheDirectory is not available"));
1260 1261 1262 1263 1264 1265 1266

    return NULL;
}

char *
virGetUserRuntimeDirectory(void)
{
1267 1268
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserRuntimeDirectory is not available"));
1269 1270 1271 1272 1273

    return NULL;
}
# endif /* ! HAVE_GETPWUID_R && ! WIN32 */

1274
char *
J
Ján Tomko 已提交
1275
virGetUserName(uid_t uid G_GNUC_UNUSED)
1276
{
1277 1278
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserName is not available"));
1279 1280 1281 1282

    return NULL;
}

J
Ján Tomko 已提交
1283 1284
int virGetUserID(const char *name G_GNUC_UNUSED,
                 uid_t *uid G_GNUC_UNUSED)
1285
{
1286 1287
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserID is not available"));
1288

1289
    return -1;
1290 1291 1292
}


J
Ján Tomko 已提交
1293 1294
int virGetGroupID(const char *name G_GNUC_UNUSED,
                  gid_t *gid G_GNUC_UNUSED)
1295
{
1296 1297
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupID is not available"));
1298

1299
    return -1;
1300
}
L
Laine Stump 已提交
1301 1302

int
J
Ján Tomko 已提交
1303 1304 1305 1306
virSetUIDGID(uid_t uid G_GNUC_UNUSED,
             gid_t gid G_GNUC_UNUSED,
             gid_t *groups G_GNUC_UNUSED,
             int ngroups G_GNUC_UNUSED)
L
Laine Stump 已提交
1307
{
1308 1309
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virSetUIDGID is not available"));
L
Laine Stump 已提交
1310 1311
    return -1;
}
1312 1313

char *
J
Ján Tomko 已提交
1314
virGetGroupName(gid_t gid G_GNUC_UNUSED)
1315
{
1316 1317
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupName is not available"));
1318 1319 1320

    return NULL;
}
1321
#endif /* HAVE_GETPWUID_R */
1322

1323 1324 1325 1326 1327 1328 1329
#if WITH_CAPNG
/* Set the real and effective uid and gid to the given values, while
 * maintaining the capabilities indicated by bits in @capBits. Return
 * 0 on success, -1 on failure (the original system error remains in
 * errno).
 */
int
1330 1331
virSetUIDGIDWithCaps(uid_t uid, gid_t gid, gid_t *groups, int ngroups,
                     unsigned long long capBits, bool clearExistingCaps)
1332
{
1333
    size_t i;
1334
    int capng_ret;
1335 1336
    bool need_setgid = false;
    bool need_setuid = false;
1337
    bool need_setpcap = false;
1338
    const char *capstr = NULL;
1339

1340 1341 1342 1343
    /* First drop all caps (unless the requested uid is "unchanged" or
     * root and clearExistingCaps wasn't requested), then add back
     * those in capBits + the extra ones we need to change uid/gid and
     * change the capabilities bounding set.
1344 1345
     */

1346
    if (clearExistingCaps || (uid != (uid_t)-1 && uid != 0))
1347
        capng_clear(CAPNG_SELECT_BOTH);
1348

1349
    for (i = 0; i <= CAP_LAST_CAP; i++) {
1350 1351
        capstr = capng_capability_to_name(i);

1352
        if (capBits & (1ULL << i)) {
1353 1354 1355
            capng_update(CAPNG_ADD,
                         CAPNG_EFFECTIVE|CAPNG_INHERITABLE|
                         CAPNG_PERMITTED|CAPNG_BOUNDING_SET,
1356
                         i);
1357 1358

            VIR_DEBUG("Added '%s' to child capabilities' set", capstr);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        }
    }

    if (gid != (gid_t)-1 &&
        !capng_have_capability(CAPNG_EFFECTIVE, CAP_SETGID)) {
        need_setgid = true;
        capng_update(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETGID);
    }
    if (uid != (uid_t)-1 &&
        !capng_have_capability(CAPNG_EFFECTIVE, CAP_SETUID)) {
        need_setuid = true;
        capng_update(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETUID);
    }
# ifdef PR_CAPBSET_DROP
    /* If newer kernel, we need also need setpcap to change the bounding set */
    if ((capBits || need_setgid || need_setuid) &&
        !capng_have_capability(CAPNG_EFFECTIVE, CAP_SETPCAP)) {
        need_setpcap = true;
    }
    if (need_setpcap)
        capng_update(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETPCAP);
# endif

    /* Tell system we want to keep caps across uid change */
1383
    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
1384 1385
        virReportSystemError(errno, "%s",
                             _("prctl failed to set KEEPCAPS"));
1386
        return -1;
1387 1388 1389
    }

    /* Change to the temp capabilities */
1390
    if ((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0) {
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
        /* Failed.  If we are running unprivileged, and the arguments make sense
         * for this scenario, assume we're starting some kind of setuid helper:
         * do not set any of capBits in the permitted or effective sets, and let
         * the program get them on its own.
         *
         * (Too bad we cannot restrict the bounding set to the capabilities we
         * would like the helper to have!).
         */
        if (getuid() > 0 && clearExistingCaps && !need_setuid && !need_setgid) {
            capng_clear(CAPNG_SELECT_CAPS);
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot apply process capabilities %d"), capng_ret);
1404
            return -1;
1405
        }
1406 1407
    }

1408
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0)
1409
        return -1;
1410 1411

    /* Tell it we are done keeping capabilities */
1412
    if (prctl(PR_SET_KEEPCAPS, 0, 0, 0, 0)) {
1413 1414
        virReportSystemError(errno, "%s",
                             _("prctl failed to reset KEEPCAPS"));
1415
        return -1;
1416 1417
    }

1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
# ifdef PR_CAP_AMBIENT
    /* we couldn't do this in the loop earlier above, because the capabilities
     * were not applied yet, since in order to add a capability into the AMBIENT
     * set, it has to be present in both the PERMITTED and INHERITABLE sets
     * (capabilities(7))
     */
    for (i = 0; i <= CAP_LAST_CAP; i++) {
        capstr = capng_capability_to_name(i);

        if (capBits & (1ULL << i)) {
            if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0) < 0) {
                virReportSystemError(errno,
                                     _("prctl failed to enable '%s' in the "
                                       "AMBIENT set"),
                                     capstr);
1433
                return -1;
1434 1435 1436 1437 1438
            }
        }
    }
# endif

1439 1440 1441 1442 1443 1444
    /* Set bounding set while we have CAP_SETPCAP.  Unfortunately we cannot
     * do this if we failed to get the capability above, so ignore the
     * return value.
     */
    capng_apply(CAPNG_SELECT_BOUNDS);

1445 1446 1447 1448 1449 1450 1451 1452 1453
    /* Drop the caps that allow setuid/gid (unless they were requested) */
    if (need_setgid)
        capng_update(CAPNG_DROP, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETGID);
    if (need_setuid)
        capng_update(CAPNG_DROP, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETUID);
    /* Throw away CAP_SETPCAP so no more changes */
    if (need_setpcap)
        capng_update(CAPNG_DROP, CAPNG_EFFECTIVE|CAPNG_PERMITTED, CAP_SETPCAP);

1454
    if (((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0)) {
1455 1456
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot apply process capabilities %d"), capng_ret);
1457
        return -1;
1458 1459
    }

1460
    return 0;
1461 1462 1463 1464 1465 1466 1467 1468 1469
}

#else
/*
 * On platforms without libcapng, the capabilities setting is treated
 * as a NOP.
 */

int
1470
virSetUIDGIDWithCaps(uid_t uid, gid_t gid, gid_t *groups, int ngroups,
J
Ján Tomko 已提交
1471 1472
                     unsigned long long capBits G_GNUC_UNUSED,
                     bool clearExistingCaps G_GNUC_UNUSED)
1473
{
1474
    return virSetUIDGID(uid, gid, groups, ngroups);
1475 1476 1477
}
#endif

1478

J
John Ferlan 已提交
1479
void virWaitForDevices(void)
D
Daniel P. Berrange 已提交
1480
{
J
Ján Tomko 已提交
1481
    g_autoptr(virCommand) cmd = NULL;
1482
    g_autofree char *udev = NULL;
D
Daniel P. Berrange 已提交
1483 1484
    int exitstatus;

1485 1486 1487 1488
    if (!(udev = virFindFileInPath(UDEVADM)))
        return;

    if (!(cmd = virCommandNewArgList(udev, "settle", NULL)))
D
Daniel P. Berrange 已提交
1489 1490 1491 1492 1493 1494
        return;

    /*
     * NOTE: we ignore errors here; this is just to make sure that any device
     * nodes that are being created finish before we try to scan them.
     */
1495
    ignore_value(virCommandRun(cmd, &exitstatus));
D
Daniel P. Berrange 已提交
1496
}
1497

1498
#if WITH_DEVMAPPER
1499
bool
1500
virIsDevMapperDevice(const char *dev_name)
1501 1502 1503
{
    struct stat buf;

1504
    if (!stat(dev_name, &buf) &&
1505 1506 1507 1508 1509 1510
        S_ISBLK(buf.st_mode) &&
        dm_is_dm_major(major(buf.st_rdev)))
            return true;

    return false;
}
1511
#else
J
Ján Tomko 已提交
1512
bool virIsDevMapperDevice(const char *dev_name G_GNUC_UNUSED)
1513 1514 1515 1516
{
    return false;
}
#endif
O
Osier Yang 已提交
1517 1518

bool
1519 1520
virValidateWWN(const char *wwn)
{
1521
    size_t i;
1522
    const char *p = wwn;
O
Osier Yang 已提交
1523

1524
    if (STRPREFIX(wwn, "0x"))
1525 1526 1527 1528
        p += 2;

    for (i = 0; p[i]; i++) {
        if (!c_isxdigit(p[i]))
O
Osier Yang 已提交
1529
            break;
1530
    }
O
Osier Yang 已提交
1531

1532
    if (i != 16 || p[i]) {
1533 1534
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Malformed wwn: %s"), wwn);
O
Osier Yang 已提交
1535 1536 1537 1538 1539
        return false;
    }

    return true;
}
1540

1541 1542 1543 1544 1545 1546
#if defined(major) && defined(minor)
int
virGetDeviceID(const char *path, int *maj, int *min)
{
    struct stat sb;

1547
    if (stat(path, &sb) < 0)
1548 1549
        return -errno;

1550
    if (!S_ISBLK(sb.st_mode))
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
        return -EINVAL;

    if (maj)
        *maj = major(sb.st_rdev);
    if (min)
        *min = minor(sb.st_rdev);

    return 0;
}
#else
int
J
Ján Tomko 已提交
1562 1563 1564
virGetDeviceID(const char *path G_GNUC_UNUSED,
               int *maj G_GNUC_UNUSED,
               int *min G_GNUC_UNUSED)
1565 1566 1567 1568 1569 1570 1571
{
    return -ENOSYS;
}
#endif

#define SYSFS_DEV_BLOCK_PATH "/sys/dev/block"

1572
char *
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
virGetUnprivSGIOSysfsPath(const char *path,
                          const char *sysfs_dir)
{
    int maj, min;
    char *sysfs_path = NULL;
    int rc;

    if ((rc = virGetDeviceID(path, &maj, &min)) < 0) {
        virReportSystemError(-rc,
                             _("Unable to get device ID '%s'"),
                             path);
        return NULL;
    }

1587 1588 1589
    sysfs_path = g_strdup_printf("%s/%d:%d/queue/unpriv_sgio",
                                 sysfs_dir ? sysfs_dir : SYSFS_DEV_BLOCK_PATH,
                                 maj, min);
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    return sysfs_path;
}

int
virSetDeviceUnprivSGIO(const char *path,
                       const char *sysfs_dir,
                       int unpriv_sgio)
{
    char *sysfs_path = NULL;
    char *val = NULL;
    int ret = -1;
    int rc;

    if (!(sysfs_path = virGetUnprivSGIOSysfsPath(path, sysfs_dir)))
        return -1;

    if (!virFileExists(sysfs_path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("unpriv_sgio is not supported by this kernel"));
        goto cleanup;
    }

1612
    val = g_strdup_printf("%d", unpriv_sgio);
1613 1614 1615 1616 1617 1618 1619

    if ((rc = virFileWriteStr(sysfs_path, val, 0)) < 0) {
        virReportSystemError(-rc, _("failed to set %s"), sysfs_path);
        goto cleanup;
    }

    ret = 0;
1620
 cleanup:
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    VIR_FREE(sysfs_path);
    VIR_FREE(val);
    return ret;
}

int
virGetDeviceUnprivSGIO(const char *path,
                       const char *sysfs_dir,
                       int *unpriv_sgio)
{
    char *sysfs_path = NULL;
    char *buf = NULL;
    char *tmp = NULL;
    int ret = -1;

    if (!(sysfs_path = virGetUnprivSGIOSysfsPath(path, sysfs_dir)))
        return -1;

    if (!virFileExists(sysfs_path)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("unpriv_sgio is not supported by this kernel"));
        goto cleanup;
    }

    if (virFileReadAll(sysfs_path, 1024, &buf) < 0)
        goto cleanup;

    if ((tmp = strchr(buf, '\n')))
        *tmp = '\0';

    if (virStrToLong_i(buf, NULL, 10, unpriv_sgio) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to parse value of %s"), sysfs_path);
        goto cleanup;
    }

    ret = 0;
1658
 cleanup:
1659 1660 1661 1662
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}
1663

1664

M
Martin Kletzander 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
/**
 * virParseOwnershipIds:
 *
 * Parse the usual "uid:gid" ownership specification into uid_t and
 * gid_t passed as parameters.  NULL value for those parameters mean
 * the information is not needed.  Also, none of those values are
 * changed in case of any error.
 *
 * Returns -1 on error, 0 otherwise.
 */
int
virParseOwnershipIds(const char *label, uid_t *uidPtr, gid_t *gidPtr)
{
    int rc = -1;
    uid_t theuid;
    gid_t thegid;
    char *tmp_label = NULL;
    char *sep = NULL;
    char *owner = NULL;
    char *group = NULL;

1686
    tmp_label = g_strdup(label);
M
Martin Kletzander 已提交
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

    /* Split label */
    sep = strchr(tmp_label, ':');
    if (sep == NULL) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Failed to parse uid and gid from '%s'"),
                       label);
        goto cleanup;
    }
    *sep = '\0';
    owner = tmp_label;
    group = sep + 1;

    /* Parse owner and group, error message is defined by
     * virGetUserID or virGetGroupID.
     */
    if (virGetUserID(owner, &theuid) < 0 ||
        virGetGroupID(group, &thegid) < 0)
        goto cleanup;

    if (uidPtr)
        *uidPtr = theuid;
    if (gidPtr)
        *gidPtr = thegid;

    rc = 0;

1714
 cleanup:
M
Martin Kletzander 已提交
1715 1716 1717 1718
    VIR_FREE(tmp_label);

    return rc;
}
1719

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
static time_t selfLastChanged;

time_t virGetSelfLastChanged(void)
{
    return selfLastChanged;
}


void virUpdateSelfLastChanged(const char *path)
{
    struct stat sb;

    if (stat(path, &sb) < 0)
        return;

    if (sb.st_ctime > selfLastChanged) {
        VIR_DEBUG("Setting self last changed to %lld for '%s'",
                  (long long)sb.st_ctime, path);
        selfLastChanged = sb.st_ctime;
    }
}
1741

1742

P
Pavel Hrdina 已提交
1743
#ifndef WIN32
1744 1745 1746 1747
long virGetSystemPageSize(void)
{
    return sysconf(_SC_PAGESIZE);
}
P
Pavel Hrdina 已提交
1748 1749 1750 1751 1752 1753 1754
#else /* WIN32 */
long virGetSystemPageSize(void)
{
    errno = ENOSYS;
    return -1;
}
#endif /* WIN32 */
1755 1756 1757 1758 1759 1760 1761 1762

long virGetSystemPageSizeKB(void)
{
    long val = virGetSystemPageSize();
    if (val < 0)
        return val;
    return val / 1024;
}
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786

/**
 * virMemoryLimitTruncate
 *
 * Return truncated memory limit to VIR_DOMAIN_MEMORY_PARAM_UNLIMITED as maximum
 * which means that the limit is not set => unlimited.
 */
unsigned long long
virMemoryLimitTruncate(unsigned long long value)
{
    return value < VIR_DOMAIN_MEMORY_PARAM_UNLIMITED ? value :
        VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
}

/**
 * virMemoryLimitIsSet
 *
 * Returns true if the limit is set and false for unlimited value.
 */
bool
virMemoryLimitIsSet(unsigned long long value)
{
    return value < VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
}
1787 1788 1789 1790 1791


/**
 * virMemoryMaxValue
 *
1792
 * @capped: whether the value must fit into unsigned long
1793 1794
 *   (long long is assumed otherwise)
 *
1795 1796
 * Note: This function is mocked in tests/qemuxml2argvmock.c for test stability
 *
1797 1798 1799
 * Returns the maximum possible memory value in bytes.
 */
unsigned long long
1800
virMemoryMaxValue(bool capped)
1801 1802 1803
{
    /* On 32-bit machines, our bound is 0xffffffff * KiB. On 64-bit
     * machines, our bound is off_t (2^63).  */
1804
    if (capped && sizeof(unsigned long) < sizeof(long long))
1805 1806 1807 1808
        return 1024ull * ULONG_MAX;
    else
        return LLONG_MAX;
}
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833


bool
virHostHasIOMMU(void)
{
    DIR *iommuDir = NULL;
    struct dirent *iommuGroup = NULL;
    bool ret = false;
    int direrr;

    if (virDirOpenQuiet(&iommuDir, "/sys/kernel/iommu_groups/") < 0)
        goto cleanup;

    while ((direrr = virDirRead(iommuDir, &iommuGroup, NULL)) > 0)
        break;

    if (direrr < 0 || !iommuGroup)
        goto cleanup;

    ret = true;

 cleanup:
    VIR_DIR_CLOSE(iommuDir);
    return ret;
}
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876


/**
 * virHostGetDRMRenderNode:
 *
 * Picks the first DRM render node available. Missing DRI or missing DRM render
 * nodes in the system results in an error.
 *
 * Returns an absolute path to the first render node available or NULL in case
 * of an error with the error being reported.
 * Caller is responsible for freeing the result string.
 *
 */
char *
virHostGetDRMRenderNode(void)
{
    char *ret = NULL;
    DIR *driDir = NULL;
    const char *driPath = "/dev/dri";
    struct dirent *ent = NULL;
    int dirErr = 0;
    bool have_rendernode = false;

    if (virDirOpen(&driDir, driPath) < 0)
        return NULL;

    while ((dirErr = virDirRead(driDir, &ent, driPath)) > 0) {
        if (STRPREFIX(ent->d_name, "renderD")) {
            have_rendernode = true;
            break;
        }
    }

    if (dirErr < 0)
        goto cleanup;

    /* even if /dev/dri exists, there might be no renderDX nodes available */
    if (!have_rendernode) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("No DRM render nodes available"));
        goto cleanup;
    }

1877
    ret = g_strdup_printf("%s/%s", driPath, ent->d_name);
1878 1879 1880 1881 1882

 cleanup:
    VIR_DIR_CLOSE(driDir);
    return ret;
}