2 * Wininet - networking layer. Uses unix sockets.
4 * Copyright 2002 TransGaming Technologies Inc.
5 * Copyright 2013 Jacek Caban for CodeWeavers
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "wine/port.h"
27 #define NONAMELESSUNION
29 #if defined(__MINGW32__) || defined (_MSC_VER)
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_POLL_H
38 # include <sys/poll.h>
40 #ifdef HAVE_SYS_TIME_H
41 # include <sys/time.h>
43 #ifdef HAVE_SYS_SOCKET_H
44 # include <sys/socket.h>
46 #ifdef HAVE_SYS_FILIO_H
47 # include <sys/filio.h>
52 #ifdef HAVE_SYS_IOCTL_H
53 # include <sys/ioctl.h>
59 #ifdef HAVE_NETINET_IN_H
60 # include <netinet/in.h>
62 #ifdef HAVE_NETINET_TCP_H
63 # include <netinet/tcp.h>
73 #include "wine/library.h"
79 #include "wine/debug.h"
82 /* To avoid conflicts with the Unix socket headers. we only need it for
83 * the error codes anyway. */
87 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
90 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
93 * This should use winsock - To use winsock the functions will have to change a bit
94 * as they are designed for unix sockets.
97 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
100 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
101 PCCERT_CHAIN_CONTEXT chain;
102 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
103 char *server_auth[] = { oid_server_auth };
104 DWORD err = ERROR_SUCCESS, errors;
106 static const DWORD supportedErrors =
107 CERT_TRUST_IS_NOT_TIME_VALID |
108 CERT_TRUST_IS_UNTRUSTED_ROOT |
109 CERT_TRUST_IS_PARTIAL_CHAIN |
110 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
112 TRACE("verifying %s\n", debugstr_w(conn->server->name));
114 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
115 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
116 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
118 return GetLastError();
121 errors = chain->TrustStatus.dwErrorStatus;
124 /* This seems strange, but that's what tests show */
125 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
126 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
127 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
128 if(conn->mask_errors)
129 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
130 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
134 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
135 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
136 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
137 errors &= supportedErrors;
138 if(!conn->mask_errors)
140 WARN("unknown error flags\n");
143 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
144 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
145 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
146 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
147 if(!conn->mask_errors)
149 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
151 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
154 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
155 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
156 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
157 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
158 if(!conn->mask_errors)
160 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
162 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
165 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
166 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
167 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
168 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
169 if(!conn->mask_errors)
171 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
173 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
176 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
177 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
178 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
179 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
180 if(!conn->mask_errors)
182 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
184 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
187 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
188 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
193 if(!err || conn->mask_errors) {
194 CERT_CHAIN_POLICY_PARA policyPara;
195 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
196 CERT_CHAIN_POLICY_STATUS policyStatus;
197 CERT_CHAIN_CONTEXT chainCopy;
199 /* Clear chain->TrustStatus.dwErrorStatus so
200 * CertVerifyCertificateChainPolicy will verify additional checks
201 * rather than stopping with an existing, ignored error.
203 memcpy(&chainCopy, chain, sizeof(chainCopy));
204 chainCopy.TrustStatus.dwErrorStatus = 0;
205 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
206 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
207 sslExtraPolicyPara.pwszServerName = conn->server->name;
208 sslExtraPolicyPara.fdwChecks = conn->security_flags;
209 policyPara.cbSize = sizeof(policyPara);
210 policyPara.dwFlags = 0;
211 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
212 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
213 &chainCopy, &policyPara, &policyStatus);
214 /* Any error in the policy status indicates that the
215 * policy couldn't be verified.
218 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
219 WARN("CERT_E_CN_NO_MATCH\n");
220 if(conn->mask_errors)
221 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
222 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
223 }else if(policyStatus.dwError) {
224 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
225 if(conn->mask_errors)
226 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
227 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
230 err = GetLastError();
235 WARN("failed %u\n", err);
236 CertFreeCertificateChain(chain);
237 if(conn->server->cert_chain) {
238 CertFreeCertificateChain(conn->server->cert_chain);
239 conn->server->cert_chain = NULL;
241 if(conn->mask_errors)
242 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
246 /* FIXME: Reuse cached chain */
247 if(conn->server->cert_chain)
248 CertFreeCertificateChain(chain);
250 conn->server->cert_chain = chain;
251 return ERROR_SUCCESS;
254 static SecHandle cred_handle, compat_cred_handle;
255 static BOOL cred_handle_initialized, have_compat_cred_handle;
257 static CRITICAL_SECTION init_sechandle_cs;
258 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
259 0, 0, &init_sechandle_cs,
260 { &init_sechandle_cs_debug.ProcessLocksList,
261 &init_sechandle_cs_debug.ProcessLocksList },
262 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
264 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
266 static BOOL ensure_cred_handle(void)
268 SECURITY_STATUS res = SEC_E_OK;
270 EnterCriticalSection(&init_sechandle_cs);
272 if(!cred_handle_initialized) {
273 SCHANNEL_CRED cred = {SCHANNEL_CRED_VERSION};
274 SecPkgCred_SupportedProtocols prots;
276 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
277 NULL, NULL, &cred_handle, NULL);
278 if(res == SEC_E_OK) {
279 res = QueryCredentialsAttributesA(&cred_handle, SECPKG_ATTR_SUPPORTED_PROTOCOLS, &prots);
280 if(res != SEC_E_OK || (prots.grbitProtocol & SP_PROT_TLS1_1PLUS_CLIENT)) {
281 cred.grbitEnabledProtocols = prots.grbitProtocol & ~SP_PROT_TLS1_1PLUS_CLIENT;
282 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
283 NULL, NULL, &compat_cred_handle, NULL);
284 have_compat_cred_handle = res == SEC_E_OK;
288 cred_handle_initialized = res == SEC_E_OK;
291 LeaveCriticalSection(&init_sechandle_cs);
293 if(res != SEC_E_OK) {
294 WARN("Failed: %08x\n", res);
301 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
306 assert(server->addr_len);
307 result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
310 ioctlsocket(netconn->socket, FIONBIO, &flag);
311 result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
314 if (sock_get_error(errno) == WSAEINPROGRESS) {
318 pfd.fd = netconn->socket;
319 pfd.events = POLLOUT;
320 res = poll(&pfd, 1, timeout);
323 closesocket(netconn->socket);
324 return ERROR_INTERNET_CANNOT_CONNECT;
329 socklen_t len = sizeof(err);
330 if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&err, &len) && !err)
336 closesocket(netconn->socket);
339 ioctlsocket(netconn->socket, FIONBIO, &flag);
343 return ERROR_INTERNET_CANNOT_CONNECT;
347 result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
349 WARN("setsockopt(TCP_NODELAY) failed\n");
352 return ERROR_SUCCESS;
355 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
360 netconn = heap_alloc_zero(sizeof(*netconn));
362 return ERROR_OUTOFMEMORY;
364 netconn->socket = -1;
365 netconn->security_flags = security_flags | server->security_flags;
366 netconn->mask_errors = mask_errors;
367 list_init(&netconn->pool_entry);
369 result = create_netconn_socket(server, netconn, timeout);
370 if (result != ERROR_SUCCESS) {
375 server_addref(server);
376 netconn->server = server;
381 void free_netconn(netconn_t *netconn)
383 server_release(netconn->server);
385 if (netconn->secure) {
386 heap_free(netconn->peek_msg_mem);
387 netconn->peek_msg_mem = NULL;
388 netconn->peek_msg = NULL;
389 netconn->peek_len = 0;
390 heap_free(netconn->ssl_buf);
391 netconn->ssl_buf = NULL;
392 heap_free(netconn->extra_buf);
393 netconn->extra_buf = NULL;
394 netconn->extra_len = 0;
395 DeleteSecurityContext(&netconn->ssl_ctx);
398 closesocket(netconn->socket);
402 void NETCON_unload(void)
404 if(cred_handle_initialized)
405 FreeCredentialsHandle(&cred_handle);
406 if(have_compat_cred_handle)
407 FreeCredentialsHandle(&compat_cred_handle);
408 DeleteCriticalSection(&init_sechandle_cs);
411 /* translate a unix error code into a winsock one */
412 int sock_get_error( int err )
414 #if !defined(__MINGW32__) && !defined (_MSC_VER)
417 case EINTR: return WSAEINTR;
418 case EBADF: return WSAEBADF;
420 case EACCES: return WSAEACCES;
421 case EFAULT: return WSAEFAULT;
422 case EINVAL: return WSAEINVAL;
423 case EMFILE: return WSAEMFILE;
424 case EWOULDBLOCK: return WSAEWOULDBLOCK;
425 case EINPROGRESS: return WSAEINPROGRESS;
426 case EALREADY: return WSAEALREADY;
427 case ENOTSOCK: return WSAENOTSOCK;
428 case EDESTADDRREQ: return WSAEDESTADDRREQ;
429 case EMSGSIZE: return WSAEMSGSIZE;
430 case EPROTOTYPE: return WSAEPROTOTYPE;
431 case ENOPROTOOPT: return WSAENOPROTOOPT;
432 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
433 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
434 case EOPNOTSUPP: return WSAEOPNOTSUPP;
435 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
436 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
437 case EADDRINUSE: return WSAEADDRINUSE;
438 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
439 case ENETDOWN: return WSAENETDOWN;
440 case ENETUNREACH: return WSAENETUNREACH;
441 case ENETRESET: return WSAENETRESET;
442 case ECONNABORTED: return WSAECONNABORTED;
444 case ECONNRESET: return WSAECONNRESET;
445 case ENOBUFS: return WSAENOBUFS;
446 case EISCONN: return WSAEISCONN;
447 case ENOTCONN: return WSAENOTCONN;
448 case ESHUTDOWN: return WSAESHUTDOWN;
449 case ETOOMANYREFS: return WSAETOOMANYREFS;
450 case ETIMEDOUT: return WSAETIMEDOUT;
451 case ECONNREFUSED: return WSAECONNREFUSED;
452 case ELOOP: return WSAELOOP;
453 case ENAMETOOLONG: return WSAENAMETOOLONG;
454 case EHOSTDOWN: return WSAEHOSTDOWN;
455 case EHOSTUNREACH: return WSAEHOSTUNREACH;
456 case ENOTEMPTY: return WSAENOTEMPTY;
458 case EPROCLIM: return WSAEPROCLIM;
461 case EUSERS: return WSAEUSERS;
464 case EDQUOT: return WSAEDQUOT;
467 case ESTALE: return WSAESTALE;
470 case EREMOTE: return WSAEREMOTE;
472 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
478 static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode)
480 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
481 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
482 SecHandle *cred = &cred_handle;
484 SIZE_T read_buf_size = 2048;
489 const CERT_CONTEXT *cert;
490 SECURITY_STATUS status;
491 DWORD res = ERROR_SUCCESS;
493 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
494 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
496 if(!ensure_cred_handle())
500 if(!have_compat_cred_handle)
501 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
502 cred = &compat_cred_handle;
505 read_buf = heap_alloc(read_buf_size);
507 return ERROR_OUTOFMEMORY;
509 status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0,
510 &ctx, &out_desc, &attrs, NULL);
512 assert(status != SEC_E_OK);
514 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
515 if(out_buf.cbBuffer) {
516 assert(status == SEC_I_CONTINUE_NEEDED);
518 TRACE("sending %u bytes\n", out_buf.cbBuffer);
520 size = send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
521 if(size != out_buf.cbBuffer) {
522 ERR("send failed\n");
523 status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
527 FreeContextBuffer(out_buf.pvBuffer);
528 out_buf.pvBuffer = NULL;
529 out_buf.cbBuffer = 0;
532 if(status == SEC_I_CONTINUE_NEEDED) {
533 assert(in_bufs[1].cbBuffer < read_buf_size);
535 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
536 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
538 in_bufs[1].BufferType = SECBUFFER_EMPTY;
539 in_bufs[1].cbBuffer = 0;
540 in_bufs[1].pvBuffer = NULL;
543 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
544 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
546 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
549 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
551 status = E_OUTOFMEMORY;
555 in_bufs[0].pvBuffer = read_buf = new_read_buf;
556 read_buf_size += 1024;
559 size = recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
561 WARN("recv error\n");
562 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
566 TRACE("recv %lu bytes\n", size);
568 in_bufs[0].cbBuffer += size;
569 in_bufs[0].pvBuffer = read_buf;
570 status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc,
571 0, NULL, &out_desc, &attrs, NULL);
572 TRACE("InitializeSecurityContext ret %08x\n", status);
574 if(status == SEC_E_OK) {
575 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
576 FIXME("SECBUFFER_EXTRA not supported\n");
578 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes);
579 if(status != SEC_E_OK) {
580 WARN("Could not get sizes\n");
584 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
585 if(status == SEC_E_OK) {
586 res = netconn_verify_cert(connection, cert, cert->hCertStore);
587 CertFreeCertificateContext(cert);
588 if(res != ERROR_SUCCESS) {
589 WARN("cert verify failed: %u\n", res);
593 WARN("Could not get cert\n");
597 connection->ssl_buf = heap_alloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage
598 + connection->ssl_sizes.cbTrailer);
599 if(!connection->ssl_buf) {
600 res = GetLastError();
607 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
608 WARN("Failed to initialize security context failed: %08x\n", status);
609 heap_free(connection->ssl_buf);
610 connection->ssl_buf = NULL;
611 DeleteSecurityContext(&ctx);
612 return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
616 TRACE("established SSL connection\n");
617 connection->ssl_ctx = ctx;
619 connection->secure = TRUE;
620 connection->security_flags |= SECURITY_FLAG_SECURE;
622 bits = NETCON_GetCipherStrength(connection);
624 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
626 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
628 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
630 if(connection->mask_errors)
631 connection->server->security_flags = connection->security_flags;
632 return ERROR_SUCCESS;
635 /******************************************************************************
636 * NETCON_secure_connect
637 * Initiates a secure connection over an existing plaintext connection.
639 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
643 /* can't connect if we are already connected */
644 if(connection->secure) {
645 ERR("already connected\n");
646 return ERROR_INTERNET_CANNOT_CONNECT;
649 if(server != connection->server) {
650 server_release(connection->server);
651 server_addref(server);
652 connection->server = server;
655 /* connect with given TLS options */
656 res = netcon_secure_connect_setup(connection, FALSE);
657 if (res == ERROR_SUCCESS)
660 /* FIXME: when got version alert and FIN from server */
661 /* fallback to connect without TLSv1.1/TLSv1.2 */
662 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR && have_compat_cred_handle)
664 closesocket(connection->socket);
665 res = create_netconn_socket(connection->server, connection, 500);
666 if (res != ERROR_SUCCESS)
668 res = netcon_secure_connect_setup(connection, TRUE);
673 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
675 SecBuffer bufs[4] = {
676 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
677 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
678 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
679 {0, SECBUFFER_EMPTY, NULL}
681 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
684 memcpy(bufs[1].pvBuffer, msg, size);
685 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
686 if(res != SEC_E_OK) {
687 WARN("EncryptMessage failed\n");
691 if(send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
692 WARN("send failed\n");
699 /******************************************************************************
701 * Basically calls 'send()' unless we should use SSL
702 * number of chars send is put in *sent
704 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
707 if(!connection->secure)
709 *sent = send(connection->socket, msg, len, flags);
711 return sock_get_error(errno);
712 return ERROR_SUCCESS;
716 const BYTE *ptr = msg;
722 chunk_size = min(len, connection->ssl_sizes.cbMaximumMessage);
723 if(!send_ssl_chunk(connection, ptr, chunk_size))
724 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
731 return ERROR_SUCCESS;
735 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof)
737 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
739 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
740 SSIZE_T size, buf_len;
744 assert(conn->extra_len < ssl_buf_size);
746 if(conn->extra_len) {
747 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
748 buf_len = conn->extra_len;
750 heap_free(conn->extra_buf);
751 conn->extra_buf = NULL;
753 buf_len = recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0);
755 WARN("recv failed\n");
769 memset(bufs, 0, sizeof(bufs));
770 bufs[0].BufferType = SECBUFFER_DATA;
771 bufs[0].cbBuffer = buf_len;
772 bufs[0].pvBuffer = conn->ssl_buf;
774 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
778 case SEC_I_CONTEXT_EXPIRED:
779 TRACE("context expired\n");
782 case SEC_E_INCOMPLETE_MESSAGE:
783 assert(buf_len < ssl_buf_size);
785 size = recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
792 WARN("failed: %08x\n", res);
795 } while(res != SEC_E_OK);
797 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
798 if(bufs[i].BufferType == SECBUFFER_DATA) {
799 size = min(buf_size, bufs[i].cbBuffer);
800 memcpy(buf, bufs[i].pvBuffer, size);
801 if(size < bufs[i].cbBuffer) {
802 assert(!conn->peek_len);
803 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
806 conn->peek_len = bufs[i].cbBuffer-size;
807 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
814 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
815 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
816 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
820 conn->extra_len = bufs[i].cbBuffer;
821 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
828 /******************************************************************************
830 * Basically calls 'recv()' unless we should use SSL
831 * number of chars received is put in *recvd
833 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags, int *recvd)
837 return ERROR_SUCCESS;
839 if (!connection->secure)
841 *recvd = recv(connection->socket, buf, len, flags);
842 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
846 SIZE_T size = 0, cread;
849 if(connection->peek_msg) {
850 size = min(len, connection->peek_len);
851 memcpy(buf, connection->peek_msg, size);
852 connection->peek_len -= size;
853 connection->peek_msg += size;
855 if(!connection->peek_len) {
856 heap_free(connection->peek_msg_mem);
857 connection->peek_msg_mem = connection->peek_msg = NULL;
859 /* check if we have enough data from the peek buffer */
860 if(!(flags & MSG_WAITALL) || size == len) {
862 return ERROR_SUCCESS;
867 res = read_ssl_chunk(connection, (BYTE*)buf+size, len-size, &cread, &eof);
869 WARN("read_ssl_chunk failed\n");
871 return ERROR_INTERNET_CONNECTION_ABORTED;
881 }while(!size || ((flags & MSG_WAITALL) && size < len));
883 TRACE("received %ld bytes\n", size);
885 return ERROR_SUCCESS;
889 /******************************************************************************
890 * NETCON_query_data_available
891 * Returns the number of bytes of peeked data plus the number of bytes of
892 * queued, but unread data.
894 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
898 if(!connection->secure)
902 int retval = ioctlsocket(connection->socket, FIONREAD, &unread);
905 TRACE("%d bytes of queued, but unread data\n", unread);
906 *available += unread;
912 *available = connection->peek_len;
917 BOOL NETCON_is_alive(netconn_t *netconn)
923 len = recv(netconn->socket, &b, 1, MSG_PEEK|MSG_DONTWAIT);
924 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
925 #elif defined(__MINGW32__) || defined(_MSC_VER)
931 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
934 len = recv(netconn->socket, &b, 1, MSG_PEEK);
937 if(!ioctlsocket(netconn->socket, FIONBIO, &mode))
940 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
942 FIXME("not supported on this platform\n");
947 LPCVOID NETCON_GetCert(netconn_t *connection)
949 const CERT_CONTEXT *ret;
952 if (!connection->secure)
955 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
956 return res == SEC_E_OK ? ret : NULL;
959 int NETCON_GetCipherStrength(netconn_t *connection)
961 SecPkgContext_ConnectionInfo conn_info;
964 if (!connection->secure)
967 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
969 WARN("QueryContextAttributesW failed: %08x\n", res);
970 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
973 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
978 /* value is in milliseconds, convert to struct timeval */
979 if (value == INFINITE)
986 tv.tv_sec = value / 1000;
987 tv.tv_usec = (value % 1000) * 1000;
989 result = setsockopt(connection->socket, SOL_SOCKET,
990 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
994 WARN("setsockopt failed (%s)\n", strerror(errno));
995 return sock_get_error(errno);
997 return ERROR_SUCCESS;