virutil.c 67.6 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 25 26
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 * File created Jul 18, 2007 - Shuveb Hussain <shuveb@binarykarma.com>
 */

27
#include <config.h>
28

29
#include <stdlib.h>
30
#include <dirent.h>
31 32 33 34 35
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
C
Cole Robinson 已提交
36
#include <poll.h>
37
#include <sys/stat.h>
38
#include <sys/types.h>
39
#include <sys/ioctl.h>
40
#include <string.h>
E
Eric Blake 已提交
41
#include <termios.h>
42
#include <locale.h>
43

44 45 46
#if HAVE_LIBDEVMAPPER_H
# include <libdevmapper.h>
#endif
47

48
#ifdef HAVE_PATHS_H
49
# include <paths.h>
50
#endif
51
#include <netdb.h>
52
#ifdef HAVE_GETPWUID_R
53 54
# include <pwd.h>
# include <grp.h>
55
#endif
56
#if WITH_CAPNG
57
# include <cap-ng.h>
58
# include <sys/prctl.h>
59
#endif
60

61
#ifdef WIN32
62 63 64
# ifdef HAVE_WINSOCK2_H
#  include <winsock2.h>
# endif
65 66 67 68
# include <windows.h>
# include <shlobj.h>
#endif

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

84 85
verify(sizeof(gid_t) <= sizeof(unsigned int) &&
       sizeof(uid_t) <= sizeof(unsigned int));
86

87
#define VIR_FROM_THIS VIR_FROM_NONE
88

89 90
VIR_LOG_INIT("util.util");

J
Ján Tomko 已提交
91 92 93 94 95
VIR_ENUM_IMPL(virTristateBool, VIR_TRISTATE_BOOL_LAST,
              "default",
              "yes",
              "no")

J
Ján Tomko 已提交
96 97 98 99 100 101
VIR_ENUM_IMPL(virTristateSwitch, VIR_TRISTATE_SWITCH_LAST,
              "default",
              "on",
              "off")


102
#ifndef WIN32
103

104 105
int virSetInherit(int fd, bool inherit)
{
106 107
    int fflags;
    if ((fflags = fcntl(fd, F_GETFD)) < 0)
108
        return -1;
109 110 111 112 113
    if (inherit)
        fflags &= ~FD_CLOEXEC;
    else
        fflags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, fflags)) < 0)
114
        return -1;
115 116 117
    return 0;
}

118
#else /* WIN32 */
119

120
int virSetInherit(int fd ATTRIBUTE_UNUSED, bool inherit ATTRIBUTE_UNUSED)
121
{
122 123 124 125 126
    /* 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;
127 128
}

129
#endif /* WIN32 */
130

131 132
int virSetBlocking(int fd, bool blocking)
{
133
    return set_nonblocking_flag(fd, !blocking);
134 135
}

136 137
int virSetNonBlock(int fd)
{
138
    return virSetBlocking(fd, false);
139
}
140

141
int virSetCloseExec(int fd)
142
{
143
    return virSetInherit(fd, false);
144 145
}

146
#ifdef WIN32
147
int virSetSockReuseAddr(int fd ATTRIBUTE_UNUSED, bool fatal ATTRIBUTE_UNUSED)
148 149 150 151 152 153 154 155 156 157 158 159 160 161
{
    /*
     * 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
162
int virSetSockReuseAddr(int fd, bool fatal)
163 164
{
    int opt = 1;
165 166 167 168 169 170 171 172
    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;
173 174 175
}
#endif

176 177 178
int
virPipeReadUntilEOF(int outfd, int errfd,
                    char **outbuf, char **errbuf) {
179

180
    struct pollfd fds[2];
181
    size_t i;
182
    bool finished[2];
183

184 185 186
    fds[0].fd = outfd;
    fds[0].events = POLLIN;
    fds[0].revents = 0;
187
    finished[0] = false;
188 189 190
    fds[1].fd = errfd;
    fds[1].events = POLLIN;
    fds[1].revents = 0;
191
    finished[1] = false;
192

193
    while (!(finished[0] && finished[1])) {
194

195 196 197 198
        if (poll(fds, ARRAY_CARDINALITY(fds), -1) < 0) {
            if ((errno == EAGAIN) || (errno == EINTR))
                continue;
            goto pollerr;
199 200
        }

201 202 203
        for (i = 0; i < ARRAY_CARDINALITY(fds); ++i) {
            char data[1024], **buf;
            int got, size;
204

205 206 207
            if (!(fds[i].revents))
                continue;
            else if (fds[i].revents & POLLHUP)
208
                finished[i] = true;
209

210 211 212
            if (!(fds[i].revents & POLLIN)) {
                if (fds[i].revents & POLLHUP)
                    continue;
213

214 215 216 217
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Unknown poll response."));
                goto error;
            }
218

219
            got = read(fds[i].fd, data, sizeof(data));
220

221
            if (got == sizeof(data))
222
                finished[i] = false;
A
Amy Griffis 已提交
223

224
            if (got == 0) {
225
                finished[i] = true;
226 227 228 229 230 231 232 233 234
                continue;
            }
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
                goto pollerr;
            }
A
Amy Griffis 已提交
235

236 237
            buf = ((fds[i].fd == outfd) ? outbuf : errbuf);
            size = (*buf ? strlen(*buf) : 0);
238
            if (VIR_REALLOC_N(*buf, size+got+1) < 0)
239 240 241
                goto error;
            memmove(*buf+size, data, got);
            (*buf)[size+got] = '\0';
A
Amy Griffis 已提交
242
        }
243
        continue;
244

245 246 247 248
    pollerr:
        virReportSystemError(errno,
                             "%s", _("poll error"));
        goto error;
249 250
    }

251
    return 0;
252

253
 error:
254 255 256
    VIR_FREE(*outbuf);
    VIR_FREE(*errbuf);
    return -1;
257 258
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
/* 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;
    }
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287
/* 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) {
288 289
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("invalid scale %llu"), scale);
290 291 292 293 294 295 296 297 298 299 300 301 302 303
            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 {
304
            virReportError(VIR_ERR_INVALID_ARG,
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
                         _("unknown suffix '%s'"), suffix);
            return -1;
        }
        scale = 1;
        switch (c_tolower(*suffix)) {
        case 'e':
            scale *= base;
            /* fallthrough */
        case 'p':
            scale *= base;
            /* fallthrough */
        case 't':
            scale *= base;
            /* fallthrough */
        case 'g':
            scale *= base;
            /* fallthrough */
        case 'm':
            scale *= base;
            /* fallthrough */
        case 'k':
            scale *= base;
            break;
        default:
329 330
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unknown suffix '%s'"), suffix);
331 332 333 334
            return -1;
        }
    }

G
Guannan Ren 已提交
335
    if (*value && *value > (limit / scale)) {
336 337
        virReportError(VIR_ERR_OVERFLOW, _("value too large: %llu%s"),
                       *value, suffix);
338 339 340 341 342 343
        return -1;
    }
    *value *= scale;
    return 0;
}

E
Eric Blake 已提交
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
/**
 * virParseNumber:
 * @str: pointer to the char pointer used
 *
 * Parse an unsigned number
 *
 * Returns the unsigned number or -1 in case of error. @str will be
 *         updated to skip the number.
 */
int
virParseNumber(const char **str)
{
    int ret = 0;
    const char *cur = *str;

    if ((*cur < '0') || (*cur > '9'))
361
        return -1;
362

J
Jim Meyering 已提交
363
    while (c_isdigit(*cur)) {
364 365 366 367
        unsigned int c = *cur - '0';

        if ((ret > INT_MAX / 10) ||
            ((ret == INT_MAX / 10) && (c > INT_MAX % 10)))
368
            return -1;
369 370 371 372
        ret = ret * 10 + c;
        cur++;
    }
    *str = cur;
373
    return ret;
374
}
375

