phyp_driver.c 57.4 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

/*
 * Copyright IBM Corp. 2009
 *
 * phyp_driver.c: ssh layer to access Power Hypervisors
 *
 * Authors:
 *  Eduardo Otubo <otubo at linux.vnet.ibm.com>
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#include <config.h>

#include <sys/types.h>
28
#include <sys/stat.h>
29 30 31 32 33 34 35 36 37
#include <limits.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
38 39 40 41 42
#include <libssh2.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
43 44 45
#include <fcntl.h>
#include <sys/utsname.h>
#include <domain_event.h>
46 47 48 49 50 51 52 53 54 55 56 57

#include "internal.h"
#include "util.h"
#include "datatypes.h"
#include "buf.h"
#include "memory.h"
#include "logging.h"
#include "driver.h"
#include "libvirt/libvirt.h"
#include "virterror_internal.h"
#include "uuid.h"
#include "domain_conf.h"
58
#include "nodeinfo.h"
59 60 61 62 63

#include "phyp_driver.h"

#define VIR_FROM_THIS VIR_FROM_PHYP

64 65 66 67
#define PHYP_ERROR(conn, code, fmt...)                                        \
    virReportErrorHelper(conn, VIR_FROM_PHYP, code, __FILE__, __FUNCTION__,   \
                         __LINE__, fmt)

68 69 70 71 72 73 74 75
/*
 * URI: phyp://user@[hmc|ivm]/managed_system
 * */

static virDrvOpenStatus
phypOpen(virConnectPtr conn,
         virConnectAuthPtr auth, int flags ATTRIBUTE_UNUSED)
{
76
    LIBSSH2_SESSION *session = NULL;
77
    ConnectionData *connection_data = NULL;
78
    char *string = NULL;
79
    size_t len = 0;
80
    int internal_socket;
81 82 83 84
    uuid_tablePtr uuid_table = NULL;
    phyp_driverPtr phyp_driver = NULL;
    char *char_ptr;
    char *managed_system;
85 86 87 88 89 90 91 92

    if (!conn || !conn->uri)
        return VIR_DRV_OPEN_DECLINED;

    if (conn->uri->scheme == NULL || STRNEQ(conn->uri->scheme, "phyp"))
        return VIR_DRV_OPEN_DECLINED;

    if (conn->uri->server == NULL) {
93
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
94
                   "%s", _("Missing server name in phyp:// URI"));
95 96 97
        return VIR_DRV_OPEN_ERROR;
    }

98
    if (conn->uri->path == NULL) {
99
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
100
                   "%s", _("Missing managed system name in phyp:// URI"));
101 102 103
        return VIR_DRV_OPEN_ERROR;
    }

104 105
    if (conn->uri->user == NULL) {
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
106
                   "%s", _("Missing username in phyp:// URI"));
107 108 109
        return VIR_DRV_OPEN_ERROR;
    }

110 111 112 113 114 115
    if (VIR_ALLOC(phyp_driver) < 0) {
        virReportOOMError(conn);
        goto failure;
    }

    if (VIR_ALLOC(uuid_table) < 0) {
116 117 118 119 120 121 122 123 124
        virReportOOMError(conn);
        goto failure;
    }

    if (VIR_ALLOC(connection_data) < 0) {
        virReportOOMError(conn);
        goto failure;
    }

125 126 127
    len = strlen(conn->uri->path) + 1;

    if (VIR_ALLOC_N(string, len) < 0) {
128 129 130 131
        virReportOOMError(conn);
        goto failure;
    }

132 133 134 135 136 137 138
    /* need to shift one byte in order to remove the first "/" of URI component */
    if (conn->uri->path[0] == '/')
        managed_system = strdup(conn->uri->path + 1);
    else
        managed_system = strdup(conn->uri->path);

    if (!managed_system) {
139 140 141 142 143 144 145 146 147 148 149 150
        virReportOOMError(conn);
        goto failure;
    }

    /* here we are handling only the first component of the path,
     * so skipping the second:
     * */
    char_ptr = strchr(managed_system, '/');

    if (char_ptr)
        *char_ptr = '\0';

151
    if (escape_specialcharacters(conn->uri->path, string, len) == -1) {
152
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
153
                   "%s", _("Error parsing 'path'. Invalid characters."));
154
        goto failure;
155 156
    }

157
    if ((session = openSSHSession(conn, auth, &internal_socket)) == NULL) {
158
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
159
                   "%s", _("Error while opening SSH session."));
160
        goto failure;
161
    }
162
    //conn->uri->path = string;
163 164 165
    connection_data->session = session;
    connection_data->auth = auth;

166 167 168 169 170 171 172 173 174
    uuid_table->nlpars = 0;
    uuid_table->lpars = NULL;

    phyp_driver->managed_system = managed_system;
    phyp_driver->uuid_table = uuid_table;
    if ((phyp_driver->caps = phypCapsInit()) == NULL) {
        virReportOOMError(conn);
        goto failure;
    }
175

176
    conn->privateData = phyp_driver;
177
    conn->networkPrivateData = connection_data;
178 179 180 181 182
    if (phypUUIDTable_Init(conn) == -1)
        goto failure;

    if ((phyp_driver->vios_id = phypGetVIOSPartitionID(conn)) == -1)
        goto failure;
183 184

    return VIR_DRV_OPEN_SUCCESS;
185

186
  failure:
187 188 189 190 191 192 193 194 195 196 197 198 199
    if (phyp_driver != NULL) {
        virCapabilitiesFree(phyp_driver->caps);
        VIR_FREE(phyp_driver->managed_system);
        VIR_FREE(phyp_driver);
    }

    phypUUIDTable_Free(uuid_table);

    if (session != NULL) {
        libssh2_session_disconnect(session, "Disconnecting...");
        libssh2_session_free(session);
    }

200 201 202 203
    VIR_FREE(connection_data);
    VIR_FREE(string);

    return VIR_DRV_OPEN_ERROR;
204 205 206 207 208 209
}

static int
phypClose(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
210
    phyp_driverPtr phyp_driver = conn->privateData;
211
    LIBSSH2_SESSION *session = connection_data->session;
212

213 214
    libssh2_session_disconnect(session, "Disconnecting...");
    libssh2_session_free(session);
215

216
    virCapabilitiesFree(phyp_driver->caps);
217
    phypUUIDTable_Free(phyp_driver->uuid_table);
218 219
    VIR_FREE(phyp_driver->managed_system);
    VIR_FREE(phyp_driver);
220 221 222 223
    VIR_FREE(connection_data);
    return 0;
}

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

static int
phypIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Phyp uses an SSH tunnel, so is always encrypted */
    return 1;
}


static int
phypIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    /* Phyp uses an SSH tunnel, so is always secure */
    return 1;
}


241 242 243
LIBSSH2_SESSION *
openSSHSession(virConnectPtr conn, virConnectAuthPtr auth,
               int *internal_socket)
244
{
245 246 247 248 249 250 251 252 253
    LIBSSH2_SESSION *session;
    const char *hostname = conn->uri->server;
    const char *username = conn->uri->user;
    const char *password = NULL;
    int sock;
    int rc;
    struct addrinfo *ai = NULL, *cur;
    struct addrinfo hints;
    int ret;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    char *pubkey = NULL;
    char *pvtkey = NULL;
    char *userhome = virGetUserDirectory(NULL, geteuid());
    struct stat pvt_stat, pub_stat;

    if (userhome == NULL)
        goto err;

    if (virAsprintf(&pubkey, "%s/.ssh/id_rsa.pub", userhome) < 0) {
        virReportOOMError(conn);
        goto err;
    }

    if (virAsprintf(&pvtkey, "%s/.ssh/id_rsa", userhome) < 0) {
        virReportOOMError(conn);
        goto err;
    }
271

272
    memset(&hints, 0, sizeof(hints));
273 274 275 276
    hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

277
    ret = getaddrinfo(hostname, "22", &hints, &ai);
278
    if (ret != 0) {
279 280
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
                   _("Error while getting %s address info"), hostname);
281 282 283
        goto err;
    }

284 285 286 287
    cur = ai;
    while (cur != NULL) {
        sock = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
        if (sock >= 0) {
288
            if (connect(sock, cur->ai_addr, cur->ai_addrlen) == 0) {
289 290
                goto connected;
            }
291
            close(sock);
292 293
        }
        cur = cur->ai_next;
294 295
    }

