virutil.c 52.1 KB
Newer Older
1
/*
2
 * virutil.c: common, generic utility functions
3
 *
4
 * Copyright (C) 2006-2013 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"
70
#include "virerror.h"
71
#include "virlog.h"
72
#include "virbuffer.h"
73
#include "viralloc.h"
74
#include "virthread.h"
E
Eric Blake 已提交
75
#include "verify.h"
76 77 78 79 80 81
#include "virfile.h"
#include "vircommand.h"
#include "nonblocking.h"
#include "virprocess.h"
#include "virstring.h"
#include "virutil.h"
82

83 84 85
#ifndef NSIG
# define NSIG 32
#endif
86

87 88
verify(sizeof(gid_t) <= sizeof(unsigned int) &&
       sizeof(uid_t) <= sizeof(unsigned int));
89

90
#define VIR_FROM_THIS VIR_FROM_NONE
91

92
#ifndef WIN32
93

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

107
#else /* WIN32 */
108

109
int virSetInherit(int fd ATTRIBUTE_UNUSED, bool inherit ATTRIBUTE_UNUSED)
110
{
111 112 113 114 115
    /* 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;
116 117
}

118
#endif /* WIN32 */
119

120 121
int virSetBlocking(int fd, bool blocking) {
    return set_nonblocking_flag(fd, !blocking);
122 123
}

124 125
int virSetNonBlock(int fd) {
    return virSetBlocking(fd, false);
126
}
127

128
int virSetCloseExec(int fd)
129
{
130
    return virSetInherit(fd, false);
131 132
}

133 134 135
int
virPipeReadUntilEOF(int outfd, int errfd,
                    char **outbuf, char **errbuf) {
136

137 138
    struct pollfd fds[2];
    int i;
139
    bool finished[2];
140

141 142 143
    fds[0].fd = outfd;
    fds[0].events = POLLIN;
    fds[0].revents = 0;
144
    finished[0] = false;
145 146 147
    fds[1].fd = errfd;
    fds[1].events = POLLIN;
    fds[1].revents = 0;
148
    finished[1] = false;
149

150
    while (!(finished[0] && finished[1])) {
151

152 153 154 155
        if (poll(fds, ARRAY_CARDINALITY(fds), -1) < 0) {
            if ((errno == EAGAIN) || (errno == EINTR))
                continue;
            goto pollerr;
156 157
        }

158 159 160
        for (i = 0; i < ARRAY_CARDINALITY(fds); ++i) {
            char data[1024], **buf;
            int got, size;
161

162 163 164
            if (!(fds[i].revents))
                continue;
            else if (fds[i].revents & POLLHUP)
165
                finished[i] = true;
166

167 168 169
            if (!(fds[i].revents & POLLIN)) {
                if (fds[i].revents & POLLHUP)
                    continue;
170

171 172 173 174
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("Unknown poll response."));
                goto error;
            }
175

176
            got = read(fds[i].fd, data, sizeof(data));
177

178
            if (got == sizeof(data))
179
                finished[i] = false;
A
Amy Griffis 已提交
180

181
            if (got == 0) {
182
                finished[i] = true;
183 184 185 186 187 188 189 190 191
                continue;
            }
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
                goto pollerr;
            }
A
Amy Griffis 已提交
192

193 194 195 196 197 198 199 200
            buf = ((fds[i].fd == outfd) ? outbuf : errbuf);
            size = (*buf ? strlen(*buf) : 0);
            if (VIR_REALLOC_N(*buf, size+got+1) < 0) {
                virReportOOMError();
                goto error;
            }
            memmove(*buf+size, data, got);
            (*buf)[size+got] = '\0';
A
Amy Griffis 已提交
201
        }
202
        continue;
203

204 205 206 207
    pollerr:
        virReportSystemError(errno,
                             "%s", _("poll error"));
        goto error;
208 209
    }

210
    return 0;
211

212 213 214 215
error:
    VIR_FREE(*outbuf);
    VIR_FREE(*errbuf);
    return -1;
