virnetserver.c 34.9 KB
Newer Older
1 2 3
/*
 * virnetserver.c: generic network RPC server
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#include "virnetserver.h"
31
#include "virlog.h"
32
#include "viralloc.h"
33
#include "virerror.h"
34
#include "virthread.h"
35
#include "virthreadpool.h"
36
#include "virutil.h"
E
Eric Blake 已提交
37
#include "virfile.h"
38
#include "virnetservermdns.h"
39
#include "virdbus.h"
40
#include "virstring.h"
41

42 43 44 45
#ifndef SA_SIGINFO
# define SA_SIGINFO 0
#endif

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
#define VIR_FROM_THIS VIR_FROM_RPC

typedef struct _virNetServerSignal virNetServerSignal;
typedef virNetServerSignal *virNetServerSignalPtr;

struct _virNetServerSignal {
    struct sigaction oldaction;
    int signum;
    virNetServerSignalFunc func;
    void *opaque;
};

typedef struct _virNetServerJob virNetServerJob;
typedef virNetServerJob *virNetServerJobPtr;

struct _virNetServerJob {
    virNetServerClientPtr client;
    virNetMessagePtr msg;
64
    virNetServerProgramPtr prog;
65 66 67
};

struct _virNetServer {
68
    virObjectLockable parent;
69 70 71 72 73 74 75 76 77 78 79

    virThreadPoolPtr workers;

    bool privileged;

    size_t nsignals;
    virNetServerSignalPtr *signals;
    int sigread;
    int sigwrite;
    int sigwatch;

80 81 82 83
    char *mdnsGroupName;
    virNetServerMDNSPtr mdns;
    virNetServerMDNSGroupPtr mdnsGroup;

84 85 86 87 88 89 90 91 92 93
    size_t nservices;
    virNetServerServicePtr *services;

    size_t nprograms;
    virNetServerProgramPtr *programs;

    size_t nclients;
    size_t nclients_max;
    virNetServerClientPtr *clients;

94 95 96 97
    int keepaliveInterval;
    unsigned int keepaliveCount;
    bool keepaliveRequired;

98 99
    unsigned int quit :1;

100
#ifdef WITH_GNUTLS
101
    virNetTLSContextPtr tls;
102
#endif
103 104

    unsigned int autoShutdownTimeout;
105
    size_t autoShutdownInhibitions;
106 107
    bool autoShutdownCallingInhibit;
    int autoShutdownInhibitFd;
108

109
    virNetServerClientPrivNew clientPrivNew;
110
    virNetServerClientPrivPreExecRestart clientPrivPreExecRestart;
111 112
    virFreeCallback clientPrivFree;
    void *clientPrivOpaque;
113 114 115
};


116 117 118 119 120
static virClassPtr virNetServerClass;
static void virNetServerDispose(void *obj);

static int virNetServerOnceInit(void)
{
121
    if (!(virNetServerClass = virClassNew(virClassForObjectLockable(),
122
                                          "virNetServer",
123 124 125 126 127 128 129 130 131 132
                                          sizeof(virNetServer),
                                          virNetServerDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetServer)


133 134 135 136
static int virNetServerProcessMsg(virNetServerPtr srv,
                                  virNetServerClientPtr client,
                                  virNetServerProgramPtr prog,
                                  virNetMessagePtr msg)
137
{
138 139
    int ret = -1;
    if (!prog) {
140 141 142 143
        /* Only send back an error for type == CALL. Other
         * message types are not expecting replies, so we
         * must just log it & drop them
         */
144 145 146 147 148 149
        if (msg->header.type == VIR_NET_CALL ||
            msg->header.type == VIR_NET_CALL_WITH_FDS) {
            if (virNetServerProgramUnknownError(client,
                                                msg,
                                                &msg->header) < 0)
                goto cleanup;
150 151
        } else {
            VIR_INFO("Dropping client mesage, unknown program %d version %d type %d proc %d",
152 153
                     msg->header.prog, msg->header.vers,
                     msg->header.type, msg->header.proc);
154
            /* Send a dummy reply to free up 'msg' & unblock client rx */
155 156 157 158
            virNetMessageClear(msg);
            msg->header.type = VIR_NET_REPLY;
            if (virNetServerClientSendMessage(client, msg) < 0)
                goto cleanup;
159
        }
160
        goto done;
161 162
    }

163
    if (virNetServerProgramDispatch(prog,
164
                                    srv,
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
                                    client,
                                    msg) < 0)
        goto cleanup;

done:
    ret = 0;

cleanup:
    return ret;
}