296 297
    PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
               _("Failed to connect to %s"), hostname);
298
    freeaddrinfo(ai);
299 300
    goto err;

301
  connected:
302 303 304 305 306 307 308 309 310 311 312 313 314 315

    (*internal_socket) = sock;

    /* Create a session instance */
    session = libssh2_session_init();
    if (!session)
        goto err;

    /* tell libssh2 we want it all done non-blocking */
    libssh2_session_set_blocking(session, 0);

    while ((rc = libssh2_session_startup(session, sock)) ==
           LIBSSH2_ERROR_EAGAIN) ;
    if (rc) {
316
        PHYP_ERROR(conn, VIR_ERR_INTERNAL_ERROR,
317
                   "%s", _("Failure establishing SSH session."));
318
        goto disconnect;
319 320
    }

321
    /* Trying authentication by pubkey */
322 323
    if (stat(pvtkey, &pvt_stat) || stat(pubkey, &pub_stat)) {
        rc = LIBSSH2_ERROR_SOCKET_NONE;
324
        goto keyboard_interactive;
325
    }
326

327 328
    while ((rc =
            libssh2_userauth_publickey_fromfile(session, username,
329 330 331
                                                pubkey,
                                                pvtkey,
                                                NULL)) ==
332
           LIBSSH2_ERROR_EAGAIN) ;
333

334
  keyboard_interactive:
335 336 337
    if (rc == LIBSSH2_ERROR_SOCKET_NONE
        || rc == LIBSSH2_ERROR_PUBLICKEY_UNRECOGNIZED
        || rc == LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED) {
338 339 340 341 342 343
        int i;
        int hasPassphrase = 0;

        virConnectCredential creds[] = {
            {VIR_CRED_PASSPHRASE, "password", "Password", NULL, NULL, 0},
        };
344 345

        if (!auth || !auth->cb) {
346
            PHYP_ERROR(conn, VIR_ERR_AUTH_FAILED,
347
                       "%s", _("No authentication callback provided."));
348
            goto disconnect;
349 350 351 352 353 354 355 356
        }

        for (i = 0; i < auth->ncredtype; i++) {
            if (auth->credtype[i] == VIR_CRED_PASSPHRASE)
                hasPassphrase = 1;
        }

        if (!hasPassphrase) {
357
            PHYP_ERROR(conn, VIR_ERR_AUTH_FAILED,
358
                       "%s", _("Required credentials are not supported."));
359
            goto disconnect;
360 361 362 363 364 365
        }

        int res =
            (auth->cb) (creds, ARRAY_CARDINALITY(creds), auth->cbdata);

        if (res < 0) {
366
            PHYP_ERROR(conn, VIR_ERR_AUTH_FAILED,
367
                       "%s", _("Unable to fetch credentials."));
368
            goto disconnect;
369 370
        }

371
        if (creds[0].result) {
372
            password = creds[0].result;
373
        } else {
374
            PHYP_ERROR(conn, VIR_ERR_AUTH_FAILED,
375
                       "%s", _("Unable to get password certificates"));
376
            goto disconnect;
377 378
        }

379 380 381 382
        while ((rc =
                libssh2_userauth_password(session, username,
                                          password)) ==
               LIBSSH2_ERROR_EAGAIN) ;
383

384
        if (rc) {
385
            PHYP_ERROR(conn, VIR_ERR_AUTH_FAILED,
386
                       "%s", _("Authentication failed"));
387
            goto disconnect;
388 389
        } else
            goto exit;
390 391 392 393 394 395 396

    } else if (rc == LIBSSH2_ERROR_NONE) {
        goto exit;

    } else if (rc == LIBSSH2_ERROR_ALLOC || rc == LIBSSH2_ERROR_SOCKET_SEND
               || rc == LIBSSH2_ERROR_SOCKET_TIMEOUT) {
        goto err;
397
    }
398

399 400 401
  disconnect:
    libssh2_session_disconnect(session, "Disconnecting...");
    libssh2_session_free(session);
402
  err:
403 404 405
    VIR_FREE(userhome);
    VIR_FREE(pubkey);
    VIR_FREE(pvtkey);
406
    VIR_FREE(password);
407 408 409
    return NULL;

  exit:
410 411 412
    VIR_FREE(userhome);
    VIR_FREE(pubkey);
    VIR_FREE(pvtkey);
413
    VIR_FREE(password);
414 415 416 417 418 419
    return session;
}

/* this functions is the layer that manipulates the ssh channel itself
 * and executes the commands on the remote machine */
