leaseshelper.c 17.6 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 26 27
/*
 * leaseshelper.c: Helper program to create custom leases file
 *
 * Copyright (C) 2014 Red Hat, Inc.
 * Copyright (C) 2014 Nehal J Wani
 *
 * 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/>.
 *
 * Author: Nehal J Wani <nehaljw.kkd1@gmail.com>
 *
 * For IPv6 support, use dnsmasq >= 2.67
 */

#include <config.h>

P
Pavel Hrdina 已提交
28
#include <locale.h>
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

#include "virutil.h"
#include "virthread.h"
#include "virfile.h"
#include "virpidfile.h"
#include "virbuffer.h"
#include "virstring.h"
#include "virerror.h"
#include "viralloc.h"
#include "virjson.h"
#include "configmake.h"

#define VIR_FROM_THIS VIR_FROM_NETWORK

/**
 * VIR_NETWORK_DHCP_LEASE_FILE_SIZE_MAX:
 *
 * Macro providing the upper limit on the size of leases file
 */
#define VIR_NETWORK_DHCP_LEASE_FILE_SIZE_MAX (32 * 1024 * 1024)

53 54 55 56 57 58
/*
 * Use this when passing possibly-NULL strings to printf-a-likes.
 * Required for unknown parameters during init call.
 */
#define EMPTY_STR(s) ((s) ? (s) : "*")

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
static const char *program_name;

/* Display version information. */
static void
helperVersion(const char *argv0)
{
    printf("%s (%s) %s\n", argv0, PACKAGE_NAME, PACKAGE_VERSION);
}

ATTRIBUTE_NORETURN static void
usage(int status)
{
    if (status) {
        fprintf(stderr, _("%s: try --help for more details\n"), program_name);
    } else {
74
        printf(_("Usage: %s add|old|del|init mac|clientid ip [hostname]\n"
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
                 "Designed for use with 'dnsmasq --dhcp-script'\n"
                 "Refer to man page of dnsmasq for more details'\n"),
               program_name);
    }
    exit(status);
}

static int
customLeaseRewriteFile(int fd, void *opaque)
{
    char **data = opaque;

    if (safewrite(fd, *data, strlen(*data)) < 0)
        return -1;

    return 0;
}

/* Flags denoting actions for a lease */
enum virLeaseActionFlags {
    VIR_LEASE_ACTION_ADD,       /* Create new lease */
    VIR_LEASE_ACTION_OLD,       /* Lease already exists, renew it */
    VIR_LEASE_ACTION_DEL,       /* Delete the lease */
98
    VIR_LEASE_ACTION_INIT,      /* Tell dnsmasq of existing leases on restart */
99 100 101 102 103 104 105

    VIR_LEASE_ACTION_LAST
};

VIR_ENUM_DECL(virLeaseAction);

VIR_ENUM_IMPL(virLeaseAction, VIR_LEASE_ACTION_LAST,
106
              "add", "old", "del", "init");
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static int
virLeaseReadCustomLeaseFile(virJSONValuePtr leases_array_new,
                            const char *custom_lease_file,
                            const char *ip_to_delete,
                            char **server_duid)
{
    char *lease_entries = NULL;
    virJSONValuePtr leases_array = NULL;
    long long currtime = 0;
    long long expirytime;
    int custom_lease_file_len = 0;
    virJSONValuePtr lease_tmp = NULL;
    const char *ip_tmp = NULL;
    const char *server_duid_tmp = NULL;
    size_t i;
    int ret = -1;

    currtime = (long long) time(NULL);

    /* Read entire contents */
    if ((custom_lease_file_len = virFileReadAll(custom_lease_file,
                                                VIR_NETWORK_DHCP_LEASE_FILE_SIZE_MAX,
                                                &lease_entries)) < 0) {
        goto cleanup;
    }

    /* Check for previous leases */
135 136 137 138
    if (custom_lease_file_len == 0) {
        ret = 0;
        goto cleanup;
    }
139

140 141 142 143 144 145 146
    if (!(leases_array = virJSONValueFromString(lease_entries))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("invalid json in file: %s, rewriting it"),
                       custom_lease_file);
        ret = 0;
        goto cleanup;
    }