static void virNetServerHandleJob(void *jobOpaque, void *opaque)
{
    virNetServerPtr srv = opaque;
    virNetServerJobPtr job = jobOpaque;

    VIR_DEBUG("server=%p client=%p message=%p prog=%p",
              srv, job->client, job->msg, job->prog);

    if (virNetServerProcessMsg(srv, job->client, job->prog, job->msg) < 0)
185 186
        goto error;

187 188
    virObjectUnref(job->prog);
    virObjectUnref(job->client);
189 190 191 192
    VIR_FREE(job);
    return;

error:
193
    virObjectUnref(job->prog);
194 195
    virNetMessageFree(job->msg);
    virNetServerClientClose(job->client);
196
    virObjectUnref(job->client);
197
    VIR_FREE(job);
198 199 200 201 202 203 204
}

static int virNetServerDispatchNewMessage(virNetServerClientPtr client,
                                          virNetMessagePtr msg,
                                          void *opaque)
{
    virNetServerPtr srv = opaque;
205 206 207 208
    virNetServerProgramPtr prog = NULL;
    unsigned int priority = 0;
    size_t i;
    int ret = -1;
209 210 211 212

    VIR_DEBUG("server=%p client=%p message=%p",
              srv, client, msg);

213
    virObjectLock(srv);
214
    for (i = 0; i < srv->nprograms; i++) {
215
        if (virNetServerProgramMatches(srv->programs[i], msg)) {
216 217 218 219 220
            prog = srv->programs[i];
            break;
        }
    }

221 222 223 224 225 226 227
    if (srv->workers) {
        virNetServerJobPtr job;

        if (VIR_ALLOC(job) < 0) {
            virReportOOMError();
            goto cleanup;
        }
228

229 230 231 232
        job->client = client;
        job->msg = msg;

        if (prog) {
233
            virObjectRef(prog);
234 235 236
            job->prog = prog;
            priority = virNetServerProgramGetPriority(prog, msg->header.proc);
        }
237

238 239 240 241
        ret = virThreadPoolSendJob(srv->workers, priority, job);

        if (ret < 0) {
            VIR_FREE(job);
242
            virObjectUnref(prog);
243 244 245
        }
    } else {
        ret = virNetServerProcessMsg(srv, client, prog, msg);
246
    }
247 248

cleanup:
249
    virObjectUnlock(srv);
250 251 252 253 254

    return ret;
}


255 256
static int virNetServerAddClient(virNetServerPtr srv,
                                 virNetServerClientPtr client)
257
{
258
    virObjectLock(srv);
259 260

    if (srv->nclients >= srv->nclients_max) {
261 262 263
        virReportError(VIR_ERR_RPC,
                       _("Too many active clients (%zu), dropping connection from %s"),
                       srv->nclients_max, virNetServerClientRemoteAddrString(client));
264 265 266 267 268 269 270 271 272 273 274
        goto error;
    }

    if (virNetServerClientInit(client) < 0)
        goto error;

    if (VIR_EXPAND_N(srv->clients, srv->nclients, 1) < 0) {
        virReportOOMError();
        goto error;
    }
    srv->clients[srv->nclients-1] = client;
275
    virObjectRef(client);
276 277 278 279 280

    virNetServerClientSetDispatcher(client,
                                    virNetServerDispatchNewMessage,
                                    srv);

281 282 283
    virNetServerClientInitKeepAlive(client, srv->keepaliveInterval,
                                    srv->keepaliveCount);

284
    virObjectUnlock(srv);
285 286 287
    return 0;

error:
288
    virObjectUnlock(srv);
289 290 291
    return -1;
}

292 293 294 295 296 297 298 299 300 301 302
static int virNetServerDispatchNewClient(virNetServerServicePtr svc,
                                         virNetSocketPtr clientsock,
                                         void *opaque)
{
    virNetServerPtr srv = opaque;
    virNetServerClientPtr client;

    if (!(client = virNetServerClientNew(clientsock,
                                         virNetServerServiceGetAuth(svc),
                                         virNetServerServiceIsReadonly(svc),
                                         virNetServerServiceGetMaxRequests(svc),
303
#if WITH_GNUTLS
304
                                         virNetServerServiceGetTLSContext(svc),
305
#endif
306
                                         srv->clientPrivNew,
307
                                         srv->clientPrivPreExecRestart,
308 309 310 311 312 313 314 315 316 317 318 319 320
                                         srv->clientPrivFree,
                                         srv->clientPrivOpaque)))
        return -1;

    if (virNetServerAddClient(srv, client) < 0) {
        virNetServerClientClose(client);
        virObjectUnref(client);
        return -1;
    }
    virObjectUnref(client);
    return 0;
}

321