376 377 378 379
/**
 * virParseVersionString:
 * @str: const char pointer to the version string
 * @version: unsigned long pointer to output the version number
380 381
 * @allowMissing: true to treat 3 like 3.0.0, false to error out on
 * missing minor or micro
382 383 384 385 386 387 388 389 390 391 392
 *
 * 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
393 394
virParseVersionString(const char *str, unsigned long *version,
                      bool allowMissing)
395
{
396
    unsigned int major, minor = 0, micro = 0;
397 398
    char *tmp;

399
    if (virStrToLong_ui(str, &tmp, 10, &major) < 0)
400 401
        return -1;

402 403 404
    if (!allowMissing && *tmp != '.')
        return -1;

405
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &minor) < 0)
406 407
        return -1;

408 409 410
    if (!allowMissing && *tmp != '.')
        return -1;

411
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &micro) < 0)
412 413
        return -1;

414 415 416
    if (major > UINT_MAX / 1000000 || minor > 999 || micro > 999)
        return -1;

417 418 419 420 421
    *version = 1000000 * major + 1000 * minor + micro;

    return 0;
}

422 423 424 425
int virEnumFromString(const char *const*types,
                      unsigned int ntypes,
                      const char *type)
{
426
    size_t i;
427 428 429
    if (!type)
        return -1;

430
    for (i = 0; i < ntypes; i++)
431 432 433 434 435 436
        if (STREQ(types[i], type))
            return i;

    return -1;
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
/* In case thread-safe locales are available */
#if HAVE_NEWLOCALE

static locale_t virLocale;

static int
virLocaleOnceInit(void)
{
    virLocale = newlocale(LC_ALL_MASK, "C", (locale_t)0);
    if (!virLocale)
        return -1;
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virLocale)
#endif

/**
 * virDoubleToStr
 *
 * converts double to string with C locale (thread-safe).
 *
 * Returns -1 on error, size of the string otherwise.
 */
int
virDoubleToStr(char **strp, double number)
{
    int ret = -1;

#if HAVE_NEWLOCALE

    locale_t old_loc;

    if (virLocaleInitialize() < 0)
        goto error;

    old_loc = uselocale(virLocale);
    ret = virAsprintf(strp, "%lf", number);
    uselocale(old_loc);

#else

    char *radix, *tmp;
    struct lconv *lc;

482
    if ((ret = virAsprintf(strp, "%lf", number) < 0))
483 484 485 486 487 488 489 490
        goto error;

    lc = localeconv();
    radix = lc->decimal_point;
    tmp = strstr(*strp, radix);
    if (tmp) {
        *tmp = '.';
        if (strlen(radix) > 1)
491
            memmove(tmp + 1, tmp + strlen(radix), strlen(*strp) - (tmp - *strp));
492 493 494 495 496 497 498
    }

#endif /* HAVE_NEWLOCALE */
 error:
    return ret;
}

D
Daniel P. Berrange 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

/**
 * 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;
}


529 530 531 532 533 534 535 536 537 538
const char *virEnumToString(const char *const*types,
                            unsigned int ntypes,
                            int type)
{
    if (type < 0 || type >= ntypes)
        return NULL;

    return types[type];
}

539
/* Translates a device name of the form (regex) /^[fhv]d[a-z]+[0-9]*$/
540 541
 * into the corresponding index and partition number
 * (e.g. sda0 => (0,0), hdz2 => (25,2), vdaa12 => (26,12))
542
 * @param name The name of the device
543 544 545
 * @param disk The disk index to be returned
 * @param partition The partition index to be returned
 * @return 0 on success, or -1 on failure
546
 */
547
int virDiskNameParse(const char *name, int *disk, int *partition)
548
{
549
    const char *ptr = NULL;
550
    char *rem;
551
    int idx = 0;
552
    static char const* const drive_prefix[] = {"fd", "hd", "vd", "sd", "xvd", "ubd"};
553
    size_t i;
554

555 556 557
    for (i = 0; i < ARRAY_CARDINALITY(drive_prefix); i++) {
        if (STRPREFIX(name, drive_prefix[i])) {
            ptr = name + strlen(drive_prefix[i]);
558
            break;
559
        }
560 561
    }

562
    if (!ptr)
563 564
        return -1;

D
Daniel Veillard 已提交
565
    for (i = 0; *ptr; i++) {
J
Jim Meyering 已提交
566
        if (!c_islower(*ptr))
567
            break;
568

569
        idx = (idx + (i < 1 ? 0 : 1)) * 26;
570 571 572 573
        idx += *ptr - 'a';
        ptr++;
    }

574 575 576 577 578
    /* Count the trailing digits.  */
    size_t n_digits = strspn(ptr, "0123456789");
    if (ptr[n_digits] != '\0')
        return -1;

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    *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;

    if (virDiskNameParse(name, &idx, NULL))
        idx = -1;

609 610
    return idx;
}
G
Guido Günther 已提交
611

612 613 614
char *virIndexToDiskName(int idx, const char *prefix)
{
    char *name = NULL;
615 616 617
    size_t i;
    int ctr;
    int offset;
618 619

    if (idx < 0) {
620 621
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Disk index %d is negative"), idx);
622 623 624
        return NULL;
    }

625
    for (i = 0, ctr = idx; ctr >= 0; ++i, ctr = ctr / 26 - 1) { }
626 627 628

    offset = strlen(prefix);

629
    if (VIR_ALLOC_N(name, offset + i + 1))
630 631 632 633 634
        return NULL;

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

635
    for (i = i - 1, ctr = idx; ctr >= 0; --i, ctr = ctr / 26 - 1)
636
        name[offset + i] = 'a' + (ctr % 26);
637 638 639 640

    return name;
}

641
#ifndef AI_CANONIDN
642
# define AI_CANONIDN 0
643 644
#endif

C
Chris Lalancette 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
/* 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
660
 *     b)  getaddrinfo() fails or resolves to localhost - in this case, the
661 662 663
 *         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 已提交
664
 */
665 666
static char *
virGetHostnameImpl(bool quiet)
667 668
{
    int r;
669
    char hostname[HOST_NAME_MAX+1], *result = NULL;
C
Chris Lalancette 已提交
670
    struct addrinfo hints, *info;
671

672
    r = gethostname(hostname, sizeof(hostname));
673
    if (r == -1) {
674 675 676
        if (!quiet)
            virReportSystemError(errno,
                                 "%s", _("failed to determine host name"));
677
        return NULL;
678
    }
679 680
    NUL_TERMINATE(hostname);

C
Chris Lalancette 已提交
681 682 683 684 685 686 687
    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.
         */
688
        ignore_value(VIR_STRDUP_QUIET(result, hostname));
689
        goto cleanup;
C
Chris Lalancette 已提交
690 691 692 693 694 695
    }

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

696 697 698 699
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_CANONNAME|AI_CANONIDN;
    hints.ai_family = AF_UNSPEC;
    r = getaddrinfo(hostname, NULL, &hints, &info);
700
    if (r != 0) {
701 702 703 704
        if (!quiet)
            VIR_WARN("getaddrinfo failed for '%s': %s",
                     hostname, gai_strerror(r));
        ignore_value(VIR_STRDUP_QUIET(result, hostname));
705
        goto cleanup;
706
    }
707

708
    /* Tell static analyzers about getaddrinfo semantics.  */
709
    sa_assert(info);
710

C
Chris Lalancette 已提交
711 712 713 714 715 716
    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
         */
717
        ignore_value(VIR_STRDUP_QUIET(result, hostname));
C
Chris Lalancette 已提交
718 719
    else
        /* Caller frees this string. */
720
        ignore_value(VIR_STRDUP_QUIET(result, info->ai_canonname));
721

C
Chris Lalancette 已提交
722
    freeaddrinfo(info);
723

724
 cleanup:
