qemu_slirp.c 12.4 KB
Newer Older
M
Marc-André Lureau 已提交
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 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/*
 * qemu_slirp.c: QEMU Slirp support
 *
 * 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 "qemu_dbus.h"
#include "qemu_extdevice.h"
#include "qemu_security.h"
#include "qemu_slirp.h"
#include "viralloc.h"
#include "virenum.h"
#include "virerror.h"
#include "virjson.h"
#include "virlog.h"
#include "virpidfile.h"
#include "virstring.h"
#include "virtime.h"

#define VIR_FROM_THIS VIR_FROM_NONE

VIR_LOG_INIT("qemu.slirp");

VIR_ENUM_IMPL(qemuSlirpFeature,
              QEMU_SLIRP_FEATURE_LAST,
              "",
              "ipv4",
              "ipv6",
              "tftp",
              "dbus-address",
              "dbus-p2p",
              "migrate",
              "restrict",
              "exit-with-parent",
);


void
qemuSlirpFree(qemuSlirpPtr slirp)
{
    if (!slirp)
        return;

    VIR_FORCE_CLOSE(slirp->fd[0]);
    VIR_FORCE_CLOSE(slirp->fd[1]);
    virBitmapFree(slirp->features);
    VIR_FREE(slirp);
}


void
qemuSlirpSetFeature(qemuSlirpPtr slirp,
                    qemuSlirpFeature feature)
{
    ignore_value(virBitmapSetBit(slirp->features, feature));
}


bool
qemuSlirpHasFeature(const qemuSlirp *slirp,
                    qemuSlirpFeature feature)
{
    return virBitmapIsBitSet(slirp->features, feature);
}


qemuSlirpPtr
qemuSlirpNew(void)
{
J
Ján Tomko 已提交
84
    g_autoptr(qemuSlirp) slirp = NULL;
M
Marc-André Lureau 已提交
85 86 87 88 89 90 91 92

    if (VIR_ALLOC(slirp) < 0 ||
        !(slirp->features = virBitmapNew(QEMU_SLIRP_FEATURE_LAST)))
        return NULL;

    slirp->pid = (pid_t)-1;
    slirp->fd[0] = slirp->fd[1] = -1;

J
Ján Tomko 已提交
93
    return g_steal_pointer(&slirp);
M
Marc-André Lureau 已提交
94 95 96 97 98 99
}


qemuSlirpPtr
qemuSlirpNewForHelper(const char *helper)
{
J
Ján Tomko 已提交
100 101
    g_autoptr(qemuSlirp) slirp = NULL;
    g_autoptr(virCommand) cmd = NULL;
102
    g_autofree char *output = NULL;
J
Ján Tomko 已提交
103
    g_autoptr(virJSONValue) doc = NULL;
M
Marc-André Lureau 已提交
104 105 106 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 135 136 137 138 139 140 141 142 143
    virJSONValuePtr featuresJSON;
    size_t i, nfeatures;

    if (!helper)
        return NULL;

    slirp = qemuSlirpNew();
    if (!slirp) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to allocate slirp for '%s'"), helper);
        return NULL;
    }

    cmd = virCommandNewArgList(helper, "--print-capabilities", NULL);
    virCommandSetOutputBuffer(cmd, &output);
    if (virCommandRun(cmd, NULL) < 0)
        return NULL;

    if (!(doc = virJSONValueFromString(output)) ||
        !(featuresJSON = virJSONValueObjectGetArray(doc, "features"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to parse json capabilities '%s'"),
                       helper);
        return NULL;
    }

    nfeatures = virJSONValueArraySize(featuresJSON);
    for (i = 0; i < nfeatures; i++) {
        virJSONValuePtr item = virJSONValueArrayGet(featuresJSON, i);
        const char *tmpStr = virJSONValueGetString(item);
        int tmp;

        if ((tmp = qemuSlirpFeatureTypeFromString(tmpStr)) <= 0) {
            VIR_WARN("unknown slirp feature %s", tmpStr);
            continue;
        }

        qemuSlirpSetFeature(slirp, tmp);
    }

J
Ján Tomko 已提交
144
    return g_steal_pointer(&slirp);
M
Marc-André Lureau 已提交
145 146 147 148 149 150 151 152
}


static char *
qemuSlirpCreatePidFilename(virQEMUDriverConfigPtr cfg,
                           const virDomainDef *def,
                           const char *alias)
{
153 154
    g_autofree char *shortName = NULL;
    g_autofree char *name = NULL;
M
Marc-André Lureau 已提交
155

156
    if (!(shortName = virDomainDefGetShortName(def)))
M
Marc-André Lureau 已提交
157 158
        return NULL;

159 160
    name = g_strdup_printf("%s-%s-slirp", shortName, alias);

M
Marc-André Lureau 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    return virPidFileBuildPath(cfg->slirpStateDir, name);
}


int
qemuSlirpOpen(qemuSlirpPtr slirp,
              virQEMUDriverPtr driver,
              virDomainDefPtr def)
{
    int rc, pair[2] = { -1, -1 };

    if (qemuSecuritySetSocketLabel(driver->securityManager, def) < 0)
        goto error;

    rc = socketpair(AF_UNIX, SOCK_DGRAM, 0, pair);

    if (qemuSecurityClearSocketLabel(driver->securityManager, def) < 0)
        goto error;

    if (rc < 0) {
        virReportSystemError(errno, "%s", _("failed to create socketpair"));
        goto error;
    }

    slirp->fd[0] = pair[0];
    slirp->fd[1] = pair[1];

    return 0;

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


int
qemuSlirpGetFD(qemuSlirpPtr slirp)
{
    int fd = slirp->fd[0];
    slirp->fd[0] = -1;
    return fd;
}


static char *
qemuSlirpGetDBusVMStateId(virDomainNetDefPtr net)
{
    char macstr[VIR_MAC_STRING_BUFLEN] = "";
    char *id = NULL;

    /* can't use alias, because it's not stable across restarts */
