libvirt_nss_leases.c 10.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * libvirt_nss_leases.c: Name Service Switch plugin lease file parser
 *
 * Copyright (C) 2019 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
26
#include <stdbool.h>
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#include <fcntl.h>

#include <yajl/yajl_gen.h>
#include <yajl/yajl_parse.h>

#include "libvirt_nss_leases.h"
#include "libvirt_nss.h"

enum {
    FIND_LEASES_STATE_START,
    FIND_LEASES_STATE_LIST,
    FIND_LEASES_STATE_ENTRY,
};


typedef struct {
    const char *name;
    char **macs;
    size_t nmacs;
    int state;
    unsigned long long now;
    int af;
    bool *found;
    leaseAddress **addrs;
    size_t *naddrs;

    char *key;
    struct {
        unsigned long long expiry;
        char *ipaddr;
        char *macaddr;
        char *hostname;
    } entry;
} findLeasesParser;


static int
64
appendAddr(const char *name __attribute__((unused)),
65 66 67 68 69 70 71 72
           leaseAddress **tmpAddress,
           size_t *ntmpAddress,
           const char *ipAddr,
           long long expirytime,
           int af)
{
    int family;
    size_t i;
73 74 75 76 77 78 79 80 81
    struct addrinfo hints = {0};
    struct addrinfo *res = NULL;
    union {
        struct sockaddr sa;
        struct sockaddr_in sin;
        struct sockaddr_in6 sin6;
    } sa;
    unsigned char addr[16];
    int err;
82
    leaseAddress *newAddr;
83 84

    DEBUG("IP address: %s", ipAddr);
85 86 87 88 89 90 91 92 93 94 95 96

    hints.ai_family = AF_UNSPEC;
    hints.ai_flags = AI_NUMERICHOST;

    if ((err = getaddrinfo(ipAddr, NULL, &hints, &res)) != 0) {
        ERROR("Cannot parse socket address '%s': %s",
              ipAddr, gai_strerror(err));
        return -1;
    }

    if (!res) {
        ERROR("No resolved address for '%s'", ipAddr);
97 98
        return -1;
    }
99 100 101 102 103 104 105 106 107 108 109 110
    family = res->ai_family;
    memcpy(&sa, res->ai_addr, res->ai_addrlen);
    freeaddrinfo(res);

    if (family == AF_INET) {
        memcpy(addr, &sa.sin.sin_addr, sizeof(sa.sin.sin_addr));
    } else if (family == AF_INET6) {
        memcpy(addr, &sa.sin6.sin6_addr, sizeof(sa.sin6.sin6_addr));
    } else {
        DEBUG("Skipping unexpected family %d", family);
        return 0;
    }
111 112 113 114 115 116 117 118

    if (af != AF_UNSPEC && af != family) {
        DEBUG("Skipping address which family is %d, %d requested", family, af);
        return 0;
    }

    for (i = 0; i < *ntmpAddress; i++) {
        if (family == AF_INET) {
119 120
            if ((*tmpAddress)[i].af == AF_INET &&
                memcmp((*tmpAddress)[i].addr,
121 122
                       &sa.sin.sin_addr,
                       sizeof(sa.sin.sin_addr)) == 0) {
123 124 125 126
                DEBUG("IP address already in the list");
                return 0;
            }
        } else {
127 128
            if ((*tmpAddress)[i].af == AF_INET6 &&
                memcmp((*tmpAddress)[i].addr,
129 130
                       &sa.sin6.sin6_addr,
                       sizeof(sa.sin6.sin6_addr)) == 0) {
131 132 133 134 135 136
                DEBUG("IP address already in the list");
                return 0;
            }
        }
    }

137 138
    newAddr = realloc(*tmpAddress, sizeof(*newAddr) * (*ntmpAddress + 1));
    if (!newAddr) {
139 140 141
        ERROR("Out of memory");
        return -1;
    }
142
    *tmpAddress = newAddr;
143 144 145 146 147

    (*tmpAddress)[*ntmpAddress].expirytime = expirytime;
    (*tmpAddress)[*ntmpAddress].af = family;
    if (family == AF_INET)
        memcpy((*tmpAddress)[*ntmpAddress].addr,
148 149
               &sa.sin.sin_addr,
               sizeof(sa.sin.sin_addr));
150 151
    else
        memcpy((*tmpAddress)[*ntmpAddress].addr,
152 153
               &sa.sin6.sin6_addr,
               sizeof(sa.sin6.sin6_addr));
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    (*ntmpAddress)++;
    return 0;
}