147

148 149 150 151 152
    if (!virJSONValueIsArray(leases_array)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("couldn't fetch array of leases"));
        goto cleanup;
    }
153

154 155 156 157 158 159 160
    i = 0;
    while (i < virJSONValueArraySize(leases_array)) {
        if (!(lease_tmp = virJSONValueArrayGet(leases_array, i))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to parse json"));
            goto cleanup;
        }
161

162 163 164 165 166 167 168 169 170 171 172
        if (!(ip_tmp = virJSONValueObjectGetString(lease_tmp, "ip-address")) ||
            (virJSONValueObjectGetNumberLong(lease_tmp, "expiry-time", &expirytime) < 0)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to parse json"));
            goto cleanup;
        }
        /* Check whether lease has expired or not */
        if (expirytime < currtime) {
            i++;
            continue;
        }
173

174 175 176 177 178
        /* Check whether lease has to be included or not */
        if (ip_to_delete && STREQ(ip_tmp, ip_to_delete)) {
            i++;
            continue;
        }
179

180 181 182 183 184 185 186 187
        if (strchr(ip_tmp, ':')) {
            /* This is an ipv6 lease */
            if ((server_duid_tmp
                 = virJSONValueObjectGetString(lease_tmp, "server-duid"))) {
                if (!*server_duid && VIR_STRDUP(*server_duid, server_duid_tmp) < 0) {
                    /* Control reaches here when the 'action' is not for an
                     * ipv6 lease or, for some weird reason the env var
                     * DNSMASQ_SERVER_DUID wasn't set*/
188 189
                    goto cleanup;
                }
190 191 192 193 194 195
            } else {
                /* Inject server-duid into those ipv6 leases which
                 * didn't have it previously, for example, those
                 * created by leaseshelper from libvirt 1.2.6 */
                if (virJSONValueObjectAppendString(lease_tmp, "server-duid", *server_duid) < 0)
                    goto cleanup;
196 197
            }
        }
198 199 200 201 202 203 204 205 206

        /* Move old lease to new array */
        if (virJSONValueArrayAppend(leases_array_new, lease_tmp) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to create json"));
            goto cleanup;
        }

        ignore_value(virJSONValueArraySteal(leases_array, i));
207 208 209 210 211 212 213 214 215 216
    }

    ret = 0;

 cleanup:
    virJSONValueFree(leases_array);
    VIR_FREE(lease_entries);
    return ret;
}

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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
static int
virLeasePrintLeases(virJSONValuePtr leases_array_new,
                    const char *server_duid)
{
    virJSONValuePtr lease_tmp = NULL;
    const char *ip_tmp = NULL;
    long long expirytime = 0;
    int ret = -1;
    size_t i;

    /* Man page of dnsmasq says: the script (helper program, in our case)
     * should write the saved state of the lease database, in dnsmasq
     * leasefile format, to stdout and exit with zero exit code, when
     * called with argument init. Format:
     * $expirytime $mac $ip $hostname $clientid # For all ipv4 leases
     * duid $server-duid # If DHCPv6 is present
     * $expirytime $iaid $ip $hostname $clientduid # For all ipv6 leases */

    /* Traversing the ipv4 leases */
    for (i = 0; i < virJSONValueArraySize(leases_array_new); i++) {
        lease_tmp = virJSONValueArrayGet(leases_array_new, i);
        if (!(ip_tmp = virJSONValueObjectGetString(lease_tmp, "ip-address"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to parse json"));
            goto cleanup;
        }
        if (!strchr(ip_tmp, ':')) {
            if (virJSONValueObjectGetNumberLong(lease_tmp, "expiry-time",
                                                &expirytime) < 0)
                continue;

            printf("%lld %s %s %s %s\n",
                   expirytime,
                   virJSONValueObjectGetString(lease_tmp, "mac-address"),
                   virJSONValueObjectGetString(lease_tmp, "ip-address"),
                   EMPTY_STR(virJSONValueObjectGetString(lease_tmp, "hostname")),
                   EMPTY_STR(virJSONValueObjectGetString(lease_tmp, "client-id")));
        }
    }

    /* Traversing the ipv6 leases */
    if (server_duid) {
        printf("duid %s\n", server_duid);
        for (i = 0; i < virJSONValueArraySize(leases_array_new); i++) {
            lease_tmp = virJSONValueArrayGet(leases_array_new, i);
            if (!(ip_tmp = virJSONValueObjectGetString(lease_tmp, "ip-address"))) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("failed to parse json"));
                goto cleanup;
            }
            if (strchr(ip_tmp, ':')) {
                if (virJSONValueObjectGetNumberLong(lease_tmp, "expiry-time",
                                                    &expirytime) < 0)
                    continue;

                printf("%lld %s %s %s %s\n",
                       expirytime,
                       virJSONValueObjectGetString(lease_tmp, "iaid"),
                       virJSONValueObjectGetString(lease_tmp, "ip-address"),
                       EMPTY_STR(virJSONValueObjectGetString(lease_tmp, "hostname")),
                       EMPTY_STR(virJSONValueObjectGetString(lease_tmp, "client-id")));
            }
        }
    }

    ret = 0;

 cleanup:
    return ret;
}