216 217
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
/* 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;
    }
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246
/* 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) {
247 248
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("invalid scale %llu"), scale);
249 250 251 252 253 254 255 256 257 258 259 260 261 262
            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 {
263
            virReportError(VIR_ERR_INVALID_ARG,
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                         _("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:
288 289
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unknown suffix '%s'"), suffix);
290 291 292 293
            return -1;
        }
    }

G
Guannan Ren 已提交
294
    if (*value && *value > (limit / scale)) {
295 296
        virReportError(VIR_ERR_OVERFLOW, _("value too large: %llu%s"),
                       *value, suffix);
297 298 299 300 301 302
        return -1;
    }
    *value *= scale;
    return 0;
}

E
Eric Blake 已提交
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
/**
 * 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'))
320
        return -1;
321

J
Jim Meyering 已提交
322
    while (c_isdigit(*cur)) {
323 324 325 326
        unsigned int c = *cur - '0';

        if ((ret > INT_MAX / 10) ||
            ((ret == INT_MAX / 10) && (c > INT_MAX % 10)))
327
            return -1;
328 329 330 331
        ret = ret * 10 + c;
        cur++;
    }
    *str = cur;
332
    return ret;
333
}
334

335 336 337 338
/**
 * virParseVersionString:
 * @str: const char pointer to the version string
 * @version: unsigned long pointer to output the version number
339 340
 * @allowMissing: true to treat 3 like 3.0.0, false to error out on
 * missing minor or micro
341 342 343 344 345 346 347 348 349 350 351
 *
 * 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
352 353
virParseVersionString(const char *str, unsigned long *version,
                      bool allowMissing)
354
{
355
    unsigned int major, minor = 0, micro = 0;
356 357
    char *tmp;

358
    if (virStrToLong_ui(str, &tmp, 10, &major) < 0)
359 360
        return -1;

361 362 363
    if (!allowMissing && *tmp != '.')
        return -1;

364
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &minor) < 0)
365 366
        return -1;

367 368 369
    if (!allowMissing && *tmp != '.')
        return -1;

370
    if ((*tmp == '.') && virStrToLong_ui(tmp + 1, &tmp, 10, &micro) < 0)
371 372
        return -1;

373 374 375
    if (major > UINT_MAX / 1000000 || minor > 999 || micro > 999)
        return -1;

376 377 378 379 380
    *version = 1000000 * major + 1000 * minor + micro;

    return 0;
}

381 382 383 384 385
int virEnumFromString(const char *const*types,
                      unsigned int ntypes,
                      const char *type)
{
    unsigned int i;
386 387 388
    if (!type)
        return -1;

389
    for (i = 0; i < ntypes; i++)
390 391 392 393 394 395
        if (STREQ(types[i], type))
            return i;

    return -1;
}

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 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 440
/* 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;

441
    if ((ret = virAsprintf(strp, "%lf", number) < 0))
442 443 444 445 446 447 448 449
        goto error;

    lc = localeconv();
    radix = lc->decimal_point;
    tmp = strstr(*strp, radix);
    if (tmp) {
        *tmp = '.';
        if (strlen(radix) > 1)
450
            memmove(tmp + 1, tmp + strlen(radix), strlen(*strp) - (tmp - *strp));
451 452 453 454 455 456 457
    }

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

D
Daniel P. Berrange 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

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


488 489 490 491 492 493 494 495 496 497
const char *virEnumToString(const char *const*types,
                            unsigned int ntypes,
                            int type)
{
    if (type < 0 || type >= ntypes)
        return NULL;

    return types[type];
}

498 499 500
/* 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.
501 502 503 504 505 506
 * @param name The name of the device
 * @return name's index, or -1 on failure
 */
int virDiskNameToIndex(const char *name) {
    const char *ptr = NULL;
    int idx = 0;
507
    static char const* const drive_prefix[] = {"fd", "hd", "vd", "sd", "xvd", "ubd"};
508
    unsigned int i;
509

510 511 512
    for (i = 0; i < ARRAY_CARDINALITY(drive_prefix); i++) {
        if (STRPREFIX(name, drive_prefix[i])) {
            ptr = name + strlen(drive_prefix[i]);
513
            break;
514
        }
515 516
    }

517
    if (!ptr)
518 519
        return -1;

D
Daniel Veillard 已提交
520
    for (i = 0; *ptr; i++) {
J
Jim Meyering 已提交
521
        if (!c_islower(*ptr))
522
            break;
523

524
        idx = (idx + (i < 1 ? 0 : 1)) * 26;
525 526 527 528
        idx += *ptr - 'a';
        ptr++;
    }

529 530 531 532 533
    /* Count the trailing digits.  */
    size_t n_digits = strspn(ptr, "0123456789");
    if (ptr[n_digits] != '\0')
        return -1;

534 535
    return idx;
}
G
Guido Günther 已提交
536

537 538 539 540 541 542
char *virIndexToDiskName(int idx, const char *prefix)
{
    char *name = NULL;
    int i, k, offset;

    if (idx < 0) {
543 544
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Disk index %d is negative"), idx);
545 546 547 548 549 550 551 552
        return NULL;
    }

    for (i = 0, k = idx; k >= 0; ++i, k = k / 26 - 1) { }

    offset = strlen(prefix);

    if (VIR_ALLOC_N(name, offset + i + 1)) {
553
        virReportOOMError();
554 555 556 557 558 559 560 561 562 563 564 565 566
        return NULL;
    }

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

    for (i = i - 1, k = idx; k >= 0; --i, k = k / 26 - 1) {
        name[offset + i] = 'a' + (k % 26);
    }

    return name;
}