static int
findLeasesParserInteger(void *ctx,
                        long long val)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse int state=%d '%lld' (map key '%s')",
          parser->state, val, NULLSTR(parser->key));
    if (!parser->key)
        return 0;

    if (parser->state == FIND_LEASES_STATE_ENTRY) {
171
        if (strcmp(parser->key, "expiry-time"))
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
            return 0;

        parser->entry.expiry = val;
    } else {
        return 0;
    }
    return 1;
}


static int
findLeasesParserString(void *ctx,
                       const unsigned char *stringVal,
                       size_t stringLen)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse string state=%d '%.*s' (map key '%s')",
          parser->state, (int)stringLen, (const char *)stringVal,
          NULLSTR(parser->key));
    if (!parser->key)
        return 0;

    if (parser->state == FIND_LEASES_STATE_ENTRY) {
196
        if (!strcmp(parser->key, "ip-address")) {
197 198
            if (!(parser->entry.ipaddr = strndup((char *)stringVal, stringLen)))
                return 0;
199
        } else if (!strcmp(parser->key, "mac-address")) {
200 201
            if (!(parser->entry.macaddr = strndup((char *)stringVal, stringLen)))
                return 0;
202
        } else if (!strcmp(parser->key, "hostname")) {
203 204 205
            if (!(parser->entry.hostname = strndup((char *)stringVal, stringLen)))
                return 0;
        } else {
206
            return 1;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        }
    } else {
        return 0;
    }
    return 1;
}


static int
findLeasesParserMapKey(void *ctx,
                       const unsigned char *stringVal,
                       size_t stringLen)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse map key state=%d '%.*s'",
          parser->state, (int)stringLen, (const char *)stringVal);

    free(parser->key);
    if (!(parser->key = strndup((char *)stringVal, stringLen)))
        return 0;

    return 1;
}


static int
findLeasesParserStartMap(void *ctx)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse start map state=%d", parser->state);

    if (parser->state != FIND_LEASES_STATE_LIST)
        return 0;

    free(parser->key);
    parser->key = NULL;
    parser->state = FIND_LEASES_STATE_ENTRY;

    return 1;
}


static int
findLeasesParserEndMap(void *ctx)
{
    findLeasesParser *parser = ctx;
    size_t i;
    bool found = false;

    DEBUG("Parse end map state=%d", parser->state);

    if (parser->entry.macaddr == NULL)
        return 0;

    if (parser->state != FIND_LEASES_STATE_ENTRY)
        return 0;

    if (parser->nmacs) {
        DEBUG("Check %zu macs", parser->nmacs);
        for (i = 0; i < parser->nmacs && !found; i++) {
            DEBUG("Check mac '%s' vs '%s'", parser->macs[i], NULLSTR(parser->entry.macaddr));
270
            if (parser->entry.macaddr && !strcmp(parser->macs[i], parser->entry.macaddr))
271 272 273 274
                found = true;
        }
    } else {
        DEBUG("Check name '%s' vs '%s'", parser->name, NULLSTR(parser->entry.hostname));
275
        if (parser->entry.hostname && !strcmp(parser->name, parser->entry.hostname))
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
            found = true;
    }
    DEBUG("Found %d", found);
    if (parser->entry.expiry < parser->now) {
        DEBUG("Entry expired at %llu vs now %llu",
              parser->entry.expiry, parser->now);
        found = false;
    }
    if (!parser->entry.ipaddr)
        found = false;

    if (found) {
        *parser->found = true;

        if (appendAddr(parser->name,
                       parser->addrs, parser->naddrs,
                       parser->entry.ipaddr,
                       parser->entry.expiry,
                       parser->af) < 0)
            return 0;
    }

    free(parser->entry.macaddr);
    free(parser->entry.ipaddr);
    free(parser->entry.hostname);
    parser->entry.macaddr = NULL;
    parser->entry.ipaddr = NULL;
    parser->entry.hostname = NULL;

    parser->state = FIND_LEASES_STATE_LIST;

    return 1;
}