322 323 324
static void
virNetServerFatalSignal(int sig, siginfo_t *siginfo ATTRIBUTE_UNUSED,
                        void *context ATTRIBUTE_UNUSED)
325 326 327 328 329 330 331 332 333 334 335 336 337 338
{
    struct sigaction sig_action;
    int origerrno;

    origerrno = errno;
    virLogEmergencyDumpAll(sig);

    /*
     * If the signal is fatal, avoid looping over this handler
     * by deactivating it
     */
#ifdef SIGUSR2
    if (sig != SIGUSR2) {
#endif
339
        memset(&sig_action, 0, sizeof(sig_action));
340
        sig_action.sa_handler = SIG_DFL;
341
        sigaction(sig, &sig_action, NULL);
342
        raise(sig);
343 344 345 346 347 348 349 350 351
#ifdef SIGUSR2
    }
#endif
    errno = origerrno;
}


virNetServerPtr virNetServerNew(size_t min_workers,
                                size_t max_workers,
352
                                size_t priority_workers,
353
                                size_t max_clients,
354 355 356
                                int keepaliveInterval,
                                unsigned int keepaliveCount,
                                bool keepaliveRequired,
357
                                const char *mdnsGroupName,
358
                                virNetServerClientPrivNew clientPrivNew,
359
                                virNetServerClientPrivPreExecRestart clientPrivPreExecRestart,
360 361
                                virFreeCallback clientPrivFree,
                                void *clientPrivOpaque)
362 363 364 365
{
    virNetServerPtr srv;
    struct sigaction sig_action;

366
    if (virNetServerInitialize() < 0)
367 368
        return NULL;

369
    if (!(srv = virObjectLockableNew(virNetServerClass)))
370
        return NULL;
371

372 373
    if (max_workers &&
        !(srv->workers = virThreadPoolNew(min_workers, max_workers,
374
                                          priority_workers,
375 376 377 378 379
                                          virNetServerHandleJob,
                                          srv)))
        goto error;

    srv->nclients_max = max_clients;
380 381 382
    srv->keepaliveInterval = keepaliveInterval;
    srv->keepaliveCount = keepaliveCount;
    srv->keepaliveRequired = keepaliveRequired;
383
    srv->sigwrite = srv->sigread = -1;
384
    srv->clientPrivNew = clientPrivNew;
385
    srv->clientPrivPreExecRestart = clientPrivPreExecRestart;
386 387
    srv->clientPrivFree = clientPrivFree;
    srv->clientPrivOpaque = clientPrivOpaque;
388 389
    srv->privileged = geteuid() == 0;
    srv->autoShutdownInhibitFd = -1;
390

391
    if (VIR_STRDUP(srv->mdnsGroupName, mdnsGroupName) < 0)
392 393 394 395
        goto error;
    if (srv->mdnsGroupName) {
        if (!(srv->mdns = virNetServerMDNSNew()))
            goto error;
396 397
        if (!(srv->mdnsGroup = virNetServerMDNSAddGroup(srv->mdns,
                                                        srv->mdnsGroupName)))
398 399 400
            goto error;
    }

401 402 403 404 405 406 407 408 409 410 411 412
    if (virEventRegisterDefaultImpl() < 0)
        goto error;

    memset(&sig_action, 0, sizeof(sig_action));
    sig_action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &sig_action, NULL);

    /*
     * catch fatal errors to dump a log, also hook to USR2 for dynamic
     * debugging purposes or testing
     */
    sig_action.sa_sigaction = virNetServerFatalSignal;
413
    sig_action.sa_flags = SA_SIGINFO;
414 415 416 417 418 419 420 421 422 423 424 425 426 427
    sigaction(SIGFPE, &sig_action, NULL);
    sigaction(SIGSEGV, &sig_action, NULL);
    sigaction(SIGILL, &sig_action, NULL);
    sigaction(SIGABRT, &sig_action, NULL);
#ifdef SIGBUS
    sigaction(SIGBUS, &sig_action, NULL);
#endif
#ifdef SIGUSR2
    sigaction(SIGUSR2, &sig_action, NULL);
#endif

    return srv;

error:
428
    virObjectUnref(srv);
429 430 431 432
    return NULL;
}


