net.c 22.1 KB
Newer Older
1 2
/*
 * Copyright 2008 Hans Leidekker for CodeWeavers
3
 * Copyright 2013 Jacek Caban for CodeWeavers
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
21 22
#define NONAMELESSUNION
#include "ws2tcpip.h"
23 24
#include <stdarg.h>
#include <stdio.h>
25
#include <assert.h>
26 27 28 29

#include "windef.h"
#include "winbase.h"
#include "winhttp.h"
30
#include "schannel.h"
31

32 33
#include "wine/debug.h"
#include "wine/library.h"
34 35
#include "winhttp_private.h"

36 37
WINE_DEFAULT_DEBUG_CHANNEL(winhttp);

38 39 40 41 42
static int sock_send(int fd, const void *msg, size_t len, int flags)
{
    int ret;
    do
    {
43
        if ((ret = send(fd, msg, len, flags)) == -1) WARN("send error %u\n", WSAGetLastError());
44
    }
45
    while(ret == -1 && WSAGetLastError() == WSAEINTR);
46 47 48
    return ret;
}

49 50 51 52 53
static int sock_recv(int fd, void *msg, size_t len, int flags)
{
    int ret;
    do
    {
54
        if ((ret = recv(fd, msg, len, flags)) == -1) WARN("recv error %u\n", WSAGetLastError());
55
    }
56
    while(ret == -1 && WSAGetLastError() == WSAEINTR);
57 58 59
    return ret;
}

60
static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, WCHAR *server, DWORD security_flags, BOOL check_revocation )
61
{
62
    HCERTSTORE store = cert->hCertStore;
63 64 65 66 67
    BOOL ret;
    CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
    PCCERT_CHAIN_CONTEXT chain;
    char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
    char *server_auth[] = { oid_server_auth };
68
    DWORD err = ERROR_SUCCESS;
69 70 71 72

    TRACE("verifying %s\n", debugstr_w( server ));
    chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
    chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
73 74 75 76
    ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara,
                                   check_revocation ? CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT : 0,
                                   NULL, &chain );
    if (ret)
77 78 79
    {
        if (chain->TrustStatus.dwErrorStatus)
        {
80 81 82 83 84
            static const DWORD supportedErrors =
                CERT_TRUST_IS_NOT_TIME_VALID |
                CERT_TRUST_IS_UNTRUSTED_ROOT |
                CERT_TRUST_IS_NOT_VALID_FOR_USAGE;

85
            if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
86 87 88 89
            {
                if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
                    err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
            }
90 91
            else if (chain->TrustStatus.dwErrorStatus &
                     CERT_TRUST_IS_UNTRUSTED_ROOT)
92 93 94 95
            {
                if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
                    err = ERROR_WINHTTP_SECURE_INVALID_CA;
            }
96 97 98 99 100 101 102 103 104
            else if ((chain->TrustStatus.dwErrorStatus &
                      CERT_TRUST_IS_OFFLINE_REVOCATION) ||
                     (chain->TrustStatus.dwErrorStatus &
                      CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
                err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
            else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
                err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
            else if (chain->TrustStatus.dwErrorStatus &
                CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
105 106 107 108
            {
                if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
                    err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
            }
109
            else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
110 111
                err = ERROR_WINHTTP_SECURE_INVALID_CERT;
        }
112
        if (!err)
113 114 115 116
        {
            CERT_CHAIN_POLICY_PARA policyPara;
            SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
            CERT_CHAIN_POLICY_STATUS policyStatus;
117
            CERT_CHAIN_CONTEXT chainCopy;
118

119 120 121 122 123 124
            /* Clear chain->TrustStatus.dwErrorStatus so
             * CertVerifyCertificateChainPolicy will verify additional checks
             * rather than stopping with an existing, ignored error.
             */
            memcpy(&chainCopy, chain, sizeof(chainCopy));
            chainCopy.TrustStatus.dwErrorStatus = 0;
125
            sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
126 127
            sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
            sslExtraPolicyPara.pwszServerName = server;
128
            sslExtraPolicyPara.fdwChecks = security_flags;
129 130 131 132
            policyPara.cbSize = sizeof(policyPara);
            policyPara.dwFlags = 0;
            policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
            ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
133
                                                    &chainCopy, &policyPara,