725 726
    if (!result)
        virReportOOMError();
727 728 729
    return result;
}

D
Dan Walsh 已提交
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744
char *
virGetHostname(void)
{
    return virGetHostnameImpl(false);
}


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


D
Dan Walsh 已提交
745 746 747 748 749 750 751
char *
virGetUserDirectory(void)
{
    return virGetUserDirectoryByUID(geteuid());
}


752
#ifdef HAVE_GETPWUID_R
E
Eric Blake 已提交
753 754 755 756
/* Look up fields from the user database for the given user.  On
 * error, set errno, report the error, and return -1.  */
static int
virGetUserEnt(uid_t uid, char **name, gid_t *group, char **dir)
757 758 759
{
    char *strbuf;
    struct passwd pwbuf;
760
    struct passwd *pw = NULL;
761 762
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
763
    int rc;
E
Eric Blake 已提交
764 765 766 767 768 769
    int ret = -1;

    if (name)
        *name = NULL;
    if (dir)
        *dir = NULL;
770

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

775
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
E
Eric Blake 已提交
776
        return -1;
777

778 779 780 781 782 783 784
    /*
     * 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.
     */
785
    while ((rc = getpwuid_r(uid, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
786
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
E
Eric Blake 已提交
787
            goto cleanup;
788
    }
789
    if (rc != 0) {
790
        virReportSystemError(rc,
E
Eric Blake 已提交
791 792
                             _("Failed to find user record for uid '%u'"),
                             (unsigned int) uid);
E
Eric Blake 已提交
793
        goto cleanup;
794 795 796 797 798
    } else if (pw == NULL) {
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Failed to find user record for uid '%u'"),
                       (unsigned int) uid);
        goto cleanup;
E
Eric Blake 已提交
799 800 801 802 803 804 805 806 807 808
    }

    if (name && VIR_STRDUP(*name, pw->pw_name) < 0)
        goto cleanup;
    if (group)
        *group = pw->pw_gid;
    if (dir && VIR_STRDUP(*dir, pw->pw_dir) < 0) {
        if (name)
            VIR_FREE(*name);
        goto cleanup;
809 810
    }

E
Eric Blake 已提交
811
    ret = 0;
812
 cleanup:
813 814 815
    VIR_FREE(strbuf);
    return ret;
}
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830
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;

831
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        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) {
848 849 850 851 852 853 854 855 856 857
        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);
        }

858 859 860 861
        VIR_FREE(strbuf);
        return NULL;
    }

862
    ignore_value(VIR_STRDUP(ret, gr->gr_name));
863 864 865 866
    VIR_FREE(strbuf);
    return ret;
}

D
Dan Walsh 已提交
867 868 869

char *
virGetUserDirectoryByUID(uid_t uid)
870
{
E
Eric Blake 已提交
871
    char *ret;
D
Dan Walsh 已提交
872
    virGetUserEnt(uid, NULL, NULL, &ret);
E
Eric Blake 已提交
873
    return ret;
874 875
}

D
Dan Walsh 已提交
876

877
static char *virGetXDGDirectory(const char *xdgenvname, const char *xdgdefdir)
878
{
879
    const char *path = virGetEnvBlockSUID(xdgenvname);
880
    char *ret = NULL;
881
    char *home = NULL;
882 883

    if (path && path[0]) {
884
        ignore_value(virAsprintf(&ret, "%s/libvirt", path));
885
    } else {
E
Eric Blake 已提交
886 887 888
        home = virGetUserDirectory();
        if (home)
            ignore_value(virAsprintf(&ret, "%s/%s/libvirt", home, xdgdefdir));
889 890 891 892 893 894
    }

    VIR_FREE(home);
    return ret;
}

895
char *virGetUserConfigDirectory(void)
896
{
897
    return virGetXDGDirectory("XDG_CONFIG_HOME", ".config");
898 899
}

900
char *virGetUserCacheDirectory(void)
901
{
902
     return virGetXDGDirectory("XDG_CACHE_HOME", ".cache");
903 904
}

905
char *virGetUserRuntimeDirectory(void)
906
{
907
    const char *path = virGetEnvBlockSUID("XDG_RUNTIME_DIR");
908 909

    if (!path || !path[0]) {
910
        return virGetUserCacheDirectory();
911 912 913
    } else {
        char *ret;

914
        ignore_value(virAsprintf(&ret, "%s/libvirt", path));
915 916 917 918
        return ret;
    }
}

919
char *virGetUserName(uid_t uid)
920
{
E
Eric Blake 已提交
921 922 923
    char *ret;
    virGetUserEnt(uid, &ret, NULL, NULL);
    return ret;
924 925
}

926 927 928 929 930
char *virGetGroupName(gid_t gid)
{
    return virGetGroupEnt(gid);
}

931 932 933 934 935
/* 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.
 */