433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
virNetServerPtr virNetServerNewPostExecRestart(virJSONValuePtr object,
                                               virNetServerClientPrivNew clientPrivNew,
                                               virNetServerClientPrivNewPostExecRestart clientPrivNewPostExecRestart,
                                               virNetServerClientPrivPreExecRestart clientPrivPreExecRestart,
                                               virFreeCallback clientPrivFree,
                                               void *clientPrivOpaque)
{
    virNetServerPtr srv = NULL;
    virJSONValuePtr clients;
    virJSONValuePtr services;
    size_t i;
    int n;
    unsigned int min_workers;
    unsigned int max_workers;
    unsigned int priority_workers;
    unsigned int max_clients;
    unsigned int keepaliveInterval;
    unsigned int keepaliveCount;
    bool keepaliveRequired;
    const char *mdnsGroupName = NULL;

    if (virJSONValueObjectGetNumberUint(object, "min_workers", &min_workers) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing min_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "max_workers", &max_workers) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing max_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "priority_workers", &priority_workers) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing priority_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "max_clients", &max_clients) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing max_clients data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "keepaliveInterval", &keepaliveInterval) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing keepaliveInterval data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetNumberUint(object, "keepaliveCount", &keepaliveCount) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing keepaliveCount data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectGetBoolean(object, "keepaliveRequired", &keepaliveRequired) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing keepaliveRequired data in JSON document"));
        goto error;
    }

    if (virJSONValueObjectHasKey(object, "mdnsGroupName") &&
        (!(mdnsGroupName = virJSONValueObjectGetString(object, "mdnsGroupName")))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed mdnsGroupName data in JSON document"));
        goto error;
    }

    if (!(srv = virNetServerNew(min_workers, max_clients,
                                priority_workers, max_clients,
                                keepaliveInterval, keepaliveCount,
                                keepaliveRequired, mdnsGroupName,
                                clientPrivNew, clientPrivPreExecRestart,
                                clientPrivFree, clientPrivOpaque)))
        goto error;

    if (!(services = virJSONValueObjectGet(object, "services"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing services data in JSON document"));
        goto error;
    }

    n =  virJSONValueArraySize(services);
    if (n < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed services data in JSON document"));
        goto error;
    }

518
    for (i = 0; i < n; i++) {
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        virNetServerServicePtr service;
        virJSONValuePtr child = virJSONValueArrayGet(services, i);
        if (!child) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing service data in JSON document"));
            goto error;
        }

        if (!(service = virNetServerServiceNewPostExecRestart(child)))
            goto error;

        /* XXX mdns entry names ? */
        if (virNetServerAddService(srv, service, NULL) < 0) {
            virObjectUnref(service);
            goto error;
        }
    }


    if (!(clients = virJSONValueObjectGet(object, "clients"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing clients data in JSON document"));
        goto error;
    }

    n =  virJSONValueArraySize(clients);
    if (n < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Malformed clients data in JSON document"));
        goto error;
    }

551
    for (i = 0; i < n; i++) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
        virNetServerClientPtr client;
        virJSONValuePtr child = virJSONValueArrayGet(clients, i);
        if (!child) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing client data in JSON document"));
            goto error;
        }

        if (!(client = virNetServerClientNewPostExecRestart(child,
                                                            clientPrivNewPostExecRestart,
                                                            clientPrivPreExecRestart,
                                                            clientPrivFree,
                                                            clientPrivOpaque)))
            goto error;

        if (virNetServerAddClient(srv, client) < 0) {
            virObjectUnref(client);
            goto error;
        }
        virObjectUnref(client);
    }

    return srv;

error:
    virObjectUnref(srv);
    return NULL;
}


virJSONValuePtr virNetServerPreExecRestart(virNetServerPtr srv)
{
    virJSONValuePtr object;
    virJSONValuePtr clients;
    virJSONValuePtr services;
    size_t i;

589
    virObjectLock(srv);
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645

    if (!(object = virJSONValueNewObject()))
        goto error;

    if (virJSONValueObjectAppendNumberUint(object, "min_workers",
                                           virThreadPoolGetMinWorkers(srv->workers)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set min_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "max_workers",
                                           virThreadPoolGetMaxWorkers(srv->workers)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set max_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "priority_workers",
                                           virThreadPoolGetPriorityWorkers(srv->workers)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set priority_workers data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "max_clients", srv->nclients_max) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set max_clients data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "keepaliveInterval", srv->keepaliveInterval) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set keepaliveInterval data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendNumberUint(object, "keepaliveCount", srv->keepaliveCount) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set keepaliveCount data in JSON document"));
        goto error;
    }
    if (virJSONValueObjectAppendBoolean(object, "keepaliveRequired", srv->keepaliveRequired) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set keepaliveRequired data in JSON document"));
        goto error;
    }

    if (srv->mdnsGroupName &&
        virJSONValueObjectAppendString(object, "mdnsGroupName", srv->mdnsGroupName) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Cannot set mdnsGroupName data in JSON document"));
        goto error;
    }

    services = virJSONValueNewArray();
    if (virJSONValueObjectAppend(object, "services", services) < 0) {
        virJSONValueFree(services);
        goto error;
    }