134 135 136 137 138 139 140
                                                    &policyStatus );
            /* Any error in the policy status indicates that the
             * policy couldn't be verified.
             */
            if (ret && policyStatus.dwError)
            {
                if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
141
                    err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
142 143 144 145 146 147
                else
                    err = ERROR_WINHTTP_SECURE_INVALID_CERT;
            }
        }
        CertFreeCertificateChain( chain );
    }
148 149 150 151
    else
        err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
    TRACE("returning %08x\n", err);
    return err;
152 153
}

154 155
static BOOL winsock_loaded;

156 157
void netconn_unload( void )
{
158 159 160 161 162 163 164 165 166 167 168 169
    if (winsock_loaded) WSACleanup();
}

static BOOL WINAPI winsock_startup( INIT_ONCE *once, void *param, void **ctx )
{
    int ret;
    WSADATA data;
    if (!(ret = WSAStartup( MAKEWORD(1,1), &data ))) winsock_loaded = TRUE;
    else ERR( "WSAStartup failed: %d\n", ret );
    return TRUE;
}

170
static void winsock_init(void)
171 172 173 174 175 176 177 178 179
{
    static INIT_ONCE once = INIT_ONCE_STATIC_INIT;
    InitOnceExecuteOnce( &once, winsock_startup, NULL, NULL );
}

static void set_blocking( netconn_t *conn, BOOL blocking )
{
    ULONG state = !blocking;
    ioctlsocket( conn->socket, FIONBIO, &state );
180 181
}

182
netconn_t *netconn_create( hostdata_t *host, const struct sockaddr_storage *sockaddr, int timeout )
183
{
184
    netconn_t *conn;
185 186
    unsigned int addr_len;
    BOOL ret = FALSE;
187 188

    winsock_init();
189

190 191
    conn = heap_alloc_zero(sizeof(*conn));
    if (!conn) return NULL;
192
    conn->host = host;
193 194
    conn->sockaddr = *sockaddr;
    if ((conn->socket = socket( sockaddr->ss_family, SOCK_STREAM, 0 )) == -1)
195
    {
196
        WARN("unable to create socket (%u)\n", WSAGetLastError());
197 198
        heap_free(conn);
        return NULL;
199
    }
200

201
    switch (conn->sockaddr.ss_family)
202 203 204 205 206 207 208 209 210 211 212
    {
    case AF_INET:
        addr_len = sizeof(struct sockaddr_in);
        break;
    case AF_INET6:
        addr_len = sizeof(struct sockaddr_in6);
        break;
    default:
        assert(0);
    }

213
    if (timeout > 0) set_blocking( conn, FALSE );
214

215 216
    if (!connect( conn->socket, (const struct sockaddr *)&conn->sockaddr, addr_len )) ret = TRUE;
    else
217
    {
218 219
        DWORD err = WSAGetLastError();
        if (err == WSAEWOULDBLOCK || err == WSAEINPROGRESS)
220
        {
221 222 223 224 225 226 227 228
            FD_SET set;
            TIMEVAL timeval = { 0, timeout * 1000 };
            int res;

            FD_ZERO( &set );
            FD_SET( conn->socket, &set );
            if ((res = select( conn->socket + 1, NULL, &set, NULL, &timeval )) > 0) ret = TRUE;
            else if (!res) set_last_error( ERROR_WINHTTP_TIMEOUT );
229 230
        }
    }
231 232 233

    if (timeout > 0) set_blocking( conn, TRUE );

234 235
    if (!ret)
    {
236
        WARN("unable to connect to host (%u)\n", get_last_error());
237 238
        closesocket( conn->socket );
        heap_free( conn );
239
        return NULL;
240
    }
241 242 243
    return conn;
}

244
void netconn_close( netconn_t *conn )
245 246 247 248 249 250 251 252
{
    if (conn->secure)
    {
        heap_free( conn->peek_msg_mem );
        heap_free(conn->ssl_buf);
        heap_free(conn->extra_buf);
        DeleteSecurityContext(&conn->ssl_ctx);
    }
253
    closesocket( conn->socket );
254
    release_host( conn->host );
255
    heap_free(conn);
256 257
}

258 259
BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname, DWORD security_flags, CredHandle *cred_handle,
                             BOOL check_revocation)