static int
virGetUserIDByName(const char *name, uid_t *uid)
936
{
937
    char *strbuf = NULL;
938 939
    struct passwd pwbuf;
    struct passwd *pw = NULL;
940 941
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
942
    int rc;
943
    int ret = -1;
944

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

949
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
950
        goto cleanup;
951

952
    while ((rc = getpwnam_r(name, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
953
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
954
            goto cleanup;
955
    }
956 957

    if (!pw) {
958 959 960 961 962
        if (rc != 0) {
            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 */
963
            VIR_WARN("User record for user '%s' was not found: %s",
964 965 966
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

967 968
        ret = 1;
        goto cleanup;
969 970 971
    }

    *uid = pw->pw_uid;
972
    ret = 0;
973

974
 cleanup:
975 976
    VIR_FREE(strbuf);

977
    return ret;
978 979
}

980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
/* 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 {
        int rc = virGetUserIDByName(user, uid);
        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;
}
1010

1011 1012 1013 1014 1015
/* 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.
 */
static int
virGetGroupIDByName(const char *name, gid_t *gid)
1016
{
1017
    char *strbuf = NULL;
1018 1019
    struct group grbuf;
    struct group *gr = NULL;
1020 1021
    long val = sysconf(_SC_GETGR_R_SIZE_MAX);
    size_t strbuflen = val;
1022
    int rc;
1023
    int ret = -1;
1024

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

1029
    if (VIR_ALLOC_N(strbuf, strbuflen) < 0)
1030
        goto cleanup;
1031

1032
    while ((rc = getgrnam_r(name, &grbuf, strbuf, strbuflen, &gr)) == ERANGE) {
1033
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0)
1034
            goto cleanup;
1035
    }
1036 1037

    if (!gr) {
1038 1039 1040 1041 1042
        if (rc != 0) {
            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 */
1043
            VIR_WARN("Group record for user '%s' was not found: %s",
1044 1045 1046
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

1047 1048
        ret = 1;
        goto cleanup;
1049 1050 1051
    }

    *gid = gr->gr_gid;
1052
    ret = 0;
1053

1054
 cleanup:
1055 1056
    VIR_FREE(strbuf);

1057
    return ret;
1058
}
1059

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
/* 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 {
        int rc = virGetGroupIDByName(group, gid);
        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 已提交
1090

E
Eric Blake 已提交
1091

1092 1093 1094 1095 1096
/* Compute the list of primary and supplementary groups associated
 * with @uid, and including @gid in the list (unless it is -1),
 * storing a malloc'd result into @list. Return 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 已提交
1097 1098 1099 1100 1101
int
virGetGroupList(uid_t uid, gid_t gid, gid_t **list)
{
    int ret = -1;
    char *user = NULL;
1102
    gid_t primary;
E
Eric Blake 已提交
1103 1104 1105 1106 1107

    *list = NULL;
    if (uid == (uid_t)-1)
        return 0;

1108
    if (virGetUserEnt(uid, &user, &primary, NULL) < 0)
E
Eric Blake 已提交
1109 1110
        return -1;

1111 1112
    ret = mgetgroups(user, primary, list);
    if (ret < 0) {
1113
        sa_assert(!*list);
E
Eric Blake 已提交
1114 1115
        virReportSystemError(errno,
                             _("cannot get group list for '%s'"), user);
1116 1117 1118 1119
        goto cleanup;
    }

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

E
Eric Blake 已提交
1122
        for (i = 0; i < ret; i++) {
1123 1124 1125
            if ((*list)[i] == gid)
                goto cleanup;
        }
E
Eric Blake 已提交
1126
        if (VIR_APPEND_ELEMENT(*list, i, gid) < 0) {
1127 1128 1129 1130
            ret = -1;
            VIR_FREE(*list);
            goto cleanup;
        } else {
E
Eric Blake 已提交
1131
            ret = i;
1132 1133 1134
        }
    }

1135
 cleanup:
E
Eric Blake 已提交
1136 1137 1138 1139 1140
    VIR_FREE(user);
    return ret;
}


1141 1142 1143 1144
/* 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 已提交
1145 1146
 */
int
1147 1148
virSetUIDGID(uid_t uid, gid_t gid, gid_t *groups ATTRIBUTE_UNUSED,
             int ngroups ATTRIBUTE_UNUSED)
L
Laine Stump 已提交
1149
{
1150 1151 1152 1153 1154
    if (gid != (gid_t)-1 && setregid(gid, gid) < 0) {
        virReportSystemError(errno,
                             _("cannot change to '%u' group"),
                             (unsigned int) gid);
        return -1;
L
Laine Stump 已提交
1155 1156
    }

1157
# if HAVE_SETGROUPS
1158
    if (gid != (gid_t)-1 && setgroups(ngroups, groups) < 0) {
1159 1160 1161 1162
        virReportSystemError(errno, "%s",
                             _("cannot set supplemental groups"));
        return -1;
    }
L
Laine Stump 已提交
1163
# endif
1164 1165 1166 1167 1168 1169

    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 已提交
1170
    }
1171

L
Laine Stump 已提交
1172 1173 1174
    return 0;
}

1175 1176
#else /* ! HAVE_GETPWUID_R */

E
Eric Blake 已提交
1177 1178 1179 1180 1181 1182 1183 1184
int
virGetGroupList(uid_t uid ATTRIBUTE_UNUSED, gid_t gid ATTRIBUTE_UNUSED,
                gid_t **list)
{
    *list = NULL;
    return 0;
}

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
# 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) {
1197 1198
        if (SHGetPathFromIDList(pidl, buf) && VIR_STRDUP(*path, buf) < 0)
            ret = -1;
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
        CoTaskMemFree(pidl);
    }
    return ret;
}

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

    *path = NULL;

E
Eric Blake 已提交
1211
    if (GetWindowsDirectory(windowsdir, ARRAY_CARDINALITY(windowsdir))) {
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
        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:\\");
    }

1226
    return VIR_STRDUP(*path, windowsdir) < 0 ? -1 : 0;
1227 1228 1229 1230 1231
}



char *
D
Dan Walsh 已提交
1232
virGetUserDirectoryByUID(uid_t uid ATTRIBUTE_UNUSED)
1233
{
D
Dan Walsh 已提交
1234 1235 1236
    /* 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 */
1237 1238 1239
    const char *dir;
    char *ret;

1240
    dir = virGetEnvBlockSUID("HOME");
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253

    /* 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;
1254
        while ((p = strchr(dir, '/')) != NULL)
1255 1256 1257 1258 1259
            *p = '\\';
    }

    if (!dir)
        /* USERPROFILE is probably the closest equivalent to $HOME? */
1260
        dir = virGetEnvBlockSUID("USERPROFILE");
1261

1262 1263
    if (VIR_STRDUP(ret, dir) < 0)
        return NULL;
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273

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

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

    if (!ret) {
1274 1275
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine home directory"));
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
        return NULL;
    }

    return ret;
}

char *
virGetUserConfigDirectory(void)
{
    char *ret;
    if (virGetWin32SpecialFolder(CSIDL_LOCAL_APPDATA, &ret) < 0)
        return NULL;
1288

1289
    if (!ret) {
1290 1291
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        return NULL;
    }
    return ret;
}

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

    if (!ret) {
1305 1306
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
        return NULL;
    }
    return ret;
}

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

1318
# else /* !HAVE_GETPWUID_R && !WIN32 */
1319
char *
D
Dan Walsh 已提交
1320
virGetUserDirectoryByUID(uid_t uid ATTRIBUTE_UNUSED)
1321
{
1322 1323
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserDirectory is not available"));
1324 1325 1326 1327

    return NULL;
}

1328 1329 1330
char *
virGetUserConfigDirectory(void)
{
1331 1332
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserConfigDirectory is not available"));
1333 1334 1335 1336 1337 1338 1339

    return NULL;
}

char *
virGetUserCacheDirectory(void)
{
1340 1341
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserCacheDirectory is not available"));
1342 1343 1344 1345 1346 1347 1348

    return NULL;
}