static char *
420
phypExec(LIBSSH2_SESSION * session, char *cmd, int *exit_status,
421 422
         virConnectPtr conn)
{
423 424
    LIBSSH2_CHANNEL *channel;
    ConnectionData *connection_data = conn->networkPrivateData;
425
    virBuffer tex_ret = VIR_BUFFER_INITIALIZER;
426 427 428 429 430 431 432 433 434 435 436 437
    char buffer[0x4000] = { 0 };
    int exitcode;
    int bytecount = 0;
    int sock = connection_data->sock;
    int rc = 0;

    /* Exec non-blocking on the remove host */
    while ((channel = libssh2_channel_open_session(session)) == NULL &&
           libssh2_session_last_error(session, NULL, NULL, 0) ==
           LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
438

439
    if (channel == NULL) {
440 441 442
        goto err;
    }

443 444 445
    while ((rc = libssh2_channel_exec(channel, cmd)) ==
           LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
446 447
    }

448
    if (rc != 0) {
449 450 451
        goto err;
    }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    for (;;) {
        /* loop until we block */
        do {
            rc = libssh2_channel_read(channel, buffer, sizeof(buffer));
            if (rc > 0) {
                bytecount += rc;
                virBufferVSprintf(&tex_ret, "%s", buffer);
            }
        }
        while (rc > 0);

        /* this is due to blocking that would occur otherwise so we loop on
         * this condition */
        if (rc == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock, session);
        } else {
            break;
        }
    }
471

472
    exitcode = 127;
473

474 475 476
    while ((rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN) {
        waitsocket(sock, session);
    }
477

478 479
    if (rc == 0) {
        exitcode = libssh2_channel_get_exit_status(channel);
480 481
    }

482 483 484 485 486
    (*exit_status) = exitcode;
    libssh2_channel_free(channel);
    channel = NULL;
    goto exit;

487 488
  err:
    (*exit_status) = SSH_CMD_ERR;
489
    virBufferFreeAndReset(&tex_ret);
490 491 492 493
    return NULL;

  exit:
    if (virBufferError(&tex_ret)) {
494
        virBufferFreeAndReset(&tex_ret);
495 496 497 498 499 500 501 502
        virReportOOMError(conn);
        return NULL;
    }
    return virBufferContentAndReset(&tex_ret);
}

/* return the lpar_id given a name and a managed system name */
static int
503
phypGetLparID(LIBSSH2_SESSION * session, const char *managed_system,
504 505 506 507 508
              const char *name, virConnectPtr conn)
{
    int exit_status = 0;
    int lpar_id = 0;
    char *char_ptr;
509 510
    char *cmd = NULL;
    char *ret = NULL;
511 512 513 514 515 516 517 518

    if (virAsprintf(&cmd,
                    "lssyscfg -r lpar -m %s --filter lpar_names=%s -F lpar_id",
                    managed_system, name) < 0) {
        virReportOOMError(conn);
        goto err;
    }

519
    ret = phypExec(session, cmd, &exit_status, conn);
520

521
    if (exit_status < 0 || ret == NULL)
522 523
        goto err;

524
    if (virStrToLong_i(ret, &char_ptr, 10, &lpar_id) == -1)
525 526 527
        goto err;

    VIR_FREE(cmd);
528
    VIR_FREE(ret);
529 530 531 532
    return lpar_id;

  err:
    VIR_FREE(cmd);
533
    VIR_FREE(ret);
534 535 536 537 538
    return -1;
}

/* return the lpar name given a lpar_id and a managed system name */
static char *
539
phypGetLparNAME(LIBSSH2_SESSION * session, const char *managed_system,
540 541
                unsigned int lpar_id, virConnectPtr conn)
{
542 543
    char *cmd = NULL;
    char *ret = NULL;
544 545 546 547 548 549 550 551 552
    int exit_status = 0;

    if (virAsprintf(&cmd,
                    "lssyscfg -r lpar -m %s --filter lpar_ids=%d -F name",
                    managed_system, lpar_id) < 0) {
        virReportOOMError(conn);
        goto err;
    }

553
    ret = phypExec(session, cmd, &exit_status, conn);
554

555
    if (exit_status < 0 || ret == NULL)
556 557
        goto err;

558
    char *char_ptr = strchr(ret, '\n');
559 560 561 562 563

    if (char_ptr)
        *char_ptr = '\0';

    VIR_FREE(cmd);
564
    return ret;
565 566 567

  err:
    VIR_FREE(cmd);
568
    VIR_FREE(ret);
569 570 571 572
    return NULL;
}


573
/* Search into the uuid_table for a lpar_uuid given a lpar_id
574 575 576 577 578 579 580 581
 * and a managed system name
 *
 * return:  0 - record found
 *         -1 - not found
 * */
int
phypGetLparUUID(unsigned char *uuid, int lpar_id, virConnectPtr conn)
{
582 583 584
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    lparPtr *lpars = uuid_table->lpars;
585 586
    unsigned int i = 0;

587
    for (i = 0; i < uuid_table->nlpars; i++) {
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        if (lpars[i]->id == lpar_id) {
            memmove(uuid, lpars[i]->uuid, VIR_UUID_BUFLEN);
            return 0;
        }
    }

    return -1;
}

/*
 * type:
 * 0 - maxmem
 * 1 - memory
 * */
unsigned long
phypGetLparMem(virConnectPtr conn, const char *managed_system, int lpar_id,
               int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
607
    LIBSSH2_SESSION *session = connection_data->session;
608 609
    char *cmd = NULL;
    char *ret = NULL;
610 611 612 613 614 615 616 617 618
    char *char_ptr;
    int memory = 0;
    int exit_status = 0;

    if (type != 1 && type != 0)
        goto err;

    if (type) {
        if (virAsprintf(&cmd,
619 620
                        "lshwres -m %s -r mem --level lpar -F curr_mem "
                        "--filter lpar_ids=%d",
621 622 623 624 625 626
                        managed_system, lpar_id) < 0) {
            virReportOOMError(conn);
            goto err;
        }
    } else {
        if (virAsprintf(&cmd,
627 628
                        "lshwres -m %s -r mem --level lpar -F "
                        "curr_max_mem --filter lpar_ids=%d",
629 630 631 632 633 634
                        managed_system, lpar_id) < 0) {
            virReportOOMError(conn);
            goto err;
        }
    }

635
    ret = phypExec(session, cmd, &exit_status, conn);
636

637
    if (exit_status < 0 || ret == NULL)
638 639
        goto err;

640
    char_ptr = strchr(ret, '\n');
641

642 643
    if (char_ptr)
        *char_ptr = '\0';
644

645
    if (virStrToLong_i(ret, &char_ptr, 10, &memory) == -1)
646 647 648
        goto err;

    VIR_FREE(cmd);
649
    VIR_FREE(ret);
650 651 652 653
    return memory;

  err:
    VIR_FREE(cmd);
654
    VIR_FREE(ret);
655 656 657 658 659 660
    return 0;

}

unsigned long
phypGetLparCPU(virConnectPtr conn, const char *managed_system, int lpar_id)
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
{
    return phypGetLparCPUGeneric(conn, managed_system, lpar_id, 0);
}

static int
phypGetLparCPUMAX(virDomainPtr dom)
{
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    char *managed_system = phyp_driver->managed_system;

    return phypGetLparCPUGeneric(dom->conn, managed_system, dom->id, 1);
}

unsigned long
phypGetLparCPUGeneric(virConnectPtr conn, const char *managed_system,
                      int lpar_id, int type)
677 678
{
    ConnectionData *connection_data = conn->networkPrivateData;
679
    LIBSSH2_SESSION *session = connection_data->session;
680 681
    char *cmd = NULL;
    char *ret = NULL;
682
    char *char_ptr;
683 684 685
    int exit_status = 0;
    int vcpus = 0;

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    if (type) {
        if (virAsprintf(&cmd,
                        "lshwres -m %s -r proc --level lpar -F "
                        "curr_max_procs --filter lpar_ids=%d",
                        managed_system, lpar_id) < 0) {
            virReportOOMError(conn);
            goto err;
        }
    } else {
        if (virAsprintf(&cmd,
                        "lshwres -m %s -r proc --level lpar -F "
                        "curr_procs --filter lpar_ids=%d",
                        managed_system, lpar_id) < 0) {
            virReportOOMError(conn);
            goto err;
        }
702
    }
703
    ret = phypExec(session, cmd, &exit_status, conn);
704

705
    if (exit_status < 0 || ret == NULL)
706 707
        goto err;

708
    char_ptr = strchr(ret, '\n');
709 710 711 712

    if (char_ptr)
        *char_ptr = '\0';

713
    if (virStrToLong_i(ret, &char_ptr, 10, &vcpus) == -1)
714 715 716
        goto err;

    VIR_FREE(cmd);
717
    VIR_FREE(ret);
718 719 720 721
    return (unsigned long) vcpus;

  err:
    VIR_FREE(cmd);
722
    VIR_FREE(ret);
723 724 725 726 727 728 729 730
    return 0;
}

int
phypGetRemoteSlot(virConnectPtr conn, const char *managed_system,
                  const char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
731
    LIBSSH2_SESSION *session = connection_data->session;
732 733
    char *cmd = NULL;
    char *ret = NULL;
734 735 736 737 738
    char *char_ptr;
    int remote_slot = 0;
    int exit_status = 0;

    if (virAsprintf(&cmd,
739 740
                    "lshwres -m %s -r virtualio --rsubtype scsi -F "
                    "remote_slot_num --filter lpar_names=%s",
741 742 743 744
                    managed_system, lpar_name) < 0) {
        virReportOOMError(conn);
        goto err;
    }
745
    ret = phypExec(session, cmd, &exit_status, conn);
746

747
    if (exit_status < 0 || ret == NULL)
748 749
        goto err;

750
    char_ptr = strchr(ret, '\n');
751

752 753
    if (char_ptr)
        *char_ptr = '\0';
754

755
    if (virStrToLong_i(ret, &char_ptr, 10, &remote_slot) == -1)
756 757 758
        goto err;

    VIR_FREE(cmd);
759
    VIR_FREE(ret);
760 761 762 763
    return remote_slot;

  err:
    VIR_FREE(cmd);
764
    VIR_FREE(ret);
765
    return -1;
766 767 768 769 770 771 772
}

char *
phypGetBackingDevice(virConnectPtr conn, const char *managed_system,
                     char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
773
    LIBSSH2_SESSION *session = connection_data->session;
774 775
    char *cmd = NULL;
    char *ret = NULL;
776 777
    int remote_slot = 0;
    int exit_status = 0;
778 779
    char *char_ptr;
    char *backing_device = NULL;
780 781

    if ((remote_slot =
782
         phypGetRemoteSlot(conn, managed_system, lpar_name)) == -1)
783 784 785
        goto err;

    if (virAsprintf(&cmd,
786 787
                    "lshwres -m %s -r virtualio --rsubtype scsi -F "
                    "backing_devices --filter slots=%d",
788 789 790 791 792
                    managed_system, remote_slot) < 0) {
        virReportOOMError(conn);
        goto err;
    }

793
    ret = phypExec(session, cmd, &exit_status, conn);
794

795
    if (exit_status < 0 || ret == NULL)
796 797 798 799 800 801 802 803 804
        goto err;

    /* here is a little trick to deal returns of this kind:
     *
     * 0x8100000000000000//lv01
     *
     * the information we really need is only lv01, so we
     * need to skip a lot of things on the string.
     * */
805
    char_ptr = strchr(ret, '/');
806

807 808 809 810
    if (char_ptr) {
        char_ptr++;
        if (char_ptr[0] == '/')
            char_ptr++;
811 812
        else
            goto err;
813 814 815 816 817 818 819

        backing_device = strdup(char_ptr);

        if (backing_device == NULL) {
            virReportOOMError(conn);
            goto err;
        }
820 821
    } else {
        backing_device = ret;
822
        ret = NULL;
823 824
    }

825
    char_ptr = strchr(backing_device, '\n');
826 827 828 829 830

    if (char_ptr)
        *char_ptr = '\0';

    VIR_FREE(cmd);
831
    VIR_FREE(ret);
832 833 834 835
    return backing_device;

  err:
    VIR_FREE(cmd);
836
    VIR_FREE(ret);
837 838 839 840 841 842 843 844
    return NULL;

}

int
phypGetLparState(virConnectPtr conn, unsigned int lpar_id)
{
    ConnectionData *connection_data = conn->networkPrivateData;
845
    phyp_driverPtr phyp_driver = conn->privateData;
846
    LIBSSH2_SESSION *session = connection_data->session;
847 848
    char *cmd = NULL;
    char *ret = NULL;
849 850
    int exit_status = 0;
    char *char_ptr = NULL;
851
    char *managed_system = phyp_driver->managed_system;
852
    int state = VIR_DOMAIN_NOSTATE;
853 854 855 856 857

    if (virAsprintf(&cmd,
                    "lssyscfg -r lpar -m %s -F state --filter lpar_ids=%d",
                    managed_system, lpar_id) < 0) {
        virReportOOMError(conn);
858
        goto cleanup;
859 860
    }

861
    ret = phypExec(session, cmd, &exit_status, conn);
862

863 864
    if (exit_status < 0 || ret == NULL)
        goto cleanup;
865 866 867 868 869 870 871

    char_ptr = strchr(ret, '\n');

    if (char_ptr)
        *char_ptr = '\0';

    if (STREQ(ret, "Running"))
872
        state = VIR_DOMAIN_RUNNING;
873
    else if (STREQ(ret, "Not Activated"))
874
        state = VIR_DOMAIN_SHUTOFF;
875
    else if (STREQ(ret, "Shutting Down"))
876
        state = VIR_DOMAIN_SHUTDOWN;
877

878
  cleanup:
879
    VIR_FREE(cmd);
880 881
    VIR_FREE(ret);
    return state;
882 883
}

884 885 886 887 888 889
int
phypGetVIOSPartitionID(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    phyp_driverPtr phyp_driver = conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
890 891
    char *cmd = NULL;
    char *ret = NULL;
892 893 894 895 896 897 898 899 900 901 902 903
    int exit_status = 0;
    int id = -1;
    char *char_ptr;
    char *managed_system = phyp_driver->managed_system;

    if (virAsprintf(&cmd,
                    "lssyscfg -m %s -r lpar -F lpar_id,lpar_env|grep "
                    "vioserver|sed -s 's/,.*$//g'", managed_system) < 0) {
        virReportOOMError(conn);
        goto err;
    }

904
    ret = phypExec(session, cmd, &exit_status, conn);
905 906 907 908 909 910 911

    if (exit_status < 0 || ret == NULL)
        goto err;

    if (virStrToLong_i(ret, &char_ptr, 10, &id) == -1)
        goto err;

912 913
    VIR_FREE(cmd);
    VIR_FREE(ret);
914 915 916 917
    return id;

  err:
    VIR_FREE(cmd);
918
    VIR_FREE(ret);
919 920 921
    return -1;
}

922 923 924
int
phypDiskType(virConnectPtr conn, char *backing_device)
{
925
    phyp_driverPtr phyp_driver = conn->privateData;
926
    ConnectionData *connection_data = conn->networkPrivateData;
927
    LIBSSH2_SESSION *session = connection_data->session;
928 929
    char *cmd = NULL;
    char *ret = NULL;
930
    int exit_status = 0;
931 932 933
    char *char_ptr;
    char *managed_system = phyp_driver->managed_system;
    int vios_id = phyp_driver->vios_id;
934
    int disk_type = -1;
935 936

    if (virAsprintf(&cmd,
937 938 939
                    "viosvrcmd -m %s -p %d -c \"lssp -field name type "
                    "-fmt , -all|grep %s|sed -e 's/^.*,//g'\"",
                    managed_system, vios_id, backing_device) < 0) {
940
        virReportOOMError(conn);
941
        goto cleanup;
942 943
    }

944
    ret = phypExec(session, cmd, &exit_status, conn);
945

946 947
    if (exit_status < 0 || ret == NULL)
        goto cleanup;
948

949
    char_ptr = strchr(ret, '\n');
950 951 952 953 954

    if (char_ptr)
        *char_ptr = '\0';

    if (STREQ(ret, "LVPOOL"))
955
        disk_type = VIR_DOMAIN_DISK_TYPE_BLOCK;
956
    else if (STREQ(ret, "FBPOOL"))
957
        disk_type = VIR_DOMAIN_DISK_TYPE_FILE;
958

959
  cleanup:
960
    VIR_FREE(cmd);
961 962
    VIR_FREE(ret);
    return disk_type;
963 964 965 966 967 968 969 970 971 972 973 974 975 976
}

/* This is a generic function that won't be used directly by
 * libvirt api. The function returns the number of domains
 * in different states: Running, Not Activated and all:
 *
 * type: 0 - Running
 *       1 - Not Activated
 *       * - All
 * */
static int
phypNumDomainsGeneric(virConnectPtr conn, unsigned int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
977
    phyp_driverPtr phyp_driver = conn->privateData;
978
    LIBSSH2_SESSION *session = connection_data->session;
979 980 981
    int exit_status = 0;
    int ndom = 0;
    char *char_ptr;
982 983
    char *cmd = NULL;
    char *ret = NULL;
984
    char *managed_system = phyp_driver->managed_system;
985 986 987 988 989 990 991 992 993 994
    const char *state;

    if (type == 0)
        state = "|grep Running";
    else if (type == 1)
        state = "|grep \"Not Activated\"";
    else
        state = " ";

    if (virAsprintf(&cmd,
995 996
                    "lssyscfg -r lpar -m %s -F lpar_id,state %s |grep -c "
                    "^[0-9]*", managed_system, state) < 0) {
997 998 999 1000
        virReportOOMError(conn);
        goto err;
    }

1001
    ret = phypExec(session, cmd, &exit_status, conn);
1002 1003 1004 1005 1006 1007 1008 1009

    if (exit_status < 0 || ret == NULL)
        goto err;

    if (virStrToLong_i(ret, &char_ptr, 10, &ndom) == -1)
        goto err;

    VIR_FREE(cmd);
1010
    VIR_FREE(ret);
1011 1012 1013 1014
    return ndom;

  err:
    VIR_FREE(cmd);
1015
    VIR_FREE(ret);
1016
    return -1;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
}

static int
phypNumDefinedDomains(virConnectPtr conn)
{
    return phypNumDomainsGeneric(conn, 1);
}

static int
phypNumDomains(virConnectPtr conn)
{
    return phypNumDomainsGeneric(conn, 0);
}

/* This is a generic function that won't be used directly by
 * libvirt api. The function returns the ids of domains
 * in different states: Running, and all:
 *
 * type: 0 - Running
1036
 *       1 - all
1037 1038 1039 1040 1041 1042
 * */
static int
phypListDomainsGeneric(virConnectPtr conn, int *ids, int nids,
                       unsigned int type)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1043
    phyp_driverPtr phyp_driver = conn->privateData;
1044
    LIBSSH2_SESSION *session = connection_data->session;
1045
    char *managed_system = phyp_driver->managed_system;
1046 1047 1048 1049 1050
    int exit_status = 0;
    int got = 0;
    char *char_ptr;
    unsigned int i = 0, j = 0;
    char id_c[10];
1051 1052
    char *cmd = NULL;
    char *ret = NULL;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    const char *state;

    if (type == 0)
        state = "|grep Running";
    else
        state = " ";

    memset(id_c, 0, 10);

    if (virAsprintf
        (&cmd,
         "lssyscfg -r lpar -m %s -F lpar_id,state %s | sed -e 's/,.*$//g'",
         managed_system, state) < 0) {
        virReportOOMError(conn);
        goto err;
    }
1069
    ret = phypExec(session, cmd, &exit_status, conn);
1070

1071 1072
    /* I need to parse the textual return in order to get the ret */
    if (exit_status < 0 || ret == NULL)
1073 1074 1075
        goto err;
    else {
        while (got < nids) {
1076 1077 1078 1079 1080 1081 1082
            if (ret[i] == '\0')
                break;
            else if (ret[i] == '\n') {
                if (virStrToLong_i(id_c, &char_ptr, 10, &ids[got]) == -1) {
                    VIR_ERROR("Cannot parse number from '%s'", id_c);
                    goto err;
                }
1083 1084 1085 1086
                memset(id_c, 0, 10);
                j = 0;
                got++;
            } else {
1087
                id_c[j] = ret[i];
1088 1089 1090 1091 1092 1093 1094
                j++;
            }
            i++;
        }
    }

    VIR_FREE(cmd);
1095
    VIR_FREE(ret);
1096 1097 1098 1099
    return got;

  err:
    VIR_FREE(cmd);
1100
    VIR_FREE(ret);
1101
    return -1;
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
}