260
{
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
    SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
    BYTE *read_buf;
    SIZE_T read_buf_size = 2048;
    ULONG attrs = 0;
    CtxtHandle ctx;
    SSIZE_T size;
    const CERT_CONTEXT *cert;
    SECURITY_STATUS status;
    DWORD res = ERROR_SUCCESS;

    const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
        |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;

    read_buf = heap_alloc(read_buf_size);
    if(!read_buf)
        return FALSE;

279
    status = InitializeSecurityContextW(cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0,
280 281 282 283 284 285 286 287 288 289
            &ctx, &out_desc, &attrs, NULL);

    assert(status != SEC_E_OK);

    while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
        if(out_buf.cbBuffer) {
            assert(status == SEC_I_CONTINUE_NEEDED);

            TRACE("sending %u bytes\n", out_buf.cbBuffer);

290
            size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
291 292
            if(size != out_buf.cbBuffer) {
                ERR("send failed\n");
293
                res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
                break;
            }

            FreeContextBuffer(out_buf.pvBuffer);
            out_buf.pvBuffer = NULL;
            out_buf.cbBuffer = 0;
        }

        if(status == SEC_I_CONTINUE_NEEDED) {
            assert(in_bufs[1].cbBuffer < read_buf_size);

            memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
            in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;

            in_bufs[1].BufferType = SECBUFFER_EMPTY;
            in_bufs[1].cbBuffer = 0;
            in_bufs[1].pvBuffer = NULL;
        }

        assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
        assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);

        if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
            BYTE *new_read_buf;

            new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
            if(!new_read_buf) {
                status = E_OUTOFMEMORY;
                break;
            }

            in_bufs[0].pvBuffer = read_buf = new_read_buf;
            read_buf_size += 1024;
        }

329
        size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
330 331 332 333 334 335 336 337 338
        if(size < 1) {
            status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
            break;
        }

        TRACE("recv %lu bytes\n", size);

        in_bufs[0].cbBuffer += size;
        in_bufs[0].pvBuffer = read_buf;
339
        status = InitializeSecurityContextW(cred_handle, &ctx, hostname,  isc_req_flags, 0, 0, &in_desc,
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
                0, NULL, &out_desc, &attrs, NULL);
        TRACE("InitializeSecurityContext ret %08x\n", status);

        if(status == SEC_E_OK) {
            if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
                FIXME("SECBUFFER_EXTRA not supported\n");

            status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes);
            if(status != SEC_E_OK) {
                WARN("Could not get sizes\n");
                break;
            }

            status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
            if(status == SEC_E_OK) {
355
                res = netconn_verify_cert(cert, hostname, security_flags, check_revocation);
356 357 358 359 360 361 362 363 364
                CertFreeCertificateContext(cert);
                if(res != ERROR_SUCCESS) {
                    WARN("cert verify failed: %u\n", res);
                    break;
                }
            }else {
                WARN("Could not get cert\n");
                break;
            }
365 366 367 368 369 370

            conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer);
            if(!conn->ssl_buf) {
                res = GetLastError();
                break;
            }
371 372 373
        }
    }

374
    heap_free(read_buf);
375 376 377

    if(status != SEC_E_OK || res != ERROR_SUCCESS) {
        WARN("Failed to initialize security context failed: %08x\n", status);
378 379
        heap_free(conn->ssl_buf);
        conn->ssl_buf = NULL;
380 381 382 383 384 385 386 387 388 389
        DeleteSecurityContext(&ctx);
        set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR);
        return FALSE;
    }


    TRACE("established SSL connection\n");
    conn->secure = TRUE;
    conn->ssl_ctx = ctx;
    return TRUE;
390 391
}