567
#ifndef AI_CANONIDN
568
# define AI_CANONIDN 0
569 570
#endif

C
Chris Lalancette 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
/* 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
586
 *     b)  getaddrinfo() fails or resolves to localhost - in this case, the
587 588 589
 *         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 已提交
590
 */
591
char *virGetHostname(void)
592 593 594
{
    int r;
    char hostname[HOST_NAME_MAX+1], *result;
C
Chris Lalancette 已提交
595
    struct addrinfo hints, *info;
596

597
    r = gethostname(hostname, sizeof(hostname));
598
    if (r == -1) {
599 600
        virReportSystemError(errno,
                             "%s", _("failed to determine host name"));
601
        return NULL;
602
    }
603 604
    NUL_TERMINATE(hostname);

C
Chris Lalancette 已提交
605 606 607 608 609 610 611
    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.
         */
612 613
        ignore_value(VIR_STRDUP(result, hostname));
        goto cleanup;
C
Chris Lalancette 已提交
614 615 616 617 618 619
    }

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

620 621 622 623
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags = AI_CANONNAME|AI_CANONIDN;
    hints.ai_family = AF_UNSPEC;
    r = getaddrinfo(hostname, NULL, &hints, &info);
624
    if (r != 0) {
625 626
        VIR_WARN("getaddrinfo failed for '%s': %s",
                 hostname, gai_strerror(r));
627 628
        ignore_value(VIR_STRDUP(result, hostname));
        goto cleanup;
629
    }
630

631
    /* Tell static analyzers about getaddrinfo semantics.  */
632
    sa_assert(info);
633

C
Chris Lalancette 已提交
634 635 636 637 638 639
    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
         */
640
        ignore_value(VIR_STRDUP(result, hostname));
C
Chris Lalancette 已提交
641 642
    else
        /* Caller frees this string. */
643
        ignore_value(VIR_STRDUP(result, info->ai_canonname));
644

C
Chris Lalancette 已提交
645
    freeaddrinfo(info);
646

647
cleanup:
C
Chris Lalancette 已提交
648
    if (result == NULL)
649
        virReportOOMError();
650 651 652
    return result;
}

653
#ifdef HAVE_GETPWUID_R
654 655 656 657 658
enum {
    VIR_USER_ENT_DIRECTORY,
    VIR_USER_ENT_NAME,
};

659
static char *virGetUserEnt(uid_t uid,
660
                           int field)
661 662 663 664
{
    char *strbuf;
    char *ret;
    struct passwd pwbuf;
665
    struct passwd *pw = NULL;
666 667
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
668
    int rc;
669

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

    if (VIR_ALLOC_N(strbuf, strbuflen) < 0) {
675
        virReportOOMError();
676 677 678
        return NULL;
    }

679 680 681 682 683 684 685
    /*
     * 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.
     */
686 687 688 689 690 691 692 693 694
    while ((rc = getpwuid_r(uid, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0) {
            virReportOOMError();
            VIR_FREE(strbuf);
            return NULL;
        }
    }
    if (rc != 0 || pw == NULL) {
        virReportSystemError(rc,
E
Eric Blake 已提交
695 696
                             _("Failed to find user record for uid '%u'"),
                             (unsigned int) uid);
697 698 699 700
        VIR_FREE(strbuf);
        return NULL;
    }

701 702
    ignore_value(VIR_STRDUP(ret, field == VIR_USER_ENT_DIRECTORY ?
                            pw->pw_dir : pw->pw_name));
703 704 705
    VIR_FREE(strbuf);
    return ret;
}
706

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
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;

    if (VIR_ALLOC_N(strbuf, strbuflen) < 0) {
        virReportOOMError();
        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) {
            virReportOOMError();
            VIR_FREE(strbuf);
            return NULL;
        }
    }
    if (rc != 0 || gr == NULL) {
        virReportSystemError(rc,
                             _("Failed to find group record for gid '%u'"),
                             (unsigned int) gid);
        VIR_FREE(strbuf);
        return NULL;
    }

748
    ignore_value(VIR_STRDUP(ret, gr->gr_name));
749 750 751 752
    VIR_FREE(strbuf);
    return ret;
}

753
char *virGetUserDirectory(void)
754
{
755
    return virGetUserEnt(geteuid(), VIR_USER_ENT_DIRECTORY);
756 757
}

758
static char *virGetXDGDirectory(const char *xdgenvname, const char *xdgdefdir)
759
{
760
    const char *path = getenv(xdgenvname);
761
    char *ret = NULL;
762
    char *home = NULL;
763 764

    if (path && path[0]) {
765
        if (virAsprintf(&ret, "%s/libvirt", path) < 0)
766 767
            goto no_memory;
    } else {
768
        home = virGetUserEnt(geteuid(), VIR_USER_ENT_DIRECTORY);
769
        if (virAsprintf(&ret, "%s/%s/libvirt", home, xdgdefdir) < 0)
770 771 772 773 774 775 776 777 778 779 780
            goto no_memory;
    }

 cleanup:
    VIR_FREE(home);
    return ret;
 no_memory:
    virReportOOMError();
    goto cleanup;
}