char *
virGetUserRuntimeDirectory(void)
{
1349 1350
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserRuntimeDirectory is not available"));
1351 1352 1353 1354 1355

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

1356 1357 1358
char *
virGetUserName(uid_t uid ATTRIBUTE_UNUSED)
{
1359 1360
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserName is not available"));
1361 1362 1363 1364 1365 1366 1367

    return NULL;
}

int virGetUserID(const char *name ATTRIBUTE_UNUSED,
                 uid_t *uid ATTRIBUTE_UNUSED)
{
1368 1369
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserID is not available"));
1370

1371
    return -1;
1372 1373 1374 1375 1376 1377
}


int virGetGroupID(const char *name ATTRIBUTE_UNUSED,
                  gid_t *gid ATTRIBUTE_UNUSED)
{
1378 1379
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupID is not available"));
1380

1381
    return -1;
1382
}
L
Laine Stump 已提交
1383 1384 1385

int
virSetUIDGID(uid_t uid ATTRIBUTE_UNUSED,
1386 1387 1388
             gid_t gid ATTRIBUTE_UNUSED,
             gid_t *groups ATTRIBUTE_UNUSED,
             int ngroups ATTRIBUTE_UNUSED)
L
Laine Stump 已提交
1389
{
1390 1391
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virSetUIDGID is not available"));
L
Laine Stump 已提交
1392 1393
    return -1;
}
1394 1395 1396 1397

char *
virGetGroupName(gid_t gid ATTRIBUTE_UNUSED)
{
1398 1399
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupName is not available"));
1400 1401 1402

    return NULL;
}
1403
#endif /* HAVE_GETPWUID_R */
1404

1405 1406 1407 1408 1409 1410 1411
#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
1412 1413
virSetUIDGIDWithCaps(uid_t uid, gid_t gid, gid_t *groups, int ngroups,
                     unsigned long long capBits, bool clearExistingCaps)
1414
{
1415 1416
    size_t i;
    int capng_ret, ret = -1;
1417
    bool need_setgid = false, need_setuid = false;
1418
    bool need_setpcap = false;
1419

1420 1421 1422 1423
    /* 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.
1424 1425
     */

1426
    if (clearExistingCaps || (uid != (uid_t)-1 && uid != 0))
1427
       capng_clear(CAPNG_SELECT_BOTH);
1428

1429 1430
    for (i = 0; i <= CAP_LAST_CAP; i++) {
        if (capBits & (1ULL << i)) {
1431 1432 1433
            capng_update(CAPNG_ADD,
                         CAPNG_EFFECTIVE|CAPNG_INHERITABLE|
                         CAPNG_PERMITTED|CAPNG_BOUNDING_SET,
1434
                         i);
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
        }
    }

    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 */
1459
    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
1460 1461 1462 1463 1464 1465
        virReportSystemError(errno, "%s",
                             _("prctl failed to set KEEPCAPS"));
        goto cleanup;
    }

    /* Change to the temp capabilities */
1466
    if ((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0) {
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
        /* 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);
            goto cleanup;
        }
1482 1483
    }

1484
    if (virSetUIDGID(uid, gid, groups, ngroups) < 0)
1485 1486 1487
        goto cleanup;

    /* Tell it we are done keeping capabilities */
1488
    if (prctl(PR_SET_KEEPCAPS, 0, 0, 0, 0)) {
1489 1490 1491 1492 1493
        virReportSystemError(errno, "%s",
                             _("prctl failed to reset KEEPCAPS"));
        goto cleanup;
    }

1494 1495 1496 1497 1498 1499
    /* 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);

1500 1501 1502 1503 1504 1505 1506 1507 1508
    /* 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);

1509
    if (((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0)) {
1510 1511 1512 1513 1514 1515 1516
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot apply process capabilities %d"), capng_ret);
        ret = -1;
        goto cleanup;
    }

    ret = 0;
1517
 cleanup:
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
    return ret;
}

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

int
1528
virSetUIDGIDWithCaps(uid_t uid, gid_t gid, gid_t *groups, int ngroups,
1529 1530
                     unsigned long long capBits ATTRIBUTE_UNUSED,
                     bool clearExistingCaps ATTRIBUTE_UNUSED)
1531
{
1532
    return virSetUIDGID(uid, gid, groups, ngroups);
1533 1534 1535
}
#endif

1536

1537
#if defined(UDEVADM) || defined(UDEVSETTLE)
1538
void virFileWaitForDevices(void)
D
Daniel P. Berrange 已提交
1539
{
1540
# ifdef UDEVADM
D
Daniel P. Berrange 已提交
1541
    const char *const settleprog[] = { UDEVADM, "settle", NULL };
1542
# else
D
Daniel P. Berrange 已提交
1543
    const char *const settleprog[] = { UDEVSETTLE, NULL };
1544
# endif
D
Daniel P. Berrange 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    int exitstatus;

    if (access(settleprog[0], X_OK) != 0)
        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.
     * If this fails for any reason, we still have the backup of polling for
     * 5 seconds for device nodes.
     */
E
Eric Blake 已提交
1556
    ignore_value(virRun(settleprog, &exitstatus));
D
Daniel P. Berrange 已提交
1557
}
1558
#else
1559 1560
void virFileWaitForDevices(void)
{}
D
Daniel P. Berrange 已提交
1561
#endif
1562

1563
#if HAVE_LIBDEVMAPPER_H
1564
bool
1565
virIsDevMapperDevice(const char *dev_name)
1566 1567 1568
{
    struct stat buf;

1569
    if (!stat(dev_name, &buf) &&
1570 1571 1572 1573 1574 1575
        S_ISBLK(buf.st_mode) &&
        dm_is_dm_major(major(buf.st_rdev)))
            return true;

    return false;
}
1576
#else
1577
bool virIsDevMapperDevice(const char *dev_name ATTRIBUTE_UNUSED)
1578 1579 1580 1581
{
    return false;
}
#endif
O
Osier Yang 已提交
1582 1583

bool
1584 1585
virValidateWWN(const char *wwn)
{
1586
    size_t i;
1587
    const char *p = wwn;
O
Osier Yang 已提交
1588

1589
    if (STRPREFIX(wwn, "0x"))
1590 1591 1592 1593
        p += 2;

    for (i = 0; p[i]; i++) {
        if (!c_isxdigit(p[i]))
O
Osier Yang 已提交
1594
            break;
1595
    }
O
Osier Yang 已提交
1596

1597
    if (i != 16 || p[i]) {
1598 1599
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Malformed wwn: %s"), wwn);
O
Osier Yang 已提交
1600 1601 1602 1603 1604
        return false;
    }

    return true;
}
1605 1606 1607 1608

bool
virStrIsPrint(const char *str)
{
1609
    size_t i;
1610 1611 1612 1613 1614 1615 1616

    for (i = 0; str[i]; i++)
        if (!c_isprint(str[i]))
            return false;

    return true;
}
1617 1618 1619 1620 1621 1622 1623

#if defined(major) && defined(minor)
int
virGetDeviceID(const char *path, int *maj, int *min)
{
    struct stat sb;

1624
    if (stat(path, &sb) < 0)
1625 1626
        return -errno;

1627
    if (!S_ISBLK(sb.st_mode))
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
        return -EINVAL;

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

    return 0;
}
#else
int
E
Eric Blake 已提交
1639 1640 1641
virGetDeviceID(const char *path ATTRIBUTE_UNUSED,
               int *maj ATTRIBUTE_UNUSED,
               int *min ATTRIBUTE_UNUSED)
1642 1643 1644 1645 1646 1647 1648 1649
{

    return -ENOSYS;
}
#endif

#define SYSFS_DEV_BLOCK_PATH "/sys/dev/block"

1650
char *
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
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;
    }

1665 1666 1667
    ignore_value(virAsprintf(&sysfs_path, "%s/%d:%d/queue/unpriv_sgio",
                             sysfs_dir ? sysfs_dir : SYSFS_DEV_BLOCK_PATH,
                             maj, min));
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
    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;
    }

1690
    if (virAsprintf(&val, "%d", unpriv_sgio) < 0)
1691 1692 1693 1694 1695 1696 1697 1698
        goto cleanup;

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

    ret = 0;
1699
 cleanup:
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    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;
1737
 cleanup:
1738 1739 1740 1741
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}
1742 1743 1744

#ifdef __linux__
# define SYSFS_FC_HOST_PATH "/sys/class/fc_host/"
O
Osier Yang 已提交
1745
# define SYSFS_SCSI_HOST_PATH "/sys/class/scsi_host/"
1746

1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
/* virReadSCSIUniqueId:
 * @sysfs_prefix: "scsi_host" sysfs path, defaults to SYSFS_SCSI_HOST_PATH
 * @host: Host number, E.g. 5 of "scsi_host/host5"
 * @result: Return the entry value as an unsigned int
 *
 * Read the value of the "scsi_host" unique_id file.
 *
 * Returns 0 on success, and @result is filled with the unique_id value
 * Otherwise returns -1
 */