646
    for (i = 0; i < srv->nservices; i++) {
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        virJSONValuePtr child;
        if (!(child = virNetServerServicePreExecRestart(srv->services[i])))
            goto error;

        if (virJSONValueArrayAppend(services, child) < 0) {
            virJSONValueFree(child);
            goto error;
        }
    }

    clients = virJSONValueNewArray();
    if (virJSONValueObjectAppend(object, "clients", clients) < 0) {
        virJSONValueFree(clients);
        goto error;
    }

663
    for (i = 0; i < srv->nclients; i++) {
664 665 666 667 668 669 670 671 672 673
        virJSONValuePtr child;
        if (!(child = virNetServerClientPreExecRestart(srv->clients[i])))
            goto error;

        if (virJSONValueArrayAppend(clients, child) < 0) {
            virJSONValueFree(child);
            goto error;
        }
    }

674
    virObjectUnlock(srv);
675 676 677 678 679

    return object;

error:
    virJSONValueFree(object);
680
    virObjectUnlock(srv);
681 682 683 684
    return NULL;
}


685 686 687
bool virNetServerIsPrivileged(virNetServerPtr srv)
{
    bool priv;
688
    virObjectLock(srv);
689
    priv = srv->privileged;
690
    virObjectUnlock(srv);
691 692 693 694 695
    return priv;
}


void virNetServerAutoShutdown(virNetServerPtr srv,
696
                              unsigned int timeout)
697
{
698
    virObjectLock(srv);
699 700 701

    srv->autoShutdownTimeout = timeout;

702
    virObjectUnlock(srv);
703 704
}

705

706
#if defined(HAVE_DBUS) && defined(DBUS_TYPE_UNIX_FD)
707 708 709 710 711 712 713
static void virNetServerGotInhibitReply(DBusPendingCall *pending,
                                        void *opaque)
{
    virNetServerPtr srv = opaque;
    DBusMessage *reply;
    int fd;

714
    virObjectLock(srv);
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
    srv->autoShutdownCallingInhibit = false;

    VIR_DEBUG("srv=%p", srv);

    reply = dbus_pending_call_steal_reply(pending);
    if (reply == NULL)
        goto cleanup;

    if (dbus_message_get_args(reply, NULL,
                              DBUS_TYPE_UNIX_FD, &fd,
                              DBUS_TYPE_INVALID)) {
        if (srv->autoShutdownInhibitions) {
            srv->autoShutdownInhibitFd = fd;
        } else {
            /* We stopped the last VM since we made the inhibit call */
            VIR_FORCE_CLOSE(fd);
        }
    }
    dbus_message_unref(reply);

cleanup:
736
    virObjectUnlock(srv);
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
}


/* As per: http://www.freedesktop.org/wiki/Software/systemd/inhibit */
static void virNetServerCallInhibit(virNetServerPtr srv,
                                    const char *what,
                                    const char *who,
                                    const char *why,
                                    const char *mode)
{
    DBusMessage *message;
    DBusPendingCall *pendingReply;
    DBusConnection *systemBus;

    VIR_DEBUG("srv=%p what=%s who=%s why=%s mode=%s",
              srv, NULLSTR(what), NULLSTR(who), NULLSTR(why), NULLSTR(mode));

    if (!(systemBus = virDBusGetSystemBus()))
        return;

    /* Only one outstanding call at a time */
    if (srv->autoShutdownCallingInhibit)
        return;

    message = dbus_message_new_method_call("org.freedesktop.login1",
                                           "/org/freedesktop/login1",
                                           "org.freedesktop.login1.Manager",
                                           "Inhibit");
    if (message == NULL)
        return;

    dbus_message_append_args(message,
                             DBUS_TYPE_STRING, &what,
                             DBUS_TYPE_STRING, &who,
                             DBUS_TYPE_STRING, &why,
                             DBUS_TYPE_STRING, &mode,
                             DBUS_TYPE_INVALID);

    pendingReply = NULL;
    if (dbus_connection_send_with_reply(systemBus, message,
                                        &pendingReply,
                                        25*1000)) {
        dbus_pending_call_set_notify(pendingReply,
                                     virNetServerGotInhibitReply,
                                     srv, NULL);
        srv->autoShutdownCallingInhibit = true;
    }
    dbus_message_unref(message);
}
#endif