213
    id = g_strdup_printf("slirp-%s", virMacAddrFormat(&net->mac, macstr));
M
Marc-André Lureau 已提交
214 215 216 217 218 219 220 221 222 223

    return id;
}


static char *
qemuSlirpGetDBusPath(virQEMUDriverConfigPtr cfg,
                     const virDomainDef *def,
                     const char *alias)
{
224
    g_autofree char *shortName = NULL;
M
Marc-André Lureau 已提交
225 226
    char *path = NULL;

227
    if (!(shortName = virDomainDefGetShortName(def)))
M
Marc-André Lureau 已提交
228 229
        return NULL;

230 231 232
    path = g_strdup_printf("%s/%s-%s-slirp",
                           cfg->slirpStateDir, shortName, alias);

M
Marc-André Lureau 已提交
233 234 235 236 237 238 239 240 241 242 243
    return path;
}


void
qemuSlirpStop(qemuSlirpPtr slirp,
              virDomainObjPtr vm,
              virQEMUDriverPtr driver,
              virDomainNetDefPtr net,
              bool hot)
{
244
    g_autoptr(virQEMUDriverConfig) cfg = virQEMUDriverGetConfig(driver);
245 246 247
    g_autofree char *pidfile = NULL;
    g_autofree char *dbus_path = NULL;
    g_autofree char *id = qemuSlirpGetDBusVMStateId(net);
M
Marc-André Lureau 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    virErrorPtr orig_err;

    if (!(pidfile = qemuSlirpCreatePidFilename(cfg, vm->def, net->info.alias))) {
        VIR_WARN("Unable to construct slirp pidfile path");
        return;
    }

    if (id) {
        qemuDBusVMStateRemove(driver, vm, id, hot);
    } else {
        VIR_WARN("Unable to construct vmstate id");
    }

    virErrorPreserveLast(&orig_err);
262 263 264 265
    if (virPidFileForceCleanupPath(pidfile) < 0) {
        VIR_WARN("Unable to kill slirp process");
    } else {
        slirp->pid = 0;
M
Marc-André Lureau 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    }

    dbus_path = qemuSlirpGetDBusPath(cfg, vm->def, net->info.alias);
    if (dbus_path) {
        if (unlink(dbus_path) < 0 &&
            errno != ENOENT) {
            virReportSystemError(errno,
                                 _("Unable to remove stale dbus socket %s"),
                                 dbus_path);
        }
    } else {
        VIR_WARN("Unable to construct dbus socket path");
    }

    virErrorRestore(&orig_err);
}