int
virReadSCSIUniqueId(const char *sysfs_prefix,
                    int host,
                    int *result)
{
    char *sysfs_path = NULL;
    char *p = NULL;
    int ret = -1;
    char *buf = NULL;
    int unique_id;

    if (virAsprintf(&sysfs_path, "%s/host%d/unique_id",
                    sysfs_prefix ? sysfs_prefix : SYSFS_SCSI_HOST_PATH,
                    host) < 0)
        goto cleanup;

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

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

    if (virStrToLong_i(buf, NULL, 10, &unique_id) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to parse unique_id: %s"), buf);

        goto cleanup;
    }

    *result = unique_id;
    ret = 0;

 cleanup:
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
/* virFindSCSIHostByPCI:
 * @sysfs_prefix: "scsi_host" sysfs path, defaults to SYSFS_SCSI_HOST_PATH
 * @parentaddr: string of the PCI address "scsi_host" device to be found
 * @unique_id: unique_id value of the to be found "scsi_host" device
 * @result: Return the host# of the matching "scsi_host" device
 *
 * Iterate over the SYSFS_SCSI_HOST_PATH entries looking for a matching
 * PCI Address in the expected format (dddd:bb:ss.f, where 'dddd' is the
 * 'domain' value, 'bb' is the 'bus' value, 'ss' is the 'slot' value, and
 * 'f' is the 'function' value from the PCI address) with a unique_id file
 * entry having the value expected. Unlike virReadSCSIUniqueId() we don't
 * have a host number yet and that's what we're looking for.
 *
 * Returns the host name of the "scsi_host" which must be freed by the caller,
 * or NULL on failure
 */
char *
virFindSCSIHostByPCI(const char *sysfs_prefix,
                     const char *parentaddr,
                     unsigned int unique_id)
{
    const char *prefix = sysfs_prefix ? sysfs_prefix : SYSFS_SCSI_HOST_PATH;
    struct dirent *entry = NULL;
    DIR *dir = NULL;
    char *host_link = NULL;
    char *host_path = NULL;
    char *p = NULL;
    char *ret = NULL;
    char *buf = NULL;
    char *unique_path = NULL;
    unsigned int read_unique_id;

    if (!(dir = opendir(prefix))) {
        virReportSystemError(errno,
                             _("Failed to opendir path '%s'"),
                             prefix);
J
Jiri Denemark 已提交
1831
        return NULL;
1832 1833 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
    }

    while (virDirRead(dir, &entry, prefix) > 0) {
        if (entry->d_name[0] == '.' || !virFileIsLink(entry->d_name))
            continue;

        if (virAsprintf(&host_link, "%s/%s", prefix, entry->d_name) < 0)
            goto cleanup;

        if (virFileResolveLink(host_link, &host_path) < 0)
            goto cleanup;

        if (!strstr(host_path, parentaddr)) {
            VIR_FREE(host_link);
            VIR_FREE(host_path);
            continue;
        }
        VIR_FREE(host_link);
        VIR_FREE(host_path);

        if (virAsprintf(&unique_path, "%s/%s/unique_id", prefix,
                        entry->d_name) < 0)
            goto cleanup;

        if (!virFileExists(unique_path)) {
            VIR_FREE(unique_path);
            continue;
        }

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

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

        if (virStrToLong_ui(buf, NULL, 10, &read_unique_id) < 0)
            goto cleanup;

1870 1871
        VIR_FREE(buf);

1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
        if (read_unique_id != unique_id) {
            VIR_FREE(unique_path);
            continue;
        }

        ignore_value(VIR_STRDUP(ret, entry->d_name));
        break;
    }

 cleanup:
    closedir(dir);
    VIR_FREE(unique_path);
    VIR_FREE(host_link);
    VIR_FREE(host_path);
1886
    VIR_FREE(buf);
1887 1888 1889
    return ret;
}

1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
/* virGetSCSIHostNumber:
 * @adapter_name: Name of the host adapter
 * @result: Return the entry value as unsigned int
 *
 * Convert the various forms of scsi_host names into the numeric
 * host# value that can be used in order to scan sysfs looking for
 * the specific host.
 *
 * Names can be either "scsi_host#" or just "host#", where
 * "host#" is the back-compat format, but both equate to
 * the same source adapter.  First check if both pool and def
 * are using same format (easier) - if so, then compare
 *
 * Returns 0 on success, and @result has the host number.
 * Otherwise returns -1.
 */
int
virGetSCSIHostNumber(const char *adapter_name,
                     unsigned int *result)
{
    /* Specifying adapter like 'host5' is still supported for
     * back-compat reason.
     */
    if (STRPREFIX(adapter_name, "scsi_host")) {
        adapter_name += strlen("scsi_host");
    } else if (STRPREFIX(adapter_name, "fc_host")) {
        adapter_name += strlen("fc_host");
    } else if (STRPREFIX(adapter_name, "host")) {
        adapter_name += strlen("host");
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid adapter name '%s' for SCSI pool"),
                       adapter_name);
        return -1;
    }

    if (virStrToLong_ui(adapter_name, NULL, 10, result) == -1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Invalid adapter name '%s' for SCSI pool"),
                       adapter_name);
        return -1;
    }

    return 0;
}

1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
/* virGetSCSIHostNameByParentaddr:
 * @domain: The domain from the scsi_host parentaddr
 * @bus: The bus from the scsi_host parentaddr
 * @slot: The slot from the scsi_host parentaddr
 * @function: The function from the scsi_host parentaddr
 * @unique_id: The unique id value for parentaddr
 *
 * Generate a parentaddr and find the scsi_host host# for
 * the provided parentaddr PCI address fields.
 *
 * Returns the "host#" string which must be free'd by
 * the caller or NULL on error
 */
char *
virGetSCSIHostNameByParentaddr(unsigned int domain,
                               unsigned int bus,
                               unsigned int slot,
                               unsigned int function,
                               unsigned int unique_id)
{
    char *name = NULL;
    char *parentaddr = NULL;

    if (virAsprintf(&parentaddr, "%04x:%02x:%02x.%01x",
                    domain, bus, slot, function) < 0)
        goto cleanup;
    if (!(name = virFindSCSIHostByPCI(NULL, parentaddr, unique_id))) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Failed to find scsi_host using PCI '%s' "
                         "and unique_id='%u'"),
                       parentaddr, unique_id);
        goto cleanup;
    }

 cleanup:
    VIR_FREE(parentaddr);
    return name;
}

1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
/* virReadFCHost:
 * @sysfs_prefix: "fc_host" sysfs path, defaults to SYSFS_FC_HOST_PATH
 * @host: Host number, E.g. 5 of "fc_host/host5"
 * @entry: Name of the sysfs entry to read
 * @result: Return the entry value as string
 *
 * Read the value of sysfs "fc_host" entry.
 *
 * Returns 0 on success, and @result is filled with the entry value.
 * as string, Otherwise returns -1. Caller must free @result after
 * use.
 */
int
virReadFCHost(const char *sysfs_prefix,
              int host,
              const char *entry,
              char **result)
{
    char *sysfs_path = NULL;
    char *p = NULL;
    int ret = -1;
    char *buf = NULL;

    if (virAsprintf(&sysfs_path, "%s/host%d/%s",
                    sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH,
2000
                    host, entry) < 0)
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
        goto cleanup;

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

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

    if ((p = strstr(buf, "0x")))
        p += strlen("0x");
    else
        p = buf;

O
Osier Yang 已提交
2014
    if (VIR_STRDUP(*result, p) < 0)
2015 2016 2017
        goto cleanup;

    ret = 0;
2018
 cleanup:
2019 2020 2021 2022
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}
O
Osier Yang 已提交
2023

2024
bool
O
Osier Yang 已提交
2025 2026 2027 2028
virIsCapableFCHost(const char *sysfs_prefix,
                   int host)
{
    char *sysfs_path = NULL;
2029
    bool ret = false;
O
Osier Yang 已提交
2030

2031
    if (virAsprintf(&sysfs_path, "%s/host%d",
O
Osier Yang 已提交
2032
                    sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH,
2033
                    host) < 0)
2034
        return false;
O
Osier Yang 已提交
2035

2036
    if (virFileExists(sysfs_path))
2037
        ret = true;
O
Osier Yang 已提交
2038 2039 2040 2041 2042

    VIR_FREE(sysfs_path);
    return ret;
}

2043
bool
O
Osier Yang 已提交
2044 2045 2046 2047 2048
virIsCapableVport(const char *sysfs_prefix,
                  int host)
{
    char *scsi_host_path = NULL;
    char *fc_host_path = NULL;
E
Eric Blake 已提交
2049
    bool ret = false;
O
Osier Yang 已提交
2050 2051

    if (virAsprintf(&fc_host_path,
2052
                    "%s/host%d/%s",
O
Osier Yang 已提交
2053 2054
                    sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH,
                    host,
2055
                    "vport_create") < 0)
2056
        return false;
O
Osier Yang 已提交
2057 2058

    if (virAsprintf(&scsi_host_path,
2059
                    "%s/host%d/%s",
O
Osier Yang 已提交
2060 2061
                    sysfs_prefix ? sysfs_prefix : SYSFS_SCSI_HOST_PATH,
                    host,
2062
                    "vport_create") < 0)
O
Osier Yang 已提交
2063 2064
        goto cleanup;

2065 2066
    if (virFileExists(fc_host_path) ||
        virFileExists(scsi_host_path))
2067
        ret = true;
O
Osier Yang 已提交
2068

2069
 cleanup:
O
Osier Yang 已提交
2070 2071 2072 2073
    VIR_FREE(fc_host_path);
    VIR_FREE(scsi_host_path);
    return ret;
}
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098