788 789
void virNetServerAddShutdownInhibition(virNetServerPtr srv)
{
790
    virObjectLock(srv);
791
    srv->autoShutdownInhibitions++;
792 793 794

    VIR_DEBUG("srv=%p inhibitions=%zu", srv, srv->autoShutdownInhibitions);

795
#if defined(HAVE_DBUS) && defined(DBUS_TYPE_UNIX_FD)
796 797 798 799 800 801 802 803
    if (srv->autoShutdownInhibitions == 1)
        virNetServerCallInhibit(srv,
                                "shutdown",
                                _("Libvirt"),
                                _("Virtual machines need to be saved"),
                                "delay");
#endif

804
    virObjectUnlock(srv);
805 806 807 808 809
}


void virNetServerRemoveShutdownInhibition(virNetServerPtr srv)
{
810
    virObjectLock(srv);
811
    srv->autoShutdownInhibitions--;
812 813 814 815 816 817

    VIR_DEBUG("srv=%p inhibitions=%zu", srv, srv->autoShutdownInhibitions);

    if (srv->autoShutdownInhibitions == 0)
        VIR_FORCE_CLOSE(srv->autoShutdownInhibitFd);

818
    virObjectUnlock(srv);
819 820 821 822
}



823 824 825 826
static sig_atomic_t sigErrors = 0;
static int sigLastErrno = 0;
static int sigWrite = -1;

827 828 829
static void
virNetServerSignalHandler(int sig, siginfo_t * siginfo,
                          void* context ATTRIBUTE_UNUSED)
830 831 832
{
    int origerrno;
    int r;
833 834 835 836 837 838
    siginfo_t tmp;

    if (SA_SIGINFO)
        tmp = *siginfo;
    else
        memset(&tmp, 0, sizeof(tmp));
839 840

    /* set the sig num in the struct */
841
    tmp.si_signo = sig;
842 843

    origerrno = errno;
844
    r = safewrite(sigWrite, &tmp, sizeof(tmp));
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    if (r == -1) {
        sigErrors++;
        sigLastErrno = errno;
    }
    errno = origerrno;
}

static void
virNetServerSignalEvent(int watch,
                        int fd ATTRIBUTE_UNUSED,
                        int events ATTRIBUTE_UNUSED,
                        void *opaque) {
    virNetServerPtr srv = opaque;
    siginfo_t siginfo;
    int i;

861
    virObjectLock(srv);
862 863 864 865 866 867 868 869 870

    if (saferead(srv->sigread, &siginfo, sizeof(siginfo)) != sizeof(siginfo)) {
        virReportSystemError(errno, "%s",
                             _("Failed to read from signal pipe"));
        virEventRemoveHandle(watch);
        srv->sigwatch = -1;
        goto cleanup;
    }

871
    for (i = 0; i < srv->nsignals; i++) {
872 873 874
        if (siginfo.si_signo == srv->signals[i]->signum) {
            virNetServerSignalFunc func = srv->signals[i]->func;
            void *funcopaque = srv->signals[i]->opaque;
875
            virObjectUnlock(srv);
876 877 878 879 880
            func(srv, &siginfo, funcopaque);
            return;
        }
    }

881 882
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unexpected signal received: %d"), siginfo.si_signo);
883 884

cleanup:
885
    virObjectUnlock(srv);
886 887 888 889
}

static int virNetServerSignalSetup(virNetServerPtr srv)
{
E
Eric Blake 已提交
890
    int fds[2] = { -1, -1 };
891 892 893 894 895 896 897 898 899 900 901 902 903 904

    if (srv->sigwrite != -1)
        return 0;

    if (pipe2(fds, O_CLOEXEC|O_NONBLOCK) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to create signal pipe"));
        return -1;
    }

    if ((srv->sigwatch = virEventAddHandle(fds[0],
                                           VIR_EVENT_HANDLE_READABLE,
                                           virNetServerSignalEvent,
                                           srv, NULL)) < 0) {
905 906
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to add signal handle watch"));
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        goto error;
    }

    srv->sigread = fds[0];
    srv->sigwrite = fds[1];
    sigWrite = fds[1];

    return 0;

error:
    VIR_FORCE_CLOSE(fds[0]);
    VIR_FORCE_CLOSE(fds[1]);
    return -1;
}