static int
phypListDomains(virConnectPtr conn, int *ids, int nids)
{
    return phypListDomainsGeneric(conn, ids, nids, 0);
}

static int
phypListDefinedDomains(virConnectPtr conn, char **const names, int nnames)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1114
    phyp_driverPtr phyp_driver = conn->privateData;
1115
    LIBSSH2_SESSION *session = connection_data->session;
1116
    char *managed_system = phyp_driver->managed_system;
1117 1118
    int exit_status = 0;
    int got = 0;
1119 1120 1121 1122 1123
    int i;
    char *cmd = NULL;
    char *ret = NULL;
    char *domains = NULL;
    char *char_ptr2 = NULL;
1124 1125 1126

    if (virAsprintf
        (&cmd,
1127 1128
         "lssyscfg -r lpar -m %s -F name,state | grep \"Not Activated\" | "
         "sed -e 's/,.*$//g'", managed_system) < 0) {
1129 1130 1131 1132
        virReportOOMError(conn);
        goto err;
    }

1133
    ret = phypExec(session, cmd, &exit_status, conn);
1134 1135

    /* I need to parse the textual return in order to get the domains */
1136
    if (exit_status < 0 || ret == NULL)
1137 1138
        goto err;
    else {
1139 1140
        domains = ret;

1141 1142 1143 1144 1145
        while (got < nnames) {
            char_ptr2 = strchr(domains, '\n');

            if (char_ptr2) {
                *char_ptr2 = '\0';
1146 1147
                if ((names[got++] = strdup(domains)) == NULL) {
                    virReportOOMError(conn);
1148
                    goto err;
1149
                }
1150 1151
                char_ptr2++;
                domains = char_ptr2;
1152 1153
            } else
                break;
1154 1155 1156 1157 1158 1159 1160 1161
        }
    }

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return got;

  err:
1162 1163 1164
    for (i = 0; i < got; i++)
        VIR_FREE(names[i]);
    VIR_FREE(cmd);
1165
    VIR_FREE(ret);
1166
    return -1;
1167 1168 1169 1170 1171 1172
}

static virDomainPtr
phypDomainLookupByName(virConnectPtr conn, const char *lpar_name)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1173
    phyp_driverPtr phyp_driver = conn->privateData;
1174
    LIBSSH2_SESSION *session = connection_data->session;
1175 1176
    virDomainPtr dom = NULL;
    int lpar_id = 0;
1177
    char *managed_system = phyp_driver->managed_system;
1178
    unsigned char lpar_uuid[VIR_UUID_BUFLEN];
1179

1180
    lpar_id = phypGetLparID(session, managed_system, lpar_name, conn);
1181
    if (lpar_id == -1)
1182
        return NULL;
1183 1184

    if (phypGetLparUUID(lpar_uuid, lpar_id, conn) == -1)
1185
        return NULL;
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

    dom = virGetDomain(conn, lpar_name, lpar_uuid);

    if (dom)
        dom->id = lpar_id;

    return dom;
}

static virDomainPtr
phypDomainLookupByID(virConnectPtr conn, int lpar_id)
{
    ConnectionData *connection_data = conn->networkPrivateData;
1199
    phyp_driverPtr phyp_driver = conn->privateData;
1200
    LIBSSH2_SESSION *session = connection_data->session;
1201
    virDomainPtr dom = NULL;
1202
    char *managed_system = phyp_driver->managed_system;
1203
    int exit_status = 0;
1204
    unsigned char lpar_uuid[VIR_UUID_BUFLEN];
1205

1206
    char *lpar_name = phypGetLparNAME(session, managed_system, lpar_id,
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
                                      conn);

    if (phypGetLparUUID(lpar_uuid, lpar_id, conn) == -1)
        goto err;

    if (exit_status < 0)
        goto err;

    dom = virGetDomain(conn, lpar_name, lpar_uuid);

    if (dom)
        dom->id = lpar_id;

    VIR_FREE(lpar_name);
    return dom;

  err:
    VIR_FREE(lpar_name);
    return NULL;
}

static char *
phypDomainDumpXML(virDomainPtr dom, int flags)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
1232
    phyp_driverPtr phyp_driver = dom->conn->privateData;
1233
    LIBSSH2_SESSION *session = connection_data->session;
1234
    virDomainDef def;
1235
    char *managed_system = phyp_driver->managed_system;
1236

1237
    memset(&def, 0, sizeof(virDomainDef));
1238

1239 1240
    def.virtType = VIR_DOMAIN_VIRT_PHYP;
    def.id = dom->id;
1241

1242
    char *lpar_name = phypGetLparNAME(session, managed_system, def.id,
1243 1244 1245 1246 1247 1248 1249
                                      dom->conn);

    if (lpar_name == NULL) {
        VIR_ERROR("%s", "Unable to determine domain's name.");
        goto err;
    }

1250
    if (phypGetLparUUID(def.uuid, dom->id, dom->conn) == -1) {
1251 1252 1253 1254
        VIR_ERROR("%s", "Unable to generate random uuid.");
        goto err;
    }

1255
    if ((def.maxmem =
1256 1257 1258 1259 1260
         phypGetLparMem(dom->conn, managed_system, dom->id, 0)) == 0) {
        VIR_ERROR("%s", "Unable to determine domain's max memory.");
        goto err;
    }

1261
    if ((def.memory =
1262 1263 1264 1265 1266
         phypGetLparMem(dom->conn, managed_system, dom->id, 1)) == 0) {
        VIR_ERROR("%s", "Unable to determine domain's memory.");
        goto err;
    }

1267
    if ((def.vcpus =
1268 1269 1270 1271 1272
         phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0) {
        VIR_ERROR("%s", "Unable to determine domain's CPU.");
        goto err;
    }

1273
    return virDomainDefFormat(dom->conn, &def, flags);
1274 1275 1276

  err:
    return NULL;
1277 1278 1279 1280 1281 1282
}

static int
phypDomainResume(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
1283
    phyp_driverPtr phyp_driver = dom->conn->privateData;
1284
    LIBSSH2_SESSION *session = connection_data->session;
1285
    char *managed_system = phyp_driver->managed_system;
1286
    int exit_status = 0;
1287 1288
    char *cmd = NULL;
    char *ret = NULL;
1289 1290 1291 1292 1293 1294 1295 1296 1297

    if (virAsprintf
        (&cmd,
         "chsysstate -m %s -r lpar -o on --id %d -f %s",
         managed_system, dom->id, dom->name) < 0) {
        virReportOOMError(dom->conn);
        goto err;
    }

1298
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1299

1300 1301 1302
    if (exit_status < 0)
        goto err;

1303 1304 1305 1306
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

1307 1308 1309 1310
  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;
1311 1312 1313 1314 1315 1316
}

static int
phypDomainShutdown(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
1317
    phyp_driverPtr phyp_driver = dom->conn->privateData;
1318
    LIBSSH2_SESSION *session = connection_data->session;
1319
    char *managed_system = phyp_driver->managed_system;
1320
    int exit_status = 0;
1321 1322
    char *cmd = NULL;
    char *ret = NULL;
1323 1324 1325 1326 1327 1328 1329 1330 1331

    if (virAsprintf
        (&cmd,
         "chsysstate -m %s -r lpar -o shutdown --id %d",
         managed_system, dom->id) < 0) {
        virReportOOMError(dom->conn);
        goto err;
    }

1332
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1333

1334 1335 1336
    if (exit_status < 0)
        goto err;

1337 1338 1339 1340
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

1341 1342 1343 1344
  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;
1345 1346 1347 1348 1349
}