int
qemuSlirpStart(qemuSlirpPtr slirp,
               virDomainObjPtr vm,
               virQEMUDriverPtr driver,
               virDomainNetDefPtr net,
               bool hotplug,
               bool incoming)
{
292
    g_autoptr(virQEMUDriverConfig) cfg = virQEMUDriverGetConfig(driver);
J
Ján Tomko 已提交
293
    g_autoptr(virCommand) cmd = NULL;
294 295 296 297
    g_autofree char *pidfile = NULL;
    g_autofree char *dbus_path = NULL;
    g_autofree char *dbus_addr = NULL;
    g_autofree char *id = NULL;
M
Marc-André Lureau 已提交
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
    size_t i;
    const unsigned long long timeout = 5 * 1000; /* ms */
    pid_t pid = (pid_t) -1;
    int rc;
    int exitstatus = 0;
    int cmdret = 0;
    VIR_AUTOCLOSE errfd = -1;

    if (incoming &&
        !qemuSlirpHasFeature(slirp, QEMU_SLIRP_FEATURE_MIGRATE)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("The slirp-helper doesn't support migration"));
    }

    if (!(pidfile = qemuSlirpCreatePidFilename(cfg, vm->def, net->info.alias)))
        return -1;

    if (!(cmd = virCommandNew(cfg->slirpHelperName)))
        return -1;

    virCommandClearCaps(cmd);
    virCommandSetPidFile(cmd, pidfile);
    virCommandSetErrorFD(cmd, &errfd);
    virCommandDaemonize(cmd);

    virCommandAddArgFormat(cmd, "--fd=%d", slirp->fd[1]);
    virCommandPassFD(cmd, slirp->fd[1],
                     VIR_COMMAND_PASS_FD_CLOSE_PARENT);
    slirp->fd[1] = -1;

    for (i = 0; i < net->guestIP.nips; i++) {
        const virNetDevIPAddr *ip = net->guestIP.ips[i];
330
        g_autofree char *addr = NULL;
M
Marc-André Lureau 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        const char *opt = "";

        if (!(addr = virSocketAddrFormat(&ip->address)))
            return -1;

        if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET))
            opt = "--net";
        if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET6))
            opt = "--prefix-ipv6";

        virCommandAddArgFormat(cmd, "%s=%s", opt, addr);

        if (ip->prefix) {
            if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET)) {
                virSocketAddr netmask;
346
                g_autofree char *netmaskStr = NULL;
M
Marc-André Lureau 已提交
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

                if (virSocketAddrPrefixToNetmask(ip->prefix, &netmask, AF_INET) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Failed to translate prefix %d to netmask"),
                                   ip->prefix);
                    return -1;
                }
                if (!(netmaskStr = virSocketAddrFormat(&netmask)))
                    return -1;
                virCommandAddArgFormat(cmd, "--mask=%s", netmaskStr);
            }
            if (VIR_SOCKET_ADDR_IS_FAMILY(&ip->address, AF_INET6))
                virCommandAddArgFormat(cmd, "--prefix-length-ipv6=%u", ip->prefix);
        }
    }

    if (qemuSlirpHasFeature(slirp, QEMU_SLIRP_FEATURE_DBUS_P2P)) {
        if (!(id = qemuSlirpGetDBusVMStateId(net)))
            return -1;

        if (!(dbus_path = qemuSlirpGetDBusPath(cfg, vm->def, net->info.alias)))
            return -1;

        if (unlink(dbus_path) < 0 && errno != ENOENT) {
            virReportSystemError(errno, _("Unable to unlink %s"), dbus_path);
            return -1;
        }

375
        dbus_addr = g_strdup_printf("unix:path=%s", dbus_path);
M
Marc-André Lureau 已提交
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 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 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

        virCommandAddArgFormat(cmd, "--dbus-id=%s", id);

        virCommandAddArgFormat(cmd, "--dbus-p2p=%s", dbus_addr);

        if (incoming &&
            qemuSlirpHasFeature(slirp, QEMU_SLIRP_FEATURE_MIGRATE))
            virCommandAddArg(cmd, "--dbus-incoming");
    }

    if (qemuSlirpHasFeature(slirp, QEMU_SLIRP_FEATURE_EXIT_WITH_PARENT))
        virCommandAddArg(cmd, "--exit-with-parent");

    if (qemuExtDeviceLogCommand(driver, vm, cmd, "slirp") < 0)
        return -1;

    if (qemuSecurityCommandRun(driver, vm, cmd, -1, -1, &exitstatus, &cmdret) < 0)
        return -1;

    if (cmdret < 0 || exitstatus != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not start 'slirp'. exitstatus: %d"), exitstatus);
        goto error;
    }

    rc = virPidFileReadPath(pidfile, &pid);
    if (rc < 0) {
        virReportSystemError(-rc,
                             _("Unable to read slirp pidfile '%s'"),
                             pidfile);
        goto error;
    }

    if (dbus_path) {
        virTimeBackOffVar timebackoff;

        if (virTimeBackOffStart(&timebackoff, 1, timeout) < 0)
            goto error;

        while (virTimeBackOffWait(&timebackoff)) {
            char errbuf[1024] = { 0 };

            if (virFileExists(dbus_path))
                break;

            if (virProcessKill(pid, 0) == 0)
                continue;

            if (saferead(errfd, errbuf, sizeof(errbuf) - 1) < 0) {
                virReportSystemError(errno,
                                     _("slirp helper %s died unexpectedly"),
                                     cfg->prHelperName);
            } else {
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("slirp helper died and reported: %s"), errbuf);
            }
            goto error;
        }

        if (!virFileExists(dbus_path)) {
            virReportError(VIR_ERR_OPERATION_TIMEOUT, "%s",
                           _("slirp dbus socket did not show up"));
            goto error;
        }
    }

    if (qemuSlirpHasFeature(slirp, QEMU_SLIRP_FEATURE_MIGRATE) &&
        qemuDBusVMStateAdd(driver, vm, id, dbus_addr, hotplug) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to register slirp migration"));
        goto error;
    }

    slirp->pid = pid;
    return 0;

 error:
    if (pid != -1)
        virProcessKillPainfully(pid, true);
    if (pidfile)
        unlink(pidfile);
    if (dbus_path)
        unlink(dbus_path);
    return -1;
}