static int
findLeasesParserStartArray(void *ctx)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse start array state=%d", parser->state);

    if (parser->state == FIND_LEASES_STATE_START) {
        parser->state = FIND_LEASES_STATE_LIST;
    } else {
        return 0;
    }

    return 1;
}


static int
findLeasesParserEndArray(void *ctx)
{
    findLeasesParser *parser = ctx;

    DEBUG("Parse end array state=%d", parser->state);

    if (parser->state == FIND_LEASES_STATE_LIST)
        parser->state = FIND_LEASES_STATE_START;
    else
        return 0;

    return 1;
}


int
findLeases(const char *file,
           const char *name,
           char **macs,
           size_t nmacs,
           int af,
           time_t now,
           leaseAddress **addrs,
           size_t *naddrs,
           bool *found)
{
    int fd = -1;
    int ret = -1;
    const yajl_callbacks parserCallbacks = {
        NULL, /* null */
        NULL, /* bool */
        findLeasesParserInteger,
        NULL, /* double */
        NULL, /* number */
        findLeasesParserString,
        findLeasesParserStartMap,
        findLeasesParserMapKey,
        findLeasesParserEndMap,
        findLeasesParserStartArray,
        findLeasesParserEndArray,
    };
    findLeasesParser parserState = {
        .name = name,
        .macs = macs,
        .nmacs = nmacs,
        .af = af,
        .now = now,
        .found = found,
        .addrs = addrs,
        .naddrs = naddrs,
    };
    yajl_handle parser = NULL;
    char line[1024];
M
Michal Privoznik 已提交
382
    ssize_t nreadTotal = 0;
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    int rv;

    if ((fd = open(file, O_RDONLY)) < 0) {
        ERROR("Cannot open %s", file);
        goto cleanup;
    }

    parser = yajl_alloc(&parserCallbacks, NULL, &parserState);
    if (!parser) {
        ERROR("Unable to create JSON parser");
        goto cleanup;
    }

    while (1) {
        rv = read(fd, line, sizeof(line));
        if (rv < 0)
            goto cleanup;
        if (rv == 0)
            break;
M
Michal Privoznik 已提交
402
        nreadTotal += rv;
403 404 405

        if (yajl_parse(parser, (const unsigned char *)line, rv)  !=
            yajl_status_ok) {
406 407 408 409
            unsigned char *err = yajl_get_error(parser, 1,
                                                (const unsigned char*)line, rv);
            ERROR("Parse failed %s", (const char *) err);
            yajl_free_error(parser, err);
410 411 412 413
            goto cleanup;
        }
    }

M
Michal Privoznik 已提交
414 415
    if (nreadTotal > 0 &&
        yajl_complete_parse(parser) != yajl_status_ok) {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        ERROR("Parse failed %s",
              yajl_get_error(parser, 1, NULL, 0));
        goto cleanup;
    }

    ret = 0;

 cleanup:
    if (ret != 0) {
        free(*addrs);
        *addrs = NULL;
        *naddrs = 0;
    }
    yajl_free(parser);
    free(parserState.entry.ipaddr);
    free(parserState.entry.macaddr);
    free(parserState.entry.hostname);
    free(parserState.key);
    if (fd != -1)
        close(fd);
    return ret;
}