static int
phypDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
1350 1351
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    char *managed_system = phyp_driver->managed_system;
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

    info->state = phypGetLparState(dom->conn, dom->id);

    if ((info->maxMem =
         phypGetLparMem(dom->conn, managed_system, dom->id, 0)) == 0)
        VIR_WARN("%s", "Unable to determine domain's max memory.");

    if ((info->memory =
         phypGetLparMem(dom->conn, managed_system, dom->id, 1)) == 0)
        VIR_WARN("%s", "Unable to determine domain's memory.");

    if ((info->nrVirtCpu =
         phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0)
        VIR_WARN("%s", "Unable to determine domain's CPU.");

    return 0;
}

1370 1371 1372 1373 1374 1375 1376 1377
static int
phypDomainDestroy(virDomainPtr dom)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
    char *managed_system = phyp_driver->managed_system;
    int exit_status = 0;
1378 1379
    char *cmd = NULL;
    char *ret = NULL;
1380 1381 1382 1383 1384 1385 1386 1387

    if (virAsprintf
        (&cmd,
         "rmsyscfg -m %s -r lpar --id %d", managed_system, dom->id) < 0) {
        virReportOOMError(dom->conn);
        goto err;
    }

1388
    ret = phypExec(session, cmd, &exit_status, dom->conn);
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453

    if (exit_status < 0)
        goto err;

    if (phypUUIDTable_RemLpar(dom->conn, dom->id) == -1)
        goto err;

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;

}

static virDomainPtr
phypDomainCreateAndStart(virConnectPtr conn,
                         const char *xml,
                         unsigned int flags ATTRIBUTE_UNUSED)
{

    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    virDomainDefPtr def = NULL;
    virDomainPtr dom = NULL;
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    lparPtr *lpars = uuid_table->lpars;
    unsigned int i = 0;
    char *managed_system = phyp_driver->managed_system;

    if (!(def = virDomainDefParseString(conn, phyp_driver->caps, xml,
                                        VIR_DOMAIN_XML_SECURE)))
        goto err;

    /* checking if this name already exists on this system */
    if (phypGetLparID(session, managed_system, def->name, conn) == -1) {
        VIR_WARN("%s", "LPAR name already exists.");
        goto err;
    }

    /* checking if ID or UUID already exists on this system */
    for (i = 0; i < uuid_table->nlpars; i++) {
        if (lpars[i]->id == def->id || lpars[i]->uuid == def->uuid) {
            VIR_WARN("%s", "LPAR ID or UUID already exists.");
            goto err;
        }
    }

    if ((dom = virGetDomain(conn, def->name, def->uuid)) == NULL)
        goto err;

    if (phypBuildLpar(conn, def) == -1)
        goto err;

    if (phypDomainResume(dom) == -1)
        goto err;

    return dom;

  err:
    virDomainDefFree(def);
1454 1455
    if (dom)
        virUnrefDomain(dom);
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    return NULL;
}

static char *
phypConnectGetCapabilities(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    char *xml;

    if ((xml = virCapabilitiesFormatXML(phyp_driver->caps)) == NULL)
        virReportOOMError(conn);

    return xml;
}

virCapsPtr
phypCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

    if ((caps = virCapabilitiesNew(utsname.machine, 0, 0)) == NULL)
        goto no_memory;

    /* Some machines have problematic NUMA toplogy causing
     * unexpected failures. We don't want to break the QEMU
     * driver in this scenario, so log errors & carry on
     */
    if (nodeCapsInitNUMA(caps) < 0) {
        virCapabilitiesFreeNUMAInfo(caps);
        VIR_WARN0
            ("Failed to query host NUMA topology, disabling NUMA capabilities");
    }

    /* XXX shouldn't 'borrow' KVM's prefix */
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]) {
                                0x52, 0x54, 0x00});

    if ((guest = virCapabilitiesAddGuest(caps,
                                         "linux",
                                         utsname.machine,
                                         sizeof(int) == 4 ? 32 : 8,
                                         NULL, NULL, 0, NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      "phyp", NULL, NULL, 0, NULL) == NULL)
        goto no_memory;

    return caps;

  no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}

static int
phypDomainSetCPU(virDomainPtr dom, unsigned int nvcpus)
{
    ConnectionData *connection_data = dom->conn->networkPrivateData;
    phyp_driverPtr phyp_driver = dom->conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
    char *managed_system = phyp_driver->managed_system;
    int exit_status = 0;
1523 1524
    char *cmd = NULL;
    char *ret = NULL;
1525 1526 1527 1528 1529 1530 1531 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
    char operation;
    unsigned long ncpus = 0;
    unsigned int amount = 0;

    if ((ncpus = phypGetLparCPU(dom->conn, managed_system, dom->id)) == 0)
        goto err;

    if (nvcpus > phypGetLparCPUMAX(dom)) {
        VIR_ERROR("%s",
                  "You are trying to set a number of CPUs bigger than "
                  "the max possible..");
        goto err;
    }

    if (ncpus > nvcpus) {
        operation = 'r';
        amount = nvcpus - ncpus;
    } else if (ncpus < nvcpus) {
        operation = 'a';
        amount = nvcpus - ncpus;
    } else
        goto exit;

    if (virAsprintf
        (&cmd,
         "chhwres -r proc -m %s --id %d -o %c --procunits %d 2>&1 |sed"
         "-e 's/^.*\\([0-9]\\+.[0-9]\\+\\).*$/\\1/g'",
         managed_system, dom->id, operation, amount) < 0) {
        virReportOOMError(dom->conn);
        goto err;
    }

1557
    ret = phypExec(session, cmd, &exit_status, dom->conn);
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

    if (exit_status < 0) {
        VIR_ERROR("%s",
                  "Possibly you don't have IBM Tools installed in your LPAR."
                  "Contact your support to enable this feature.");
        goto err;
    }

  exit:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

}

virDriver phypDriver = {
    VIR_DRV_PHYP,
    "PHYP",
    phypOpen,                   /* open */
    phypClose,                  /* close */
    NULL,                       /* supports_feature */
    NULL,                       /* type */
    NULL,                       /* version */
1586
    NULL,                       /* libvirtVersion (impl. in libvirt.c) */
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
    NULL,                       /* getHostname */
    NULL,                       /* getMaxVcpus */
    NULL,                       /* nodeGetInfo */
    phypConnectGetCapabilities, /* getCapabilities */
    phypListDomains,            /* listDomains */
    phypNumDomains,             /* numOfDomains */
    phypDomainCreateAndStart,   /* domainCreateXML */
    phypDomainLookupByID,       /* domainLookupByID */
    NULL,                       /* domainLookupByUUID */
    phypDomainLookupByName,     /* domainLookupByName */
    NULL,                       /* domainSuspend */
    phypDomainResume,           /* domainResume */
    phypDomainShutdown,         /* domainShutdown */
    NULL,                       /* domainReboot */
    phypDomainDestroy,          /* domainDestroy */
    NULL,                       /* domainGetOSType */
    NULL,                       /* domainGetMaxMemory */
    NULL,                       /* domainSetMaxMemory */
    NULL,                       /* domainSetMemory */
1606 1607 1608 1609
    phypDomainGetInfo,          /* domainGetInfo */
    NULL,                       /* domainSave */
    NULL,                       /* domainRestore */
    NULL,                       /* domainCoreDump */
1610
    phypDomainSetCPU,           /* domainSetVcpus */
1611 1612
    NULL,                       /* domainPinVcpu */
    NULL,                       /* domainGetVcpus */
1613
    phypGetLparCPUMAX,          /* domainGetMaxVcpus */
1614 1615 1616
    NULL,                       /* domainGetSecurityLabel */
    NULL,                       /* nodeGetSecurityModel */
    phypDomainDumpXML,          /* domainDumpXML */
1617 1618
    NULL,                       /* domainXMLFromNative */
    NULL,                       /* domainXMLToNative */
1619 1620 1621 1622 1623 1624
    phypListDefinedDomains,     /* listDefinedDomains */
    phypNumDefinedDomains,      /* numOfDefinedDomains */
    NULL,                       /* domainCreate */
    NULL,                       /* domainDefineXML */
    NULL,                       /* domainUndefine */
    NULL,                       /* domainAttachDevice */
1625
    NULL,                       /* domainAttachDeviceFlags */
1626
    NULL,                       /* domainDetachDevice */
1627
    NULL,                       /* domainDetachDeviceFlags */
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    NULL,                       /* domainGetAutostart */
    NULL,                       /* domainSetAutostart */
    NULL,                       /* domainGetSchedulerType */
    NULL,                       /* domainGetSchedulerParameters */
    NULL,                       /* domainSetSchedulerParameters */
    NULL,                       /* domainMigratePrepare */
    NULL,                       /* domainMigratePerform */
    NULL,                       /* domainMigrateFinish */
    NULL,                       /* domainBlockStats */
    NULL,                       /* domainInterfaceStats */
1638
    NULL,                       /* domainMemoryStats */
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
    NULL,                       /* domainBlockPeek */
    NULL,                       /* domainMemoryPeek */
    NULL,                       /* nodeGetCellsFreeMemory */
    NULL,                       /* getFreeMemory */
    NULL,                       /* domainEventRegister */
    NULL,                       /* domainEventDeregister */
    NULL,                       /* domainMigratePrepare2 */
    NULL,                       /* domainMigrateFinish2 */
    NULL,                       /* nodeDeviceDettach */
    NULL,                       /* nodeDeviceReAttach */
    NULL,                       /* nodeDeviceReset */
C
Chris Lalancette 已提交
1650
    NULL,                       /* domainMigratePrepareTunnel */
1651 1652 1653 1654
    phypIsEncrypted,
    phypIsSecure,
    NULL,                       /* domainIsActive */
    NULL,                       /* domainIsPersistent */
J
Jiri Denemark 已提交
1655
    NULL,                       /* cpuCompare */
1656 1657 1658
};