J
Ján Tomko 已提交
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
static int
virLeaseNew(virJSONValuePtr *lease_ret,
            const char *mac,
            const char *clientid,
            const char *ip,
            const char *hostname,
            const char *iaid,
            const char *server_duid)
{
    virJSONValuePtr lease_new = NULL;
    const char *exptime_tmp = virGetEnvAllowSUID("DNSMASQ_LEASE_EXPIRES");
    long long expirytime = 0;
    char *exptime = NULL;
    int ret = -1;

    /* In case hostname is still unknown, use the last known one */
    if (!hostname)
        hostname = virGetEnvAllowSUID("DNSMASQ_OLD_HOSTNAME");

    if (!mac) {
        ret = 0;
        goto cleanup;
    }

    if (exptime_tmp) {
        if (VIR_STRDUP(exptime, exptime_tmp) < 0)
            goto cleanup;

        /* Removed extraneous trailing space in DNSMASQ_LEASE_EXPIRES
         * (dnsmasq < 2.52) */
        if (exptime[strlen(exptime) - 1] == ' ')
            exptime[strlen(exptime) - 1] = '\0';
    }

    if (!exptime ||
        virStrToLong_ll(exptime, NULL, 10, &expirytime) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to convert lease expiry time to long long: %s"),
                       NULLSTR(exptime));
        goto cleanup;
    }

    /* Create new lease */
    if (!(lease_new = virJSONValueNewObject())) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create json"));
        goto cleanup;
    }

    if (iaid && virJSONValueObjectAppendString(lease_new, "iaid", iaid) < 0)
        goto cleanup;
    if (ip && virJSONValueObjectAppendString(lease_new, "ip-address", ip) < 0)
        goto cleanup;
    if (mac && virJSONValueObjectAppendString(lease_new, "mac-address", mac) < 0)
        goto cleanup;
    if (hostname && virJSONValueObjectAppendString(lease_new, "hostname", hostname) < 0)
        goto cleanup;
    if (clientid && virJSONValueObjectAppendString(lease_new, "client-id", clientid) < 0)
        goto cleanup;
    if (server_duid && virJSONValueObjectAppendString(lease_new, "server-duid", server_duid) < 0)
        goto cleanup;
    if (expirytime && virJSONValueObjectAppendNumberLong(lease_new, "expiry-time", expirytime) < 0)
        goto cleanup;

    ret = 0;
    *lease_ret = lease_new;
    lease_new = NULL;
 cleanup:
    VIR_FREE(exptime);
    virJSONValueFree(lease_new);
    return ret;
}