781
char *virGetUserConfigDirectory(void)
782
{
783
    return virGetXDGDirectory("XDG_CONFIG_HOME", ".config");
784 785
}

786
char *virGetUserCacheDirectory(void)
787
{
788
     return virGetXDGDirectory("XDG_CACHE_HOME", ".cache");
789 790
}

791
char *virGetUserRuntimeDirectory(void)
792
{
793
    const char *path = getenv("XDG_RUNTIME_DIR");
794 795

    if (!path || !path[0]) {
796
        return virGetUserCacheDirectory();
797 798 799
    } else {
        char *ret;

800
        if (virAsprintf(&ret, "%s/libvirt", path) < 0) {
801 802 803 804 805 806 807 808
            virReportOOMError();
            return NULL;
        }

        return ret;
    }
}

809
char *virGetUserName(uid_t uid)
810
{
811
    return virGetUserEnt(uid, VIR_USER_ENT_NAME);
812 813
}

814 815 816 817 818
char *virGetGroupName(gid_t gid)
{
    return virGetGroupEnt(gid);
}

819 820 821 822 823
/* 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)
824
{
825
    char *strbuf = NULL;
826 827
    struct passwd pwbuf;
    struct passwd *pw = NULL;
828 829
    long val = sysconf(_SC_GETPW_R_SIZE_MAX);
    size_t strbuflen = val;
830
    int rc;
831
    int ret = -1;
832

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

    if (VIR_ALLOC_N(strbuf, strbuflen) < 0) {
838
        virReportOOMError();
839
        goto cleanup;
840 841
    }

842 843 844
    while ((rc = getpwnam_r(name, &pwbuf, strbuf, strbuflen, &pw)) == ERANGE) {
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0) {
            virReportOOMError();
845
            goto cleanup;
846 847
        }
    }
848 849

    if (!pw) {
850 851 852 853 854
        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 */
855
            VIR_WARN("User record for user '%s' was not found: %s",
856 857 858
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

859 860
        ret = 1;
        goto cleanup;
861 862 863
    }

    *uid = pw->pw_uid;
864
    ret = 0;
865

866
cleanup:
867 868
    VIR_FREE(strbuf);

869
    return ret;
870 871
}

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
/* 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;
}
902

903 904 905 906 907
/* 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)
908
{
909
    char *strbuf = NULL;
910 911
    struct group grbuf;
    struct group *gr = NULL;
912 913
    long val = sysconf(_SC_GETGR_R_SIZE_MAX);
    size_t strbuflen = val;
914
    int rc;
915
    int ret = -1;
916

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

    if (VIR_ALLOC_N(strbuf, strbuflen) < 0) {
922
        virReportOOMError();
923
        goto cleanup;
924 925
    }

926 927 928
    while ((rc = getgrnam_r(name, &grbuf, strbuf, strbuflen, &gr)) == ERANGE) {
        if (VIR_RESIZE_N(strbuf, strbuflen, strbuflen, strbuflen) < 0) {
            virReportOOMError();
929
            goto cleanup;
930 931
        }
    }
932 933

    if (!gr) {
934 935 936 937 938
        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 */
939
            VIR_WARN("Group record for user '%s' was not found: %s",
940 941 942
                     name, virStrerror(rc, buf, sizeof(buf)));
        }

943 944
        ret = 1;
        goto cleanup;
945 946 947
    }

    *gid = gr->gr_gid;
948
    ret = 0;
949

950
cleanup:
951 952
    VIR_FREE(strbuf);

953
    return ret;
954
}
955

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
/* 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 已提交
986 987 988

/* Set the real and effective uid and gid to the given values, and call
 * initgroups so that the process has all the assumed group membership of
989 990
 * that uid. return 0 on success, -1 on failure (the original system error
 * remains in errno).
L
Laine Stump 已提交
991 992 993 994
 */