int
1659
phypBuildLpar(virConnectPtr conn, virDomainDefPtr def)
1660
{
1661 1662 1663 1664
    ConnectionData *connection_data = conn->networkPrivateData;
    phyp_driverPtr phyp_driver = conn->privateData;
    LIBSSH2_SESSION *session = connection_data->session;
    char *managed_system = phyp_driver->managed_system;
1665 1666
    char *cmd = NULL;
    char *ret = NULL;
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
    int exit_status = 0;

    if (virAsprintf
        (&cmd,
         "mksyscfg -m %s -r lpar -p %s -i min_mem=%d,desired_mem=%d,"
         "max_mem=%d,desired_procs=%d,virtual_scsi_adapters=%s",
         managed_system, def->name, (int) def->memory,
         (int) def->memory, (int) def->maxmem, (int) def->vcpus,
         def->disks[0]->src) < 0) {
        virReportOOMError(conn);
        goto err;
    }

1680
    ret = phypExec(session, cmd, &exit_status, conn);
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711

    if (exit_status < 0) {
        VIR_ERROR("%s\"%s\"", "Unable to create LPAR. Reason: ", ret);
        goto err;
    }

    if (phypUUIDTable_AddLpar(conn, def->uuid, def->id) == -1) {
        VIR_ERROR("%s", "Unable to add LPAR to the table");
        goto err;
    }

    VIR_FREE(cmd);
    VIR_FREE(ret);
    return 0;

  err:
    VIR_FREE(cmd);
    VIR_FREE(ret);
    return -1;
}

int
phypUUIDTable_RemLpar(virConnectPtr conn, int id)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;

    for (i = 0; i <= uuid_table->nlpars; i++) {
        if (uuid_table->lpars[i]->id == id) {
            uuid_table->lpars[i]->id = -1;
1712
            memset(uuid_table->lpars[i]->uuid, 0, VIR_UUID_BUFLEN);
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
        }
    }

    if (phypUUIDTable_WriteFile(conn) == -1)
        goto err;

    if (phypUUIDTable_Push(conn) == -1)
        goto err;

    return 0;

  err:
    return -1;
}

int
phypUUIDTable_AddLpar(virConnectPtr conn, unsigned char *uuid, int id)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;

    uuid_table->nlpars++;
    unsigned int i = uuid_table->nlpars;
    i--;

    if (VIR_REALLOC_N(uuid_table->lpars, uuid_table->nlpars) < 0) {
        virReportOOMError(conn);
        goto err;
    }

    if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
        virReportOOMError(conn);
        goto err;
    }

    uuid_table->lpars[i]->id = id;
1749
    memmove(uuid_table->lpars[i]->uuid, uuid, VIR_UUID_BUFLEN);
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771

    if (phypUUIDTable_WriteFile(conn) == -1)
        goto err;

    if (phypUUIDTable_Push(conn) == -1)
        goto err;

    return 0;

  err:
    return -1;
}

int
phypUUIDTable_ReadFile(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;
    int fd = -1;
    char local_file[] = "./uuid_table";
    int rc = 0;
1772
    int id;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

    if ((fd = open(local_file, O_RDONLY)) == -1) {
        VIR_WARN("%s", "Unable to write information to local file.");
        goto err;
    }

    /* Creating a new data base and writing to local file */
    if (VIR_ALLOC_N(uuid_table->lpars, uuid_table->nlpars) >= 0) {
        for (i = 0; i < uuid_table->nlpars; i++) {

1783
            rc = read(fd, &id, sizeof(int));
1784
            if (rc == sizeof(int)) {
1785
                if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
1786
                    virReportOOMError(conn);
1787 1788
                    goto err;
                }
1789
                uuid_table->lpars[i]->id = id;
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
            } else {
                VIR_WARN("%s",
                         "Unable to read from information to local file.");
                goto err;
            }

            rc = read(fd, uuid_table->lpars[i]->uuid, VIR_UUID_BUFLEN);
            if (rc != VIR_UUID_BUFLEN) {
                VIR_WARN("%s",
                         "Unable to read information to local file.");
                goto err;
            }
        }
1803 1804
    } else
        virReportOOMError(conn);
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827

    close(fd);
    return 0;

  err:
    close(fd);
    return -1;
}

int
phypUUIDTable_WriteFile(virConnectPtr conn)
{
    phyp_driverPtr phyp_driver = conn->privateData;
    uuid_tablePtr uuid_table = phyp_driver->uuid_table;
    unsigned int i = 0;
    int fd = -1;
    char local_file[] = "./uuid_table";

    if ((fd = creat(local_file, 0755)) == -1)
        goto err;

    for (i = 0; i < uuid_table->nlpars; i++) {
        if (safewrite(fd, &uuid_table->lpars[i]->id,
1828
                      sizeof(uuid_table->lpars[i]->id)) !=
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
            sizeof(uuid_table->lpars[i]->id)) {
            VIR_ERROR("%s", "Unable to write information to local file.");
            goto err;
        }

        if (safewrite(fd, uuid_table->lpars[i]->uuid, VIR_UUID_BUFLEN) !=
            VIR_UUID_BUFLEN) {
            VIR_ERROR("%s", "Unable to write information to local file.");
            goto err;
        }
    }

    close(fd);
1842
    return 0;
1843 1844 1845 1846

  err:
    close(fd);
    return -1;
1847 1848
}