361 362 363 364 365 366 367
int
main(int argc, char **argv)
{
    char *pid_file = NULL;
    char *custom_lease_file = NULL;
    const char *ip = NULL;
    const char *mac = NULL;
368
    const char *leases_str = NULL;
369 370 371 372
    const char *iaid = virGetEnvAllowSUID("DNSMASQ_IAID");
    const char *clientid = virGetEnvAllowSUID("DNSMASQ_CLIENT_ID");
    const char *interface = virGetEnvAllowSUID("DNSMASQ_INTERFACE");
    const char *hostname = virGetEnvAllowSUID("DNSMASQ_SUPPLIED_HOSTNAME");
373
    char *server_duid = NULL;
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    int action = -1;
    int pid_file_fd = -1;
    int rv = EXIT_FAILURE;
    bool delete = false;
    virJSONValuePtr lease_new = NULL;
    virJSONValuePtr leases_array_new = NULL;

    virSetErrorFunc(NULL, NULL);
    virSetErrorLogPriorityFunc(NULL);

    program_name = argv[0];

    if (setlocale(LC_ALL, "") == NULL ||
        bindtextdomain(PACKAGE, LOCALEDIR) == NULL ||
        textdomain(PACKAGE) == NULL) {
        fprintf(stderr, _("%s: initialization failed\n"), program_name);
        exit(EXIT_FAILURE);
    }

    if (virThreadInitialize() < 0 ||
        virErrorInitialize() < 0) {
        fprintf(stderr, _("%s: initialization failed\n"), program_name);
        exit(EXIT_FAILURE);
    }

    /* Doesn't hurt to check */
    if (argc > 1) {
        if (STREQ(argv[1], "--help"))
            usage(EXIT_SUCCESS);

        if (STREQ(argv[1], "--version")) {
            helperVersion(argv[0]);
            exit(EXIT_SUCCESS);
        }
    }

410
    if (argc != 4 && argc != 5 && argc != 2) {
411 412 413 414 415
        /* Refer man page of dnsmasq --dhcp-script for more details */
        usage(EXIT_FAILURE);
    }

    /* Make sure dnsmasq knows the interface. The interface name is not known
416 417 418 419 420
     * via env variable set by dnsmasq when dnsmasq (re)starts and throws 'del'
     * events for expired leases. So, libvirtd sets another env var for this
     * purpose */
    if (!interface &&
        !(interface = virGetEnvAllowSUID("VIR_BRIDGE_NAME")))
421 422 423 424
        goto cleanup;

    ip = argv[3];
    mac = argv[2];
P
Peter Krempa 已提交
425 426 427 428 429

    if ((action = virLeaseActionTypeFromString(argv[1])) < 0) {
        fprintf(stderr, _("Unsupported action: %s\n"), argv[1]);
        exit(EXIT_FAILURE);
    }
430 431 432 433 434 435

    /* In case hostname is known, it is the 5th argument */
    if (argc == 5)
        hostname = argv[4];

    /* Check if it is an IPv6 lease */
436
    if (iaid) {
437 438 439 440
        mac = virGetEnvAllowSUID("DNSMASQ_MAC");
        clientid = argv[2];
    }

441 442 443
    if (VIR_STRDUP(server_duid, virGetEnvAllowSUID("DNSMASQ_SERVER_DUID")) < 0)
        goto cleanup;

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    if (virAsprintf(&custom_lease_file,
                    LOCALSTATEDIR "/lib/libvirt/dnsmasq/%s.status",
                    interface) < 0)
        goto cleanup;

    if (VIR_STRDUP(pid_file, LOCALSTATEDIR "/run/leaseshelper.pid") < 0)
        goto cleanup;

    /* Try to claim the pidfile, exiting if we can't */
    if ((pid_file_fd = virPidFileAcquirePath(pid_file, true, getpid())) < 0)
        goto cleanup;

    /* Since interfaces can be hot plugged, we need to make sure that the
     * corresponding custom lease file exists. If not, 'touch' it */
    if (virFileTouch(custom_lease_file, 0644) < 0)
        goto cleanup;

P
Peter Krempa 已提交
461
    switch ((enum virLeaseActionFlags) action) {
462
    case VIR_LEASE_ACTION_ADD:
P
Peter Krempa 已提交
463
    case VIR_LEASE_ACTION_OLD:
J
Ján Tomko 已提交
464 465 466
        /* Create new lease */
        if (virLeaseNew(&lease_new, mac, clientid, ip, hostname, server_duid, iaid) < 0)
            goto cleanup;
467 468 469 470 471 472 473 474 475 476 477 478 479
        /* Custom ipv6 leases *will not* be created if the env-var DNSMASQ_MAC
         * is not set. In the special case, when the $(interface).status file
         * is not already present and dnsmasq is (re)started, the corresponding
         * ipv6 custom lease will be created only when the guest sends the
         * 'old' action for its existing ipv6 interfaces.
         *
         * According to rfc3315, the combination of DUID and IAID can be used
         * to uniquely identify each ipv6 guest interface. So, in future, if
         * we introduce virNetworkGetDHCPLeaseBy(IAID|DUID|IAID+DUID) for ipv6
         * interfaces, then, the following if condition won't be required, as
         * the new lease will be created irrespective of whether the MACID is
         * known or not.
         */
J
Ján Tomko 已提交
480
        if (!lease_new)
P
Peter Krempa 已提交
481 482
            break;

483
        /* fallthrough */
P
Peter Krempa 已提交
484
    case VIR_LEASE_ACTION_DEL:
485
        /* Delete the corresponding lease, if it already exists */
P
Peter Krempa 已提交
486 487 488 489 490 491
        delete = true;
        break;

    case VIR_LEASE_ACTION_INIT:
    case VIR_LEASE_ACTION_LAST:
        break;
492
    }
493 494 495 496 497 498 499

    if (!(leases_array_new = virJSONValueNewArray())) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to create json"));
        goto cleanup;
    }