int
virSetUIDGID(uid_t uid, gid_t gid)
{
995
    int err;
996
    char *buf = NULL;
997

998
    if (gid != (gid_t)-1) {
L
Laine Stump 已提交
999
        if (setregid(gid, gid) < 0) {
1000
            virReportSystemError(err = errno,
1001
                                 _("cannot change to '%u' group"),
E
Eric Blake 已提交
1002
                                 (unsigned int) gid);
1003
            goto error;
L
Laine Stump 已提交
1004 1005 1006
        }
    }

1007
    if (uid != (uid_t)-1) {
L
Laine Stump 已提交
1008 1009 1010
# ifdef HAVE_INITGROUPS
        struct passwd pwd, *pwd_result;
        size_t bufsize;
1011
        int rc;
L
Laine Stump 已提交
1012 1013 1014 1015 1016 1017 1018

        bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
        if (bufsize == -1)
            bufsize = 16384;

        if (VIR_ALLOC_N(buf, bufsize) < 0) {
            virReportOOMError();
1019 1020
            err = ENOMEM;
            goto error;
L
Laine Stump 已提交
1021
        }
1022 1023 1024 1025
        while ((rc = getpwuid_r(uid, &pwd, buf, bufsize,
                                &pwd_result)) == ERANGE) {
            if (VIR_RESIZE_N(buf, bufsize, bufsize, bufsize) < 0) {
                virReportOOMError();
1026 1027
                err = ENOMEM;
                goto error;
1028 1029
            }
        }
1030 1031

        if (rc) {
1032
            virReportSystemError(err = rc, _("cannot getpwuid_r(%u)"),
E
Eric Blake 已提交
1033
                                 (unsigned int) uid);
1034
            goto error;
L
Laine Stump 已提交
1035
        }
1036 1037 1038 1039

        if (!pwd_result) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("getpwuid_r failed to retrieve data "
1040
                             "for uid '%u'"),
1041 1042 1043 1044 1045
                           (unsigned int) uid);
            err = EINVAL;
            goto error;
        }

L
Laine Stump 已提交
1046
        if (initgroups(pwd.pw_name, pwd.pw_gid) < 0) {
1047
            virReportSystemError(err = errno,
L
Laine Stump 已提交
1048
                                 _("cannot initgroups(\"%s\", %d)"),
E
Eric Blake 已提交
1049
                                 pwd.pw_name, (unsigned int) pwd.pw_gid);
1050
            goto error;
L
Laine Stump 已提交
1051 1052 1053
        }
# endif
        if (setreuid(uid, uid) < 0) {
1054
            virReportSystemError(err = errno,
1055
                                 _("cannot change to uid to '%u'"),
E
Eric Blake 已提交
1056
                                 (unsigned int) uid);
1057
            goto error;
L
Laine Stump 已提交
1058 1059
        }
    }
1060 1061

    VIR_FREE(buf);
L
Laine Stump 已提交
1062
    return 0;
1063 1064

error:
1065
    VIR_FREE(buf);
1066 1067
    errno = err;
    return -1;
L
Laine Stump 已提交
1068 1069
}

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
#else /* ! HAVE_GETPWUID_R */

# 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) {
1084 1085
        if (SHGetPathFromIDList(pidl, buf) && VIR_STRDUP(*path, buf) < 0)
            ret = -1;
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        CoTaskMemFree(pidl);
    }
    return ret;
}

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

    *path = NULL;

    if (GetWindowsDirectory(windowsdir, ARRAY_CARDINALITY(windowsdir)))
    {
        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:\\");
    }

1114
    return VIR_STRDUP(*path, windowsdir) < 0 ? -1 : 0;
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
}