int
virManageVport(const int parent_host,
               const char *wwpn,
               const char *wwnn,
               int operation)
{
    int ret = -1;
    char *operation_path = NULL, *vport_name = NULL;
    const char *operation_file = NULL;

    switch (operation) {
    case VPORT_CREATE:
        operation_file = "vport_create";
        break;
    case VPORT_DELETE:
        operation_file = "vport_delete";
        break;
    default:
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("Invalid vport operation (%d)"), operation);
        goto cleanup;
    }

    if (virAsprintf(&operation_path,
2099
                    "%s/host%d/%s",
2100 2101
                    SYSFS_FC_HOST_PATH,
                    parent_host,
2102
                    operation_file) < 0)
2103 2104 2105 2106 2107
        goto cleanup;

    if (!virFileExists(operation_path)) {
        VIR_FREE(operation_path);
        if (virAsprintf(&operation_path,
2108
                        "%s/host%d/%s",
2109 2110
                        SYSFS_SCSI_HOST_PATH,
                        parent_host,
2111
                        operation_file) < 0)
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
            goto cleanup;

        if (!virFileExists(operation_path)) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("vport operation '%s' is not supported for host%d"),
                           operation_file, parent_host);
            goto cleanup;
        }
    }

    if (virAsprintf(&vport_name,
                    "%s:%s",
2124
                    wwpn,
2125
                    wwnn) < 0)
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
        goto cleanup;

    if (virFileWriteStr(operation_path, vport_name, 0) == 0)
        ret = 0;
    else
        virReportSystemError(errno,
                             _("Write of '%s' to '%s' during "
                               "vport create/delete failed"),
                             vport_name, operation_path);

2136
 cleanup:
2137 2138 2139 2140
    VIR_FREE(vport_name);
    VIR_FREE(operation_path);
    return ret;
}
2141 2142 2143

/* virGetHostNameByWWN:
 *
2144
 * Iterate over the sysfs tree to get FC host name (e.g. host5)
O
Osier Yang 已提交
2145 2146 2147 2148
 * by the provided "wwnn,wwpn" pair.
 *
 * Returns the FC host name which must be freed by the caller,
 * or NULL on failure.
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
 */
char *
virGetFCHostNameByWWN(const char *sysfs_prefix,
                      const char *wwnn,
                      const char *wwpn)
{
    const char *prefix = sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH;
    struct dirent *entry = NULL;
    DIR *dir = NULL;
    char *wwnn_path = NULL;
    char *wwpn_path = NULL;
    char *wwnn_buf = NULL;
    char *wwpn_buf = NULL;
    char *p;
    char *ret = NULL;

    if (!(dir = opendir(prefix))) {
        virReportSystemError(errno,
                             _("Failed to opendir path '%s'"),
                             prefix);
        return NULL;
    }

# define READ_WWN(wwn_path, buf)                      \
    do {                                              \
        if (virFileReadAll(wwn_path, 1024, &buf) < 0) \
            goto cleanup;                             \
        if ((p = strchr(buf, '\n')))                  \
            *p = '\0';                                \
        if (STRPREFIX(buf, "0x"))                     \
            p = buf + strlen("0x");                   \
        else                                          \
            p = buf;                                  \
    } while (0)

E
Eric Blake 已提交
2184
    while (virDirRead(dir, &entry, prefix) > 0) {
2185 2186 2187
        if (entry->d_name[0] == '.')
            continue;

2188
        if (virAsprintf(&wwnn_path, "%s/%s/node_name", prefix,
2189
                        entry->d_name) < 0)
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
            goto cleanup;

        if (!virFileExists(wwnn_path)) {
            VIR_FREE(wwnn_path);
            continue;
        }

        READ_WWN(wwnn_path, wwnn_buf);

        if (STRNEQ(wwnn, p)) {
            VIR_FREE(wwnn_buf);
            VIR_FREE(wwnn_path);
            continue;
        }

2205
        if (virAsprintf(&wwpn_path, "%s/%s/port_name", prefix,
2206
                        entry->d_name) < 0)
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
            goto cleanup;

        if (!virFileExists(wwpn_path)) {
            VIR_FREE(wwnn_buf);
            VIR_FREE(wwnn_path);
            VIR_FREE(wwpn_path);
            continue;
        }

        READ_WWN(wwpn_path, wwpn_buf);

        if (STRNEQ(wwpn, p)) {
            VIR_FREE(wwnn_path);
            VIR_FREE(wwpn_path);
            VIR_FREE(wwnn_buf);
            VIR_FREE(wwpn_buf);
            continue;
        }

2226
        ignore_value(VIR_STRDUP(ret, entry->d_name));
2227 2228 2229
        break;
    }

2230
 cleanup:
2231 2232 2233 2234 2235 2236 2237 2238
# undef READ_WWN
    closedir(dir);
    VIR_FREE(wwnn_path);
    VIR_FREE(wwpn_path);
    VIR_FREE(wwnn_buf);
    VIR_FREE(wwpn_buf);
    return ret;
}
2239 2240 2241 2242 2243 2244

# define PORT_STATE_ONLINE "Online"

/* virFindFCHostCapableVport:
 *
 * Iterate over the sysfs and find out the first online HBA which
O
Osier Yang 已提交
2245 2246
 * supports vport, and not saturated. Returns the host name (e.g.
 * host5) on success, or NULL on failure.
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
 */
char *
virFindFCHostCapableVport(const char *sysfs_prefix)
{
    const char *prefix = sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH;
    DIR *dir = NULL;
    struct dirent *entry = NULL;
    char *max_vports = NULL;
    char *vports = NULL;
    char *state = NULL;
    char *ret = NULL;

    if (!(dir = opendir(prefix))) {
        virReportSystemError(errno,
                             _("Failed to opendir path '%s'"),
                             prefix);
        return NULL;
    }

E
Eric Blake 已提交
2266
    while (virDirRead(dir, &entry, prefix) > 0) {
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
        unsigned int host;
        char *p = NULL;

        if (entry->d_name[0] == '.')
            continue;

        p = entry->d_name + strlen("host");
        if (virStrToLong_ui(p, NULL, 10, &host) == -1) {
            VIR_DEBUG("Failed to parse host number from '%s'",
                      entry->d_name);
            continue;
        }

O
Osier Yang 已提交
2280
        if (!virIsCapableVport(prefix, host))
2281 2282
            continue;

O
Osier Yang 已提交
2283
        if (virReadFCHost(prefix, host, "port_state", &state) < 0) {
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
             VIR_DEBUG("Failed to read port_state for host%d", host);
             continue;
        }

        /* Skip the not online FC host */
        if (STRNEQ(state, PORT_STATE_ONLINE)) {
            VIR_FREE(state);
            continue;
        }
        VIR_FREE(state);

O
Osier Yang 已提交
2295
        if (virReadFCHost(prefix, host, "max_npiv_vports", &max_vports) < 0) {
2296 2297 2298 2299
             VIR_DEBUG("Failed to read max_npiv_vports for host%d", host);
             continue;
        }

O
Osier Yang 已提交
2300
        if (virReadFCHost(prefix, host, "npiv_vports_inuse", &vports) < 0) {
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
             VIR_DEBUG("Failed to read npiv_vports_inuse for host%d", host);
             VIR_FREE(max_vports);
             continue;
        }

        /* Compare from the strings directly, instead of converting
         * the strings to integers first
         */
        if ((strlen(max_vports) >= strlen(vports)) ||
            ((strlen(max_vports) == strlen(vports)) &&
             strcmp(max_vports, vports) > 0)) {
2312
            ignore_value(VIR_STRDUP(ret, entry->d_name));
2313 2314 2315 2316 2317 2318 2319
            goto cleanup;
        }

        VIR_FREE(max_vports);
        VIR_FREE(vports);
    }

2320
 cleanup:
2321 2322 2323 2324 2325
    closedir(dir);
    VIR_FREE(max_vports);
    VIR_FREE(vports);
    return ret;
}
2326
#else
2327 2328 2329
int
virReadSCSIUniqueId(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                    int host ATTRIBUTE_UNUSED,
2330
                    int *result ATTRIBUTE_UNUSED)