int virNetServerAddSignalHandler(virNetServerPtr srv,
                                 int signum,
                                 virNetServerSignalFunc func,
                                 void *opaque)
{
927
    virNetServerSignalPtr sigdata = NULL;
928 929
    struct sigaction sig_action;

930
    virObjectLock(srv);
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

    if (virNetServerSignalSetup(srv) < 0)
        goto error;

    if (VIR_EXPAND_N(srv->signals, srv->nsignals, 1) < 0)
        goto no_memory;

    if (VIR_ALLOC(sigdata) < 0)
        goto no_memory;

    sigdata->signum = signum;
    sigdata->func = func;
    sigdata->opaque = opaque;

    memset(&sig_action, 0, sizeof(sig_action));
    sig_action.sa_sigaction = virNetServerSignalHandler;
    sig_action.sa_flags = SA_SIGINFO;
    sigemptyset(&sig_action.sa_mask);

    sigaction(signum, &sig_action, &sigdata->oldaction);

    srv->signals[srv->nsignals-1] = sigdata;

954
    virObjectUnlock(srv);
955 956 957 958 959 960
    return 0;

no_memory:
    virReportOOMError();
error:
    VIR_FREE(sigdata);
961
    virObjectUnlock(srv);
962 963 964 965 966 967
    return -1;
}



int virNetServerAddService(virNetServerPtr srv,
968
                           virNetServerServicePtr svc,
969
                           const char *mdnsEntryName)
970
{
971
    virObjectLock(srv);
972 973 974 975

    if (VIR_EXPAND_N(srv->services, srv->nservices, 1) < 0)
        goto no_memory;

976 977 978
    if (mdnsEntryName) {
        int port = virNetServerServiceGetPort(svc);

E
Eric Blake 已提交
979 980 981
        if (!virNetServerMDNSAddEntry(srv->mdnsGroup,
                                      mdnsEntryName,
                                      port))
982 983 984
            goto error;
    }

985
    srv->services[srv->nservices-1] = svc;
986
    virObjectRef(svc);
987 988 989 990 991

    virNetServerServiceSetDispatcher(svc,
                                     virNetServerDispatchNewClient,
                                     srv);

992
    virObjectUnlock(srv);
993 994 995 996
    return 0;

no_memory:
    virReportOOMError();
997
error:
998
    virObjectUnlock(srv);
999 1000 1001 1002 1003 1004
    return -1;
}

int virNetServerAddProgram(virNetServerPtr srv,
                           virNetServerProgramPtr prog)
{
1005
    virObjectLock(srv);
1006 1007 1008 1009

    if (VIR_EXPAND_N(srv->programs, srv->nprograms, 1) < 0)
        goto no_memory;

1010
    srv->programs[srv->nprograms-1] = virObjectRef(prog);
1011

1012
    virObjectUnlock(srv);
1013 1014 1015 1016
    return 0;

no_memory:
    virReportOOMError();
1017
    virObjectUnlock(srv);
1018 1019 1020
    return -1;
}

1021
#if WITH_GNUTLS
1022 1023 1024
int virNetServerSetTLSContext(virNetServerPtr srv,
                              virNetTLSContextPtr tls)
{
1025
    srv->tls = virObjectRef(tls);
1026 1027
    return 0;
}
1028
#endif
1029 1030 1031 1032 1033 1034


static void virNetServerAutoShutdownTimer(int timerid ATTRIBUTE_UNUSED,
                                          void *opaque) {
    virNetServerPtr srv = opaque;

1035
    virObjectLock(srv);
1036

1037
    if (!srv->autoShutdownInhibitions) {
1038 1039 1040 1041
        VIR_DEBUG("Automatic shutdown triggered");
        srv->quit = 1;
    }

1042
    virObjectUnlock(srv);
1043 1044 1045 1046 1047 1048 1049 1050
}


void virNetServerUpdateServices(virNetServerPtr srv,
                                bool enabled)
{
    int i;

1051
    virObjectLock(srv);
1052
    for (i = 0; i < srv->nservices; i++)
1053 1054
        virNetServerServiceToggle(srv->services[i], enabled);

1055
    virObjectUnlock(srv);
1056 1057 1058 1059 1060 1061 1062 1063 1064
}