char *
virGetUserDirectory(void)
{
    const char *dir;
    char *ret;

    dir = getenv("HOME");

    /* 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;
1139
        while ((p = strchr(dir, '/')) != NULL)
1140 1141 1142 1143 1144 1145 1146
            *p = '\\';
    }

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

1147 1148
    if (VIR_STRDUP(ret, dir) < 0)
        return NULL;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

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

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

    if (!ret) {
1159 1160
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine home directory"));
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
        return NULL;
    }

    return ret;
}

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

1174
    if (!ret) {
1175 1176
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        return NULL;
    }
    return ret;
}

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

    if (!ret) {
1190 1191
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to determine config directory"));
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        return NULL;
    }
    return ret;
}

char *
virGetUserRuntimeDirectory(void)
{
    return virGetUserCacheDirectory();
}
# else /* !HAVE_GETPWUID_R && !WIN32 */
1203
char *
1204
virGetUserDirectory(void)
1205
{
1206 1207
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserDirectory is not available"));
1208 1209 1210 1211

    return NULL;
}

1212 1213 1214
char *
virGetUserConfigDirectory(void)
{
1215 1216
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserConfigDirectory is not available"));
1217 1218 1219 1220 1221 1222 1223

    return NULL;
}

char *
virGetUserCacheDirectory(void)
{
1224 1225
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserCacheDirectory is not available"));
1226 1227 1228 1229 1230 1231 1232

    return NULL;
}

char *
virGetUserRuntimeDirectory(void)
{
1233 1234
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserRuntimeDirectory is not available"));
1235 1236 1237 1238 1239

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

1240 1241 1242
char *
virGetUserName(uid_t uid ATTRIBUTE_UNUSED)
{
1243 1244
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserName is not available"));
1245 1246 1247 1248 1249 1250 1251

    return NULL;
}

int virGetUserID(const char *name ATTRIBUTE_UNUSED,
                 uid_t *uid ATTRIBUTE_UNUSED)
{
1252 1253
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetUserID is not available"));
1254 1255 1256 1257 1258 1259 1260 1261

    return 0;
}


int virGetGroupID(const char *name ATTRIBUTE_UNUSED,
                  gid_t *gid ATTRIBUTE_UNUSED)
{
1262 1263
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupID is not available"));
1264 1265 1266

    return 0;
}
L
Laine Stump 已提交
1267 1268 1269 1270 1271

int
virSetUIDGID(uid_t uid ATTRIBUTE_UNUSED,
             gid_t gid ATTRIBUTE_UNUSED)
{
1272 1273
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virSetUIDGID is not available"));
L
Laine Stump 已提交
1274 1275
    return -1;
}
1276 1277 1278 1279

char *
virGetGroupName(gid_t gid ATTRIBUTE_UNUSED)
{
1280 1281
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   "%s", _("virGetGroupName is not available"));
1282 1283 1284

    return NULL;
}
1285
#endif /* HAVE_GETPWUID_R */
1286

1287 1288 1289 1290 1291 1292 1293
#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
1294 1295
virSetUIDGIDWithCaps(uid_t uid, gid_t gid, unsigned long long capBits,
                     bool clearExistingCaps)
1296 1297 1298
{
    int ii, capng_ret, ret = -1;
    bool need_setgid = false, need_setuid = false;
1299
    bool need_setpcap = false;
1300

1301 1302 1303 1304
    /* 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.
1305 1306
     */

1307
    if (clearExistingCaps || (uid != (uid_t)-1 && uid != 0))
1308
       capng_clear(CAPNG_SELECT_BOTH);
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339

    for (ii = 0; ii <= CAP_LAST_CAP; ii++) {
        if (capBits & (1ULL << ii)) {
            capng_update(CAPNG_ADD,
                         CAPNG_EFFECTIVE|CAPNG_INHERITABLE|
                         CAPNG_PERMITTED|CAPNG_BOUNDING_SET,
                         ii);
        }
    }

    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 */
1340
    if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0)) {
1341 1342 1343 1344 1345 1346
        virReportSystemError(errno, "%s",
                             _("prctl failed to set KEEPCAPS"));
        goto cleanup;
    }

    /* Change to the temp capabilities */
1347
    if ((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0) {
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
        /* 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;
        }
1363 1364 1365 1366 1367 1368
    }

    if (virSetUIDGID(uid, gid) < 0)
        goto cleanup;

    /* Tell it we are done keeping capabilities */
1369
    if (prctl(PR_SET_KEEPCAPS, 0, 0, 0, 0)) {
1370 1371 1372 1373 1374
        virReportSystemError(errno, "%s",
                             _("prctl failed to reset KEEPCAPS"));
        goto cleanup;
    }

1375 1376 1377 1378 1379 1380
    /* 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);

1381 1382 1383 1384 1385 1386 1387 1388 1389
    /* 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);

1390
    if (((capng_ret = capng_apply(CAPNG_SELECT_CAPS)) < 0)) {
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot apply process capabilities %d"), capng_ret);
        ret = -1;
        goto cleanup;
    }

    ret = 0;
cleanup:
    return ret;
}

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

int
virSetUIDGIDWithCaps(uid_t uid, gid_t gid,
1410 1411
                     unsigned long long capBits ATTRIBUTE_UNUSED,
                     bool clearExistingCaps ATTRIBUTE_UNUSED)
1412 1413 1414 1415 1416
{
    return virSetUIDGID(uid, gid);
}
#endif

1417

1418
#if defined(UDEVADM) || defined(UDEVSETTLE)
1419
void virFileWaitForDevices(void)
D
Daniel P. Berrange 已提交
1420
{
1421
# ifdef UDEVADM
D
Daniel P. Berrange 已提交
1422
    const char *const settleprog[] = { UDEVADM, "settle", NULL };
1423
# else
D
Daniel P. Berrange 已提交
1424
    const char *const settleprog[] = { UDEVSETTLE, NULL };
1425
# endif
D
Daniel P. Berrange 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    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.
     */
1437
    if (virRun(settleprog, &exitstatus) < 0)
1438
    {}
D
Daniel P. Berrange 已提交
1439
}
1440
#else
1441
void virFileWaitForDevices(void) {}
D
Daniel P. Berrange 已提交
1442
#endif
1443

1444
#if HAVE_LIBDEVMAPPER_H
1445
bool
1446
virIsDevMapperDevice(const char *dev_name)
1447 1448 1449
{
    struct stat buf;

1450
    if (!stat(dev_name, &buf) &&
1451 1452 1453 1454 1455 1456
        S_ISBLK(buf.st_mode) &&
        dm_is_dm_major(major(buf.st_rdev)))
            return true;

    return false;
}
1457
#else
1458
bool virIsDevMapperDevice(const char *dev_name ATTRIBUTE_UNUSED)
1459 1460 1461 1462
{
    return false;
}
#endif
O
Osier Yang 已提交
1463 1464 1465 1466

bool
virValidateWWN(const char *wwn) {
    int i;
1467
    const char *p = wwn;
O
Osier Yang 已提交
1468

1469 1470 1471 1472 1473 1474
    if (STRPREFIX(wwn, "0x")) {
        p += 2;
    }

    for (i = 0; p[i]; i++) {
        if (!c_isxdigit(p[i]))
O
Osier Yang 已提交
1475
            break;
1476
    }
O
Osier Yang 已提交
1477

1478
    if (i != 16 || p[i]) {
O
Osier Yang 已提交
1479 1480 1481 1482 1483 1484 1485
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed wwn: %s"));
        return false;
    }

    return true;
}
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497

bool
virStrIsPrint(const char *str)
{
    int i;

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

    return true;
}
1498 1499 1500 1501 1502 1503 1504

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

1505
    if (stat(path, &sb) < 0)
1506 1507
        return -errno;

1508
    if (!S_ISBLK(sb.st_mode))
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
        return -EINVAL;

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

    return 0;
}
#else
int
E
Eric Blake 已提交
1520 1521 1522
virGetDeviceID(const char *path ATTRIBUTE_UNUSED,
               int *maj ATTRIBUTE_UNUSED,
               int *min ATTRIBUTE_UNUSED)