500 501 502
    if (virLeaseReadCustomLeaseFile(leases_array_new, custom_lease_file,
                                    delete ? ip : NULL, &server_duid) < 0)
        goto cleanup;
503

504 505
    switch ((enum virLeaseActionFlags) action) {
    case VIR_LEASE_ACTION_INIT:
506 507
        if (virLeasePrintLeases(leases_array_new, server_duid) < 0)
            goto cleanup;
508 509 510 511 512

        break;

    case VIR_LEASE_ACTION_OLD:
    case VIR_LEASE_ACTION_ADD:
513
        if (lease_new && virJSONValueArrayAppend(leases_array_new, lease_new) < 0) {
514 515 516 517
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to create json"));
            goto cleanup;
        }
P
Pavel Hrdina 已提交
518
        lease_new = NULL;
519

P
Peter Krempa 已提交
520 521
        /* fallthrough */
    case VIR_LEASE_ACTION_DEL:
522 523 524 525 526
        if (!(leases_str = virJSONValueToString(leases_array_new, true))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("empty json array"));
            goto cleanup;
        }
527

528 529 530 531
        /* Write to file */
        if (virFileRewrite(custom_lease_file, 0644,
                           customLeaseRewriteFile, &leases_str) < 0)
            goto cleanup;
P
Peter Krempa 已提交
532 533 534 535
        break;

    case VIR_LEASE_ACTION_LAST:
        break;
536
    }
537 538 539 540 541 542 543 544

    rv = EXIT_SUCCESS;

 cleanup:
    if (pid_file_fd != -1)
        virPidFileReleasePath(pid_file, pid_file_fd);

    VIR_FREE(pid_file);
545
    VIR_FREE(server_duid);
546 547 548 549 550 551
    VIR_FREE(custom_lease_file);
    virJSONValueFree(lease_new);
    virJSONValueFree(leases_array_new);

    return rv;
}