1849 1850
int
phypUUIDTable_Init(virConnectPtr conn)
1851
{
1852 1853
    uuid_tablePtr uuid_table;
    phyp_driverPtr phyp_driver;
1854 1855 1856 1857
    int nids = 0;
    int *ids = NULL;
    unsigned int i = 0;

1858
    if ((nids = phypNumDomainsGeneric(conn, 2)) < 0)
1859
        goto err;
1860

1861 1862 1863 1864
    /* exit early if there are no domains */
    if (nids == 0)
        return 0;

1865
    if (VIR_ALLOC_N(ids, nids) < 0) {
1866
        virReportOOMError(conn);
1867 1868
        goto err;
    }
1869

1870
    if ((nids = phypListDomainsGeneric(conn, ids, nids, 1)) < 0)
1871 1872
        goto err;

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
    /* exit early if there are no domains */
    /* FIXME: phypNumDomainsGeneric() returned > 0 but phypListDomainsGeneric()
     *        returned 0. indicates this an error condition?
     *        an even stricter check would be to treat
     *
     *          phypNumDomainsGeneric() != phypListDomainsGeneric()
     *
     *        as an error */
    if (nids == 0) {
        VIR_FREE(ids);
        return 0;
    }

1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    phyp_driver = conn->privateData;
    uuid_table = phyp_driver->uuid_table;
    uuid_table->nlpars = nids;

    /* try to get the table from server */
    if (phypUUIDTable_Pull(conn) == -1) {
        /* file not found in the server, creating a new one */
        if (VIR_ALLOC_N(uuid_table->lpars, uuid_table->nlpars) >= 0) {
            for (i = 0; i < uuid_table->nlpars; i++) {
                if (VIR_ALLOC(uuid_table->lpars[i]) < 0) {
                    virReportOOMError(conn);
                    goto err;
                }
                uuid_table->lpars[i]->id = ids[i];

                if (virUUIDGenerate(uuid_table->lpars[i]->uuid) < 0)
                    VIR_WARN("%s %d", "Unable to generate UUID for domain",
                             ids[i]);
            }
1905 1906
        } else {
            virReportOOMError(conn);
1907
            goto err;
1908
        }
1909 1910 1911 1912 1913 1914 1915 1916 1917

        if (phypUUIDTable_WriteFile(conn) == -1)
            goto err;

        if (phypUUIDTable_Push(conn) == -1)
            goto err;
    } else {
        if (phypUUIDTable_ReadFile(conn) == -1)
            goto err;
1918
        goto exit;
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
    }

  exit:
    VIR_FREE(ids);
    return 0;

  err:
    VIR_FREE(ids);
    return -1;
}

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
void
phypUUIDTable_Free(uuid_tablePtr uuid_table)
{
    int i;

    if (uuid_table == NULL)
        return;

    for (i = 0; i < uuid_table->nlpars; i++)
        VIR_FREE(uuid_table->lpars[i]);

    VIR_FREE(uuid_table->lpars);
    VIR_FREE(uuid_table);
}

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
int
phypUUIDTable_Push(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    LIBSSH2_CHANNEL *channel = NULL;
    struct stat local_fileinfo;
    char buffer[1024];
    int rc = 0;
    FILE *fd;
    size_t nread, sent;
    char *ptr;
    char remote_file[] = "/home/hscroot/libvirt_uuid_table";
    char local_file[] = "./uuid_table";

    if (stat(local_file, &local_fileinfo) == -1) {
        VIR_WARN0("Unable to stat local file.");
        goto err;
    }
1964

1965 1966 1967 1968
    if (!(fd = fopen(local_file, "rb"))) {
        VIR_WARN0("Unable to open local file.");
        goto err;
    }
1969

1970 1971 1972 1973 1974
    do {
        channel =
            libssh2_scp_send(session, remote_file,
                             0x1FF & local_fileinfo.st_mode,
                             (unsigned long) local_fileinfo.st_size);
1975

1976 1977 1978 1979 1980 1981 1982 1983
        if ((!channel) && (libssh2_session_last_errno(session) !=
                           LIBSSH2_ERROR_EAGAIN))
            goto err;
    } while (!channel);

    do {
        nread = fread(buffer, 1, sizeof(buffer), fd);
        if (nread <= 0) {
1984 1985 1986 1987 1988 1989 1990
            if (feof(fd)) {
                /* end of file */
                break;
            } else {
                VIR_ERROR("Failed to read from '%s'", local_file);
                goto err;
            }
1991
        }
1992 1993 1994 1995 1996 1997 1998 1999
        ptr = buffer;
        sent = 0;

        do {
            /* write the same data over and over, until error or completion */
            rc = libssh2_channel_write(channel, ptr, nread);
            if (LIBSSH2_ERROR_EAGAIN == rc) {   /* must loop around */
                continue;
2000
            } else if (rc > 0) {
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
                /* rc indicates how many bytes were written this time */
                sent += rc;
            }
        } while (rc > 0 && sent < nread);
        ptr += sent;
        nread -= sent;
    } while (1);

    goto exit;

  exit:
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
2018
    }
2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
    return 0;

  err:
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
    return -1;
}

int
phypUUIDTable_Pull(virConnectPtr conn)
{
    ConnectionData *connection_data = conn->networkPrivateData;
    LIBSSH2_SESSION *session = connection_data->session;
    LIBSSH2_CHANNEL *channel = NULL;
    struct stat fileinfo;
    char buffer[1024];
    int rc = 0;
    int fd;
    int got = 0;
    int amount = 0;
    int total = 0;
    int sock = 0;
    char remote_file[] = "/home/hscroot/libvirt_uuid_table";
    char local_file[] = "./uuid_table";

    /* Trying to stat the remote file. */
    do {
        channel = libssh2_scp_recv(session, remote_file, &fileinfo);

        if (!channel) {
            if (libssh2_session_last_errno(session) !=
                LIBSSH2_ERROR_EAGAIN) {
                goto err;;
            } else {
                waitsocket(sock, session);
            }
        }
    } while (!channel);

    /* Creating a new data base based on remote file */
    if ((fd = creat(local_file, 0755)) == -1)
        goto err;

    /* Request a file via SCP */
    while (got < fileinfo.st_size) {
        do {
            amount = sizeof(buffer);

            if ((fileinfo.st_size - got) < amount) {
                amount = fileinfo.st_size - got;
            }

            rc = libssh2_channel_read(channel, buffer, amount);
            if (rc > 0) {
                if (safewrite(fd, buffer, rc) != rc)
                    VIR_WARN("%s",
                             "Unable to write information to local file.");

                got += rc;
                total += rc;
            }
        } while (rc > 0);

        if ((rc == LIBSSH2_ERROR_EAGAIN)
            && (got < fileinfo.st_size)) {
            /* this is due to blocking that would occur otherwise
             * so we loop on this condition */

            waitsocket(sock, session);  /* now we wait */
            continue;
        }
        break;
    }
    close(fd);
    goto exit;

2100
  exit:
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
    return 0;

  err:
    if (channel) {
        libssh2_channel_send_eof(channel);
        libssh2_channel_wait_eof(channel);
        libssh2_channel_wait_closed(channel);
        libssh2_channel_free(channel);
        channel = NULL;
    }
    return -1;
2119 2120
}

2121
int
2122
escape_specialcharacters(char *src, char *dst, size_t dstlen)
2123 2124 2125 2126 2127 2128 2129 2130 2131
{
    size_t len = strlen(src);
    char temp_buffer[len];
    unsigned int i = 0, j = 0;
    if (len == 0)
        return -1;

    for (i = 0; i < len; i++) {
        switch (src[i]) {
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
            case '&':
            case ';':
            case '`':
            case '@':
            case '"':
            case '|':
            case '*':
            case '?':
            case '~':
            case '<':
            case '>':
            case '^':
            case '(':
            case ')':
            case '[':
            case ']':
            case '{':
            case '}':
            case '$':
            case '%':
            case '#':
            case '\\':
            case '\n':
            case '\r':
2156 2157 2158 2159 2160 2161 2162 2163 2164
            case '\t':
                continue;
            default:
                temp_buffer[j] = src[i];
                j++;
        }
    }
    temp_buffer[j] = '\0';

C
Chris Lalancette 已提交
2165
    if (virStrcpy(dst, temp_buffer, dstlen) == NULL)
2166 2167 2168 2169
        return -1;

    return 0;
}
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180

int
waitsocket(int socket_fd, LIBSSH2_SESSION * session)
{
    struct timeval timeout;
    int rc;
    fd_set fd;
    fd_set *writefd = NULL;
    fd_set *readfd = NULL;
    int dir;

2181 2182
    timeout.tv_sec = 0;
    timeout.tv_usec = 1000;
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200

    FD_ZERO(&fd);

    FD_SET(socket_fd, &fd);

    /* now make sure we wait in the correct direction */
    dir = libssh2_session_block_directions(session);

    if (dir & LIBSSH2_SESSION_BLOCK_INBOUND)
        readfd = &fd;

    if (dir & LIBSSH2_SESSION_BLOCK_OUTBOUND)
        writefd = &fd;

    rc = select(socket_fd + 1, readfd, writefd, NULL, &timeout);

    return rc;
}
2201 2202 2203 2204 2205 2206 2207

int
phypRegister(void)
{
    virRegisterDriver(&phypDriver);
    return 0;
}