void virNetServerRun(virNetServerPtr srv)
{
    int timerid = -1;
    int timerActive = 0;
    int i;

1065
    virObjectLock(srv);
1066

1067 1068 1069 1070
    if (srv->mdns &&
        virNetServerMDNSStart(srv->mdns) < 0)
        goto cleanup;

1071 1072
    srv->quit = 0;

1073 1074 1075 1076
    if (srv->autoShutdownTimeout &&
        (timerid = virEventAddTimeout(-1,
                                      virNetServerAutoShutdownTimer,
                                      srv, NULL)) < 0) {
1077 1078
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to register shutdown timeout"));
1079 1080 1081
        goto cleanup;
    }

1082
    VIR_DEBUG("srv=%p quit=%d", srv, srv->quit);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    while (!srv->quit) {
        /* A shutdown timeout is specified, so check
         * if any drivers have active state, if not
         * shutdown after timeout seconds
         */
        if (srv->autoShutdownTimeout) {
            if (timerActive) {
                if (srv->clients) {
                    VIR_DEBUG("Deactivating shutdown timer %d", timerid);
                    virEventUpdateTimeout(timerid, -1);
                    timerActive = 0;
                }
            } else {
                if (!srv->clients) {
                    VIR_DEBUG("Activating shutdown timer %d", timerid);
                    virEventUpdateTimeout(timerid,
                                          srv->autoShutdownTimeout * 1000);
                    timerActive = 1;
                }
            }
        }

1105
        virObjectUnlock(srv);
1106
        if (virEventRunDefaultImpl() < 0) {
1107
            virObjectLock(srv);
1108 1109 1110
            VIR_DEBUG("Loop iteration error, exiting");
            break;
        }
1111
        virObjectLock(srv);
1112 1113

    reprocess:
1114
        for (i = 0; i < srv->nclients; i++) {
1115 1116 1117
            /* Coverity 5.3.0 couldn't see that srv->clients is non-NULL
             * if srv->nclients is non-zero.  */
            sa_assert(srv->clients);
1118 1119 1120
            if (virNetServerClientWantClose(srv->clients[i]))
                virNetServerClientClose(srv->clients[i]);
            if (virNetServerClientIsClosed(srv->clients[i])) {
1121
                virNetServerClientPtr client = srv->clients[i];
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
                if (srv->nclients > 1) {
                    memmove(srv->clients + i,
                            srv->clients + i + 1,
                            sizeof(*srv->clients) * (srv->nclients - (i + 1)));
                    VIR_SHRINK_N(srv->clients, srv->nclients, 1);
                } else {
                    VIR_FREE(srv->clients);
                    srv->nclients = 0;
                }

1132 1133 1134 1135
                virObjectUnlock(srv);
                virObjectUnref(client);
                virObjectLock(srv);

1136 1137 1138 1139 1140 1141
                goto reprocess;
            }
        }
    }

cleanup:
1142
    virObjectUnlock(srv);
1143 1144 1145 1146 1147
}


void virNetServerQuit(virNetServerPtr srv)
{
1148
    virObjectLock(srv);
1149

1150
    VIR_DEBUG("Quit requested %p", srv);
1151 1152
    srv->quit = 1;

1153
    virObjectUnlock(srv);
1154 1155
}

1156
void virNetServerDispose(void *obj)
1157
{
1158
    virNetServerPtr srv = obj;
1159 1160
    int i;

1161 1162
    VIR_FORCE_CLOSE(srv->autoShutdownInhibitFd);

1163
    for (i = 0; i < srv->nservices; i++)
1164 1165 1166 1167
        virNetServerServiceToggle(srv->services[i], false);

    virThreadPoolFree(srv->workers);

1168
    for (i = 0; i < srv->nsignals; i++) {
1169 1170 1171 1172 1173 1174 1175 1176 1177
        sigaction(srv->signals[i]->signum, &srv->signals[i]->oldaction, NULL);
        VIR_FREE(srv->signals[i]);
    }
    VIR_FREE(srv->signals);
    VIR_FORCE_CLOSE(srv->sigread);
    VIR_FORCE_CLOSE(srv->sigwrite);
    if (srv->sigwatch > 0)
        virEventRemoveHandle(srv->sigwatch);

1178
    for (i = 0; i < srv->nservices; i++)
1179
        virObjectUnref(srv->services[i]);
1180 1181
    VIR_FREE(srv->services);

1182
    for (i = 0; i < srv->nprograms; i++)
1183
        virObjectUnref(srv->programs[i]);
1184 1185
    VIR_FREE(srv->programs);

1186
    for (i = 0; i < srv->nclients; i++) {
1187
        virNetServerClientClose(srv->clients[i]);
1188
        virObjectUnref(srv->clients[i]);
1189 1190 1191
    }
    VIR_FREE(srv->clients);

1192
    VIR_FREE(srv->mdnsGroupName);
1193
    virNetServerMDNSFree(srv->mdns);
1194
}
1195 1196 1197 1198 1199 1200 1201 1202

void virNetServerClose(virNetServerPtr srv)
{
    int i;

    if (!srv)
        return;

1203
    virObjectLock(srv);
1204 1205 1206 1207 1208

    for (i = 0; i < srv->nservices; i++) {
        virNetServerServiceClose(srv->services[i]);
    }

1209
    virObjectUnlock(srv);
1210
}
1211 1212 1213 1214

bool virNetServerKeepAliveRequired(virNetServerPtr srv)
{
    bool required;
1215
    virObjectLock(srv);
1216
    required = srv->keepaliveRequired;
1217
    virObjectUnlock(srv);
1218 1219
    return required;
}