1523 1524 1525 1526 1527 1528 1529 1530
{

    return -ENOSYS;
}
#endif

#define SYSFS_DEV_BLOCK_PATH "/sys/dev/block"

1531
char *
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
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;
    }

    if (virAsprintf(&sysfs_path, "%s/%d:%d/queue/unpriv_sgio",
                    sysfs_dir ? sysfs_dir : SYSFS_DEV_BLOCK_PATH,
                    maj, min) < 0) {
        virReportOOMError();
        return NULL;
    }

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

    if (virAsprintf(&val, "%d", unpriv_sgio) < 0) {
        virReportOOMError();
        goto cleanup;
    }

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

    ret = 0;
cleanup:
    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;
cleanup:
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}
1629 1630 1631

#ifdef __linux__
# define SYSFS_FC_HOST_PATH "/sys/class/fc_host/"
O
Osier Yang 已提交
1632
# define SYSFS_SCSI_HOST_PATH "/sys/class/scsi_host/"
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 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674

/* 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,
                    host, entry) < 0) {
        virReportOOMError();
        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 已提交
1675
    if (VIR_STRDUP(*result, p) < 0)
1676 1677 1678 1679 1680 1681 1682 1683
        goto cleanup;

    ret = 0;
cleanup:
    VIR_FREE(sysfs_path);
    VIR_FREE(buf);
    return ret;
}
O
Osier Yang 已提交
1684

1685
bool
O
Osier Yang 已提交
1686 1687 1688 1689
virIsCapableFCHost(const char *sysfs_prefix,
                   int host)
{
    char *sysfs_path = NULL;
1690
    bool ret = false;
O
Osier Yang 已提交
1691

1692
    if (virAsprintf(&sysfs_path, "%s/host%d",
O
Osier Yang 已提交
1693 1694 1695
                    sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH,
                    host) < 0) {
        virReportOOMError();
1696
        return false;
O
Osier Yang 已提交
1697 1698 1699
    }

    if (access(sysfs_path, F_OK) == 0)
1700
        ret = true;
O
Osier Yang 已提交
1701 1702 1703 1704 1705

    VIR_FREE(sysfs_path);
    return ret;
}

1706
bool
O
Osier Yang 已提交
1707 1708 1709 1710 1711
virIsCapableVport(const char *sysfs_prefix,
                  int host)
{
    char *scsi_host_path = NULL;
    char *fc_host_path = NULL;
1712
    int ret = false;
O
Osier Yang 已提交
1713 1714

    if (virAsprintf(&fc_host_path,
1715
                    "%s/host%d/%s",
O
Osier Yang 已提交
1716 1717 1718 1719
                    sysfs_prefix ? sysfs_prefix : SYSFS_FC_HOST_PATH,
                    host,
                    "vport_create") < 0) {
        virReportOOMError();
1720
        return false;
O
Osier Yang 已提交
1721 1722 1723
    }

    if (virAsprintf(&scsi_host_path,
1724
                    "%s/host%d/%s",
O
Osier Yang 已提交
1725 1726 1727 1728 1729 1730 1731 1732 1733
                    sysfs_prefix ? sysfs_prefix : SYSFS_SCSI_HOST_PATH,
                    host,
                    "vport_create") < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if ((access(fc_host_path, F_OK) == 0) ||
        (access(scsi_host_path, F_OK) == 0))
1734
        ret = true;
O
Osier Yang 已提交
1735 1736 1737 1738 1739 1740

cleanup:
    VIR_FREE(fc_host_path);
    VIR_FREE(scsi_host_path);
    return ret;
}
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765

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,
1766
                    "%s/host%d/%s",
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
                    SYSFS_FC_HOST_PATH,
                    parent_host,
                    operation_file) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if (!virFileExists(operation_path)) {
        VIR_FREE(operation_path);
        if (virAsprintf(&operation_path,
1777
                        "%s/host%d/%s",
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
                        SYSFS_SCSI_HOST_PATH,
                        parent_host,
                        operation_file) < 0) {
            virReportOOMError();
            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",
1795 1796
                    wwpn,
                    wwnn) < 0) {
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
        virReportOOMError();
        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);

cleanup:
    VIR_FREE(vport_name);
    VIR_FREE(operation_path);
    return ret;
}
1814 1815 1816

/* virGetHostNameByWWN:
 *
1817
 * Iterate over the sysfs tree to get FC host name (e.g. host5)
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 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
 * by wwnn,wwpn pair.
 */
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)

    while ((entry = readdir(dir))) {
        if (entry->d_name[0] == '.')
            continue;

1858
        if (virAsprintf(&wwnn_path, "%s/%s/node_name", prefix,
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
                        entry->d_name) < 0) {
            virReportOOMError();
            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;
        }

1877
        if (virAsprintf(&wwpn_path, "%s/%s/port_name", prefix,
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
                        entry->d_name) < 0) {
            virReportOOMError();
            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;
        }

1900
        ignore_value(VIR_STRDUP(ret, entry->d_name));
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
        break;
    }