392 393 394 395 396 397 398 399
static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
{
    SecBuffer bufs[4] = {
        {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
        {size,  SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
        {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
        {0, SECBUFFER_EMPTY, NULL}
    };
400
    SecBufferDesc buf_desc = {SECBUFFER_VERSION, ARRAY_SIZE(bufs), bufs};
401 402 403 404 405 406 407 408 409
    SECURITY_STATUS res;

    memcpy(bufs[1].pvBuffer, msg, size);
    res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
    if(res != SEC_E_OK) {
        WARN("EncryptMessage failed\n");
        return FALSE;
    }

410
    if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
411 412 413 414 415 416 417
        WARN("send failed\n");
        return FALSE;
    }

    return TRUE;
}

418
BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int *sent )
419
{
420 421
    if (conn->secure)
    {
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
        const BYTE *ptr = msg;
        size_t chunk_size;

        *sent = 0;

        while(len) {
            chunk_size = min(len, conn->ssl_sizes.cbMaximumMessage);
            if(!send_ssl_chunk(conn, ptr, chunk_size))
                return FALSE;

            *sent += chunk_size;
            ptr += chunk_size;
            len -= chunk_size;
        }

        return TRUE;
438
    }
439
    return ((*sent = sock_send( conn->socket, msg, len, 0 )) != -1);
440 441
}

442 443 444 445
static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
{
    const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
    SecBuffer bufs[4];
446
    SecBufferDesc buf_desc = {SECBUFFER_VERSION, ARRAY_SIZE(bufs), bufs};
447
    SSIZE_T size, buf_len;
448
    unsigned int i;
449 450 451 452 453 454 455 456 457 458 459
    SECURITY_STATUS res;

    assert(conn->extra_len < ssl_buf_size);

    if(conn->extra_len) {
        memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
        buf_len = conn->extra_len;
        conn->extra_len = 0;
        heap_free(conn->extra_buf);
        conn->extra_buf = NULL;
    }else {
460
        buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
461
        if(buf_len < 0)
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
            return FALSE;

        if(!buf_len) {
            *eof = TRUE;
            return TRUE;
        }
    }

    *ret_size = 0;
    *eof = FALSE;

    do {
        memset(bufs, 0, sizeof(bufs));
        bufs[0].BufferType = SECBUFFER_DATA;
        bufs[0].cbBuffer = buf_len;
        bufs[0].pvBuffer = conn->ssl_buf;

        res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
        switch(res) {
        case SEC_E_OK:
            break;
        case SEC_I_CONTEXT_EXPIRED:
            TRACE("context expired\n");
            *eof = TRUE;
            return TRUE;
        case SEC_E_INCOMPLETE_MESSAGE:
            assert(buf_len < ssl_buf_size);

490
            size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
491 492 493 494 495 496 497 498 499 500 501
            if(size < 1)
                return FALSE;

            buf_len += size;
            continue;
        default:
            WARN("failed: %08x\n", res);
            return FALSE;
        }
    } while(res != SEC_E_OK);

502
    for(i = 0; i < ARRAY_SIZE(bufs); i++) {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
        if(bufs[i].BufferType == SECBUFFER_DATA) {
            size = min(buf_size, bufs[i].cbBuffer);
            memcpy(buf, bufs[i].pvBuffer, size);
            if(size < bufs[i].cbBuffer) {
                assert(!conn->peek_len);
                conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
                if(!conn->peek_msg)
                    return FALSE;
                conn->peek_len = bufs[i].cbBuffer-size;
                memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
            }

            *ret_size = size;
        }
    }

519
    for(i = 0; i < ARRAY_SIZE(bufs); i++) {
520 521 522 523 524 525 526 527 528 529 530 531 532
        if(bufs[i].BufferType == SECBUFFER_EXTRA) {
            conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
            if(!conn->extra_buf)
                return FALSE;

            conn->extra_len = bufs[i].cbBuffer;
            memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
        }
    }

    return TRUE;
}

533 534 535 536
BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
{
    *recvd = 0;
    if (!len) return TRUE;
537 538 539

    if (conn->secure)
    {
540 541
        SIZE_T size, cread;
        BOOL res, eof;
542

543
        if (conn->peek_msg)
544 545 546 547 548 549 550 551 552 553 554 555 556
        {
            *recvd = min( len, conn->peek_len );
            memcpy( buf, conn->peek_msg, *recvd );
            conn->peek_len -= *recvd;
            conn->peek_msg += *recvd;

            if (conn->peek_len == 0)
            {
                heap_free( conn->peek_msg_mem );
                conn->peek_msg_mem = NULL;
                conn->peek_msg = NULL;
            }
            /* check if we have enough data from the peek buffer */
557
            if (!(flags & MSG_WAITALL) || *recvd == len) return TRUE;
558
        }
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
        size = *recvd;

        do {
            res = read_ssl_chunk(conn, (BYTE*)buf+size, len-size, &cread, &eof);
            if(!res) {
                WARN("read_ssl_chunk failed\n");
                if(!size)
                    return FALSE;
                break;
            }

            if(eof) {
                TRACE("EOF\n");
                break;
            }

            size += cread;
        }while(!size || ((flags & MSG_WAITALL) && size < len));

        TRACE("received %ld bytes\n", size);
        *recvd = size;
        return TRUE;
581
    }
582
    return ((*recvd = sock_recv( conn->socket, buf, len, flags )) != -1);
583 584
}

585
ULONG netconn_query_data_available( netconn_t *conn )
586
{
587
    return conn->secure ? conn->peek_len : 0;
588 589 590 591
}

DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
{
592 593
    int opt = send ? SO_SNDTIMEO : SO_RCVTIMEO;
    if (setsockopt( netconn->socket, SOL_SOCKET, opt, (void *)&value, sizeof(value) ) == -1)
594
    {
595 596 597
        DWORD err = WSAGetLastError();
        WARN("setsockopt failed (%u)\n", err );
        return err;
598 599 600 601
    }
    return ERROR_SUCCESS;
}

602 603 604 605
BOOL netconn_is_alive( netconn_t *netconn )
{
    int len;
    char b;
606
    DWORD err;
607

608 609 610 611
    set_blocking( netconn, FALSE );
    len = sock_recv( netconn->socket, &b, 1, MSG_PEEK );
    err = WSAGetLastError();
    set_blocking( netconn, TRUE );
612

613
    return len == 1 || (len == -1 && err == WSAEWOULDBLOCK);
614 615
}

616
static DWORD resolve_hostname( const WCHAR *name, INTERNET_PORT port, struct sockaddr_storage *sa )
617
{
618
    ADDRINFOW *res, hints;
619 620
    int ret;

621
    memset( &hints, 0, sizeof(hints) );
622 623 624
    /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
     * their IPv6 addresses even though they have IPv6 addresses in the DNS.
     */
625 626
    hints.ai_family = AF_INET;

627
    ret = GetAddrInfoW( name, NULL, &hints, &res );
628 629
    if (ret != 0)
    {
630
        TRACE("failed to get IPv4 address of %s, retrying with IPv6\n", debugstr_w(name));
631
        hints.ai_family = AF_INET6;
632
        ret = GetAddrInfoW( name, NULL, &hints, &res );
633 634
        if (ret != 0)
        {
635
            TRACE("failed to get address of %s\n", debugstr_w(name));
636
            return ERROR_WINHTTP_NAME_NOT_RESOLVED;
637
        }
638
    }
639 640 641 642 643 644
    memcpy( sa, res->ai_addr, res->ai_addrlen );
    switch (res->ai_family)
    {
    case AF_INET:
        ((struct sockaddr_in *)sa)->sin_port = htons( port );
        break;
645 646 647
    case AF_INET6:
        ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
        break;
648
    }
649

650
    FreeAddrInfoW( res );
651
    return ERROR_SUCCESS;
652
}
653

654 655
struct resolve_args
{
656 657 658
    const WCHAR             *hostname;
    INTERNET_PORT            port;
    struct sockaddr_storage *sa;
659 660 661 662 663
};

static DWORD CALLBACK resolve_proc( LPVOID arg )
{
    struct resolve_args *ra = arg;
664
    return resolve_hostname( ra->hostname, ra->port, ra->sa );
665 666
}

667
BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr_storage *sa, int timeout )
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
{
    DWORD ret;

    if (timeout)
    {
        DWORD status;
        HANDLE thread;
        struct resolve_args ra;

        ra.hostname = hostname;
        ra.port     = port;
        ra.sa       = sa;

        thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
        if (!thread) return FALSE;

        status = WaitForSingleObject( thread, timeout );
        if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
        else ret = ERROR_WINHTTP_TIMEOUT;
        CloseHandle( thread );
    }
689
    else ret = resolve_hostname( hostname, port, sa );
690 691 692 693 694 695 696 697 698

    if (ret)
    {
        set_last_error( ret );
        return FALSE;
    }
    return TRUE;
}

699 700
const void *netconn_get_certificate( netconn_t *conn )
{
701 702 703 704 705 706
    const CERT_CONTEXT *ret;
    SECURITY_STATUS res;

    if (!conn->secure) return NULL;
    res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
    return res == SEC_E_OK ? ret : NULL;
707
}
708 709 710

int netconn_get_cipher_strength( netconn_t *conn )
{
711 712 713 714 715 716 717 718
    SecPkgContext_ConnectionInfo conn_info;
    SECURITY_STATUS res;

    if (!conn->secure) return 0;
    res = QueryContextAttributesW(&conn->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
    if(res != SEC_E_OK)
        WARN("QueryContextAttributesW failed: %08x\n", res);
    return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
719
}