2331 2332 2333 2334 2335
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return -1;
}

2336 2337 2338 2339
char *
virFindSCSIHostByPCI(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                     const char *parentaddr ATTRIBUTE_UNUSED,
                     unsigned int unique_id ATTRIBUTE_UNUSED)
2340 2341 2342 2343 2344 2345 2346 2347
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return NULL;
}

int
virGetSCSIHostNumber(const char *adapter_name ATTRIBUTE_UNUSED,
                     unsigned int *result ATTRIBUTE_UNUSED)
2348 2349
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2350
    return -1;
2351 2352 2353 2354 2355 2356 2357 2358
}

char *
virGetSCSIHostNameByParentaddr(unsigned int domain ATTRIBUTE_UNUSED,
                               unsigned int bus ATTRIBUTE_UNUSED,
                               unsigned int slot ATTRIBUTE_UNUSED,
                               unsigned int function ATTRIBUTE_UNUSED,
                               unsigned int unique_id ATTRIBUTE_UNUSED)
2359 2360
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2361
    return NULL;
2362 2363
}

2364 2365 2366 2367 2368 2369 2370 2371 2372
int
virReadFCHost(const char *sysfs_prefix ATTRIBUTE_UNUSED,
              int host ATTRIBUTE_UNUSED,
              const char *entry ATTRIBUTE_UNUSED,
              char **result ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return -1;
}
O
Osier Yang 已提交
2373

2374
bool
2375 2376
virIsCapableFCHost(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                   int host ATTRIBUTE_UNUSED)
O
Osier Yang 已提交
2377 2378
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2379
    return false;
O
Osier Yang 已提交
2380 2381
}

2382
bool
2383 2384
virIsCapableVport(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                  int host ATTRIBUTE_UNUSED)
O
Osier Yang 已提交
2385 2386
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2387
    return false;
O
Osier Yang 已提交
2388
}
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399

int
virManageVport(const int parent_host ATTRIBUTE_UNUSED,
               const char *wwpn ATTRIBUTE_UNUSED,
               const char *wwnn ATTRIBUTE_UNUSED,
               int operation ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return -1;
}

2400 2401 2402 2403 2404 2405 2406 2407 2408
char *
virGetFCHostNameByWWN(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                      const char *wwnn ATTRIBUTE_UNUSED,
                      const char *wwpn ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return NULL;
}

2409 2410 2411 2412 2413 2414 2415
char *
virFindFCHostCapableVport(const char *sysfs_prefix ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return NULL;
}

2416
#endif /* __linux__ */
2417

M
Martin Kletzander 已提交
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
/**
 * 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;

    if (VIR_STRDUP(tmp_label, label) < 0)
        goto cleanup;

    /* 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;

2468
 cleanup:
M
Martin Kletzander 已提交
2469 2470 2471 2472
    VIR_FREE(tmp_label);

    return rc;
}
2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484


/**
 * virGetEnvBlockSUID:
 * @name: the environment variable name
 *
 * Obtain an environment variable which is unsafe to
 * use when running setuid. If running setuid, a NULL
 * value will be returned
 */
const char *virGetEnvBlockSUID(const char *name)
{
2485
    return secure_getenv(name); /* exempt from syntax-check-rules */
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
}


/**
 * virGetEnvBlockSUID:
 * @name: the environment variable name
 *
 * Obtain an environment variable which is safe to
 * use when running setuid. The value will be returned
 * even when running setuid
 */
const char *virGetEnvAllowSUID(const char *name)
{
2499
    return getenv(name); /* exempt from syntax-check-rules */
2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
}


/**
 * virIsSUID:
 * Return a true value if running setuid. Does not
 * check for elevated capabilities bits.
 */
bool virIsSUID(void)
{
    return getuid() != geteuid();
}
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534


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;
    }
}
2535

2536 2537
#ifndef WIN32

2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
/**
 * virGetListenFDs:
 *
 * Parse LISTEN_PID and LISTEN_FDS passed from caller.
 *
 * Returns number of passed FDs.
 */
unsigned int
virGetListenFDs(void)
{
    const char *pidstr;
    const char *fdstr;
    size_t i = 0;
    unsigned long long procid;
    unsigned int nfds;

    VIR_DEBUG("Setting up networking from caller");

    if (!(pidstr = virGetEnvAllowSUID("LISTEN_PID"))) {
        VIR_DEBUG("No LISTEN_PID from caller");
        return 0;
    }

    if (virStrToLong_ull(pidstr, NULL, 10, &procid) < 0) {
        VIR_DEBUG("Malformed LISTEN_PID from caller %s", pidstr);
        return 0;
    }

    if ((pid_t)procid != getpid()) {
        VIR_DEBUG("LISTEN_PID %s is not for us %llu",
                  pidstr, (unsigned long long)getpid());
        return 0;
    }

    if (!(fdstr = virGetEnvAllowSUID("LISTEN_FDS"))) {
        VIR_DEBUG("No LISTEN_FDS from caller");
        return 0;
    }

    if (virStrToLong_ui(fdstr, NULL, 10, &nfds) < 0) {
        VIR_DEBUG("Malformed LISTEN_FDS from caller %s", fdstr);
        return 0;
    }

    unsetenv("LISTEN_PID");
    unsetenv("LISTEN_FDS");

    VIR_DEBUG("Got %u file descriptors", nfds);

    for (i = 0; i < nfds; i++) {
        int fd = STDERR_FILENO + i + 1;

        VIR_DEBUG("Disabling inheritance of passed FD %d", fd);

2592
        if (virSetInherit(fd, false) < 0)
2593 2594 2595 2596 2597
            VIR_WARN("Couldn't disable inheritance of passed FD %d", fd);
    }

    return nfds;
}
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607

#else /* WIN32 */

unsigned int
virGetListenFDs(void)
{
    return 0;
}

#endif /* WIN32 */
2608

P
Pavel Hrdina 已提交
2609
#ifndef WIN32
2610 2611 2612 2613
long virGetSystemPageSize(void)
{
    return sysconf(_SC_PAGESIZE);
}
P
Pavel Hrdina 已提交
2614 2615 2616 2617 2618 2619 2620
#else /* WIN32 */
long virGetSystemPageSize(void)
{
    errno = ENOSYS;
    return -1;
}
#endif /* WIN32 */
2621 2622 2623 2624 2625 2626 2627 2628

long virGetSystemPageSizeKB(void)
{
    long val = virGetSystemPageSize();
    if (val < 0)
        return val;
    return val / 1024;
}
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652

/**
 * 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;
}
2653 2654 2655 2656 2657


/**
 * virMemoryMaxValue
 *
2658
 * @capped: whether the value must fit into unsigned long
2659 2660 2661 2662 2663
 *   (long long is assumed otherwise)
 *
 * Returns the maximum possible memory value in bytes.
 */
unsigned long long
2664
virMemoryMaxValue(bool capped)
2665 2666 2667
{
    /* On 32-bit machines, our bound is 0xffffffff * KiB. On 64-bit
     * machines, our bound is off_t (2^63).  */
2668
    if (capped && sizeof(unsigned long) < sizeof(long long))
2669 2670 2671 2672
        return 1024ull * ULONG_MAX;
    else
        return LLONG_MAX;
}