cleanup:
# undef READ_WWN
    closedir(dir);
    VIR_FREE(wwnn_path);
    VIR_FREE(wwpn_path);
    VIR_FREE(wwnn_buf);
    VIR_FREE(wwpn_buf);
    return ret;
}
1913 1914 1915 1916 1917 1918

# define PORT_STATE_ONLINE "Online"

/* virFindFCHostCapableVport:
 *
 * Iterate over the sysfs and find out the first online HBA which
O
Osier Yang 已提交
1919 1920
 * supports vport, and not saturated. Returns the host name (e.g.
 * host5) on success, or NULL on failure.
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
 */
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;
    }

    while ((entry = readdir(dir))) {
        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 已提交
1954
        if (!virIsCapableVport(prefix, host))
1955 1956
            continue;

O
Osier Yang 已提交
1957
        if (virReadFCHost(prefix, host, "port_state", &state) < 0) {
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
             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 已提交
1969
        if (virReadFCHost(prefix, host, "max_npiv_vports", &max_vports) < 0) {
1970 1971 1972 1973
             VIR_DEBUG("Failed to read max_npiv_vports for host%d", host);
             continue;
        }

O
Osier Yang 已提交
1974
        if (virReadFCHost(prefix, host, "npiv_vports_inuse", &vports) < 0) {
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
             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)) {
1986
            ignore_value(VIR_STRDUP(ret, entry->d_name));
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
            goto cleanup;
        }

        VIR_FREE(max_vports);
        VIR_FREE(vports);
    }

cleanup:
    closedir(dir);
    VIR_FREE(max_vports);
    VIR_FREE(vports);
    return ret;
}
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
#else
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 已提交
2010

2011
bool
2012 2013
virIsCapableFCHost(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                   int host ATTRIBUTE_UNUSED)
O
Osier Yang 已提交
2014 2015
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2016
    return false;
O
Osier Yang 已提交
2017 2018
}

2019
bool
2020 2021
virIsCapableVport(const char *sysfs_prefix ATTRIBUTE_UNUSED,
                  int host ATTRIBUTE_UNUSED)
O
Osier Yang 已提交
2022 2023
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
2024
    return false;
O
Osier Yang 已提交
2025
}
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036

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

2037 2038 2039 2040 2041 2042 2043 2044 2045
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;
}

2046 2047 2048 2049 2050 2051 2052
char *
virFindFCHostCapableVport(const char *sysfs_prefix ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s", _("Not supported on this platform"));
    return NULL;
}

2053
#endif /* __linux__ */
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073

/**
 * virCompareLimitUlong:
 *
 * Compare two unsigned long long numbers. Value '0' of the arguments has a
 * special meaning of 'unlimited' and thus greater than any other value.
 *
 * Returns 0 if the numbers are equal, -1 if b is greater, 1 if a is greater.
 */
int
virCompareLimitUlong(unsigned long long a, unsigned long b)
{
    if (a == b)
        return 0;

    if (a == 0 || a > b)
        return 1;

    return -1;
}