webservices: Implement WsWriteEndAttribute.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blob73058602f6a5b2e6dd1464e1b0d904930e7d747e
1 /*
2 * Wininet - networking layer
4 * Copyright 2002 TransGaming Technologies Inc.
5 * Copyright 2013 Jacek Caban for CodeWeavers
7 * David Hammerton
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
24 #define NONAMELESSUNION
26 #include "ws2tcpip.h"
28 #include <time.h>
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <assert.h>
35 #include "wine/library.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "wininet.h"
39 #include "winerror.h"
41 #include "wine/debug.h"
42 #include "internet.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
46 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
48 BOOL ret;
49 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
50 PCCERT_CHAIN_CONTEXT chain;
51 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
52 char *server_auth[] = { oid_server_auth };
53 DWORD err = ERROR_SUCCESS, errors;
55 static const DWORD supportedErrors =
56 CERT_TRUST_IS_NOT_TIME_VALID |
57 CERT_TRUST_IS_UNTRUSTED_ROOT |
58 CERT_TRUST_IS_PARTIAL_CHAIN |
59 CERT_TRUST_IS_NOT_SIGNATURE_VALID |
60 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
62 TRACE("verifying %s\n", debugstr_w(conn->server->name));
64 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
65 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
66 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
67 TRACE("failed\n");
68 return GetLastError();
71 errors = chain->TrustStatus.dwErrorStatus;
73 do {
74 /* This seems strange, but that's what tests show */
75 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
76 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
77 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
78 if(conn->mask_errors)
79 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
80 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
81 break;
84 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
85 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
86 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
87 errors &= supportedErrors;
88 if(!conn->mask_errors)
89 break;
90 WARN("unknown error flags\n");
93 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
94 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
95 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
96 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
97 if(!conn->mask_errors)
98 break;
99 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
101 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
104 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
105 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
106 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
107 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
108 if(!conn->mask_errors)
109 break;
110 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
112 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
115 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
116 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
117 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
118 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
119 if(!conn->mask_errors)
120 break;
121 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
123 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
126 if(errors & CERT_TRUST_IS_NOT_SIGNATURE_VALID) {
127 WARN("CERT_TRUST_IS_NOT_SIGNATURE_VALID\n");
128 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
129 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
130 if(!conn->mask_errors)
131 break;
132 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
134 errors &= ~CERT_TRUST_IS_NOT_SIGNATURE_VALID;
137 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
138 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
139 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
140 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
141 if(!conn->mask_errors)
142 break;
143 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
145 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
148 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
149 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
150 err = ERROR_SUCCESS;
152 }while(0);
154 if(!err || conn->mask_errors) {
155 CERT_CHAIN_POLICY_PARA policyPara;
156 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
157 CERT_CHAIN_POLICY_STATUS policyStatus;
158 CERT_CHAIN_CONTEXT chainCopy;
160 /* Clear chain->TrustStatus.dwErrorStatus so
161 * CertVerifyCertificateChainPolicy will verify additional checks
162 * rather than stopping with an existing, ignored error.
164 memcpy(&chainCopy, chain, sizeof(chainCopy));
165 chainCopy.TrustStatus.dwErrorStatus = 0;
166 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
167 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
168 sslExtraPolicyPara.pwszServerName = conn->server->name;
169 sslExtraPolicyPara.fdwChecks = conn->security_flags;
170 policyPara.cbSize = sizeof(policyPara);
171 policyPara.dwFlags = 0;
172 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
173 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
174 &chainCopy, &policyPara, &policyStatus);
175 /* Any error in the policy status indicates that the
176 * policy couldn't be verified.
178 if(ret) {
179 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
180 WARN("CERT_E_CN_NO_MATCH\n");
181 if(conn->mask_errors)
182 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
183 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
184 }else if(policyStatus.dwError) {
185 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
186 if(conn->mask_errors)
187 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
188 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
190 }else {
191 err = GetLastError();
195 if(err) {
196 WARN("failed %u\n", err);
197 CertFreeCertificateChain(chain);
198 if(conn->server->cert_chain) {
199 CertFreeCertificateChain(conn->server->cert_chain);
200 conn->server->cert_chain = NULL;
202 if(conn->mask_errors)
203 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
204 return err;
207 /* FIXME: Reuse cached chain */
208 if(conn->server->cert_chain)
209 CertFreeCertificateChain(chain);
210 else
211 conn->server->cert_chain = chain;
212 return ERROR_SUCCESS;
215 static SecHandle cred_handle, compat_cred_handle;
216 static BOOL cred_handle_initialized, have_compat_cred_handle;
218 static CRITICAL_SECTION init_sechandle_cs;
219 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
220 0, 0, &init_sechandle_cs,
221 { &init_sechandle_cs_debug.ProcessLocksList,
222 &init_sechandle_cs_debug.ProcessLocksList },
223 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
225 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
227 static BOOL ensure_cred_handle(void)
229 SECURITY_STATUS res = SEC_E_OK;
231 EnterCriticalSection(&init_sechandle_cs);
233 if(!cred_handle_initialized) {
234 SCHANNEL_CRED cred = {SCHANNEL_CRED_VERSION};
235 SecPkgCred_SupportedProtocols prots;
237 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
238 NULL, NULL, &cred_handle, NULL);
239 if(res == SEC_E_OK) {
240 res = QueryCredentialsAttributesA(&cred_handle, SECPKG_ATTR_SUPPORTED_PROTOCOLS, &prots);
241 if(res != SEC_E_OK || (prots.grbitProtocol & SP_PROT_TLS1_1PLUS_CLIENT)) {
242 cred.grbitEnabledProtocols = prots.grbitProtocol & ~SP_PROT_TLS1_1PLUS_CLIENT;
243 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
244 NULL, NULL, &compat_cred_handle, NULL);
245 have_compat_cred_handle = res == SEC_E_OK;
249 cred_handle_initialized = res == SEC_E_OK;
252 LeaveCriticalSection(&init_sechandle_cs);
254 if(res != SEC_E_OK) {
255 WARN("Failed: %08x\n", res);
256 return FALSE;
259 return TRUE;
262 static BOOL winsock_loaded = FALSE;
264 static BOOL WINAPI winsock_startup(INIT_ONCE *once, void *param, void **context)
266 WSADATA wsa_data;
267 DWORD res;
269 res = WSAStartup(MAKEWORD(1,1), &wsa_data);
270 if(res == ERROR_SUCCESS)
271 winsock_loaded = TRUE;
272 else
273 ERR("WSAStartup failed: %u\n", res);
274 return TRUE;
277 void init_winsock(void)
279 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
280 InitOnceExecuteOnce(&init_once, winsock_startup, NULL, NULL);
283 static void set_socket_blocking(netconn_t *conn, BOOL is_blocking)
285 if(conn->is_blocking != is_blocking) {
286 ULONG arg = !is_blocking;
287 ioctlsocket(conn->socket, FIONBIO, &arg);
289 conn->is_blocking = is_blocking;
292 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
294 int result;
295 ULONG flag;
296 DWORD res;
298 init_winsock();
300 assert(server->addr_len);
301 result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
302 if(result != -1) {
303 set_socket_blocking(netconn, FALSE);
304 result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
305 if(result == -1)
307 res = WSAGetLastError();
308 if (res == WSAEINPROGRESS || res == WSAEWOULDBLOCK) {
309 FD_SET set;
310 int res;
311 socklen_t len = sizeof(res);
312 TIMEVAL timeout_timeval = {0, timeout*1000};
314 FD_ZERO(&set);
315 FD_SET(netconn->socket, &set);
316 res = select(netconn->socket+1, NULL, &set, NULL, &timeout_timeval);
317 if(!res || res == SOCKET_ERROR) {
318 closesocket(netconn->socket);
319 netconn->socket = -1;
320 return ERROR_INTERNET_CANNOT_CONNECT;
322 if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&res, &len) && !res)
323 result = 0;
326 if(result == -1)
328 closesocket(netconn->socket);
329 netconn->socket = -1;
332 if(result == -1)
333 return ERROR_INTERNET_CANNOT_CONNECT;
335 flag = 1;
336 result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
337 if(result < 0)
338 WARN("setsockopt(TCP_NODELAY) failed\n");
340 return ERROR_SUCCESS;
343 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
345 netconn_t *netconn;
346 int result;
348 netconn = heap_alloc_zero(sizeof(*netconn));
349 if(!netconn)
350 return ERROR_OUTOFMEMORY;
352 netconn->socket = -1;
353 netconn->security_flags = security_flags | server->security_flags;
354 netconn->mask_errors = mask_errors;
355 list_init(&netconn->pool_entry);
356 SecInvalidateHandle(&netconn->ssl_ctx);
358 result = create_netconn_socket(server, netconn, timeout);
359 if (result != ERROR_SUCCESS) {
360 heap_free(netconn);
361 return result;
364 server_addref(server);
365 netconn->server = server;
366 *ret = netconn;
367 return result;
370 BOOL is_valid_netconn(netconn_t *netconn)
372 return netconn && netconn->socket != -1;
375 void close_netconn(netconn_t *netconn)
377 closesocket(netconn->socket);
378 netconn->socket = -1;
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 if (SecIsValidHandle(&netconn->ssl_ctx))
396 DeleteSecurityContext(&netconn->ssl_ctx);
399 heap_free(netconn);
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);
409 if(winsock_loaded)
410 WSACleanup();
413 int sock_send(int fd, const void *msg, size_t len, int flags)
415 int ret;
418 ret = send(fd, msg, len, flags);
420 while(ret == -1 && WSAGetLastError() == WSAEINTR);
421 return ret;
424 int sock_recv(int fd, void *msg, size_t len, int flags)
426 int ret;
429 ret = recv(fd, msg, len, flags);
431 while(ret == -1 && WSAGetLastError() == WSAEINTR);
432 return ret;
435 static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode)
437 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
438 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
439 SecHandle *cred = &cred_handle;
440 BYTE *read_buf;
441 SIZE_T read_buf_size = 2048;
442 ULONG attrs = 0;
443 CtxtHandle ctx;
444 SSIZE_T size;
445 int bits;
446 const CERT_CONTEXT *cert;
447 SECURITY_STATUS status;
448 DWORD res = ERROR_SUCCESS;
450 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
451 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
453 if(!ensure_cred_handle())
454 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
456 if(compat_mode) {
457 if(!have_compat_cred_handle)
458 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
459 cred = &compat_cred_handle;
462 read_buf = heap_alloc(read_buf_size);
463 if(!read_buf)
464 return ERROR_OUTOFMEMORY;
466 status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0,
467 &ctx, &out_desc, &attrs, NULL);
469 assert(status != SEC_E_OK);
471 set_socket_blocking(connection, TRUE);
473 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
474 if(out_buf.cbBuffer) {
475 assert(status == SEC_I_CONTINUE_NEEDED);
477 TRACE("sending %u bytes\n", out_buf.cbBuffer);
479 size = sock_send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
480 if(size != out_buf.cbBuffer) {
481 ERR("send failed\n");
482 status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
483 break;
486 FreeContextBuffer(out_buf.pvBuffer);
487 out_buf.pvBuffer = NULL;
488 out_buf.cbBuffer = 0;
491 if(status == SEC_I_CONTINUE_NEEDED) {
492 assert(in_bufs[1].cbBuffer < read_buf_size);
494 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
495 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
497 in_bufs[1].BufferType = SECBUFFER_EMPTY;
498 in_bufs[1].cbBuffer = 0;
499 in_bufs[1].pvBuffer = NULL;
502 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
503 assert(in_bufs[1].BufferType == SECBUFFER_EMPTY);
505 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
506 BYTE *new_read_buf;
508 new_read_buf = heap_realloc(read_buf, read_buf_size + 1024);
509 if(!new_read_buf) {
510 status = E_OUTOFMEMORY;
511 break;
514 in_bufs[0].pvBuffer = read_buf = new_read_buf;
515 read_buf_size += 1024;
518 size = sock_recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
519 if(size < 1) {
520 WARN("recv error\n");
521 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
522 break;
525 TRACE("recv %lu bytes\n", size);
527 in_bufs[0].cbBuffer += size;
528 in_bufs[0].pvBuffer = read_buf;
529 status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc,
530 0, NULL, &out_desc, &attrs, NULL);
531 TRACE("InitializeSecurityContext ret %08x\n", status);
533 if(status == SEC_E_OK) {
534 if(SecIsValidHandle(&connection->ssl_ctx))
535 DeleteSecurityContext(&connection->ssl_ctx);
536 connection->ssl_ctx = ctx;
538 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
539 FIXME("SECBUFFER_EXTRA not supported\n");
541 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes);
542 if(status != SEC_E_OK) {
543 WARN("Could not get sizes\n");
544 break;
547 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
548 if(status == SEC_E_OK) {
549 res = netconn_verify_cert(connection, cert, cert->hCertStore);
550 CertFreeCertificateContext(cert);
551 if(res != ERROR_SUCCESS) {
552 WARN("cert verify failed: %u\n", res);
553 break;
555 }else {
556 WARN("Could not get cert\n");
557 break;
560 connection->ssl_buf = heap_alloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage
561 + connection->ssl_sizes.cbTrailer);
562 if(!connection->ssl_buf) {
563 res = GetLastError();
564 break;
569 heap_free(read_buf);
571 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
572 WARN("Failed to establish SSL connection: %08x (%u)\n", status, res);
573 heap_free(connection->ssl_buf);
574 connection->ssl_buf = NULL;
575 return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
578 TRACE("established SSL connection\n");
579 connection->secure = TRUE;
580 connection->security_flags |= SECURITY_FLAG_SECURE;
582 bits = NETCON_GetCipherStrength(connection);
583 if (bits >= 128)
584 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
585 else if (bits >= 56)
586 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
587 else
588 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
590 if(connection->mask_errors)
591 connection->server->security_flags = connection->security_flags;
592 return ERROR_SUCCESS;
595 /******************************************************************************
596 * NETCON_secure_connect
597 * Initiates a secure connection over an existing plaintext connection.
599 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
601 DWORD res;
603 /* can't connect if we are already connected */
604 if(connection->secure) {
605 ERR("already connected\n");
606 return ERROR_INTERNET_CANNOT_CONNECT;
609 if(server != connection->server) {
610 server_release(connection->server);
611 server_addref(server);
612 connection->server = server;
615 /* connect with given TLS options */
616 res = netcon_secure_connect_setup(connection, FALSE);
617 if (res == ERROR_SUCCESS)
618 return res;
620 /* FIXME: when got version alert and FIN from server */
621 /* fallback to connect without TLSv1.1/TLSv1.2 */
622 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR && have_compat_cred_handle)
624 closesocket(connection->socket);
625 res = create_netconn_socket(connection->server, connection, 500);
626 if (res != ERROR_SUCCESS)
627 return res;
628 res = netcon_secure_connect_setup(connection, TRUE);
630 return res;
633 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
635 SecBuffer bufs[4] = {
636 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
637 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
638 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
639 {0, SECBUFFER_EMPTY, NULL}
641 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
642 SECURITY_STATUS res;
644 memcpy(bufs[1].pvBuffer, msg, size);
645 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
646 if(res != SEC_E_OK) {
647 WARN("EncryptMessage failed\n");
648 return FALSE;
651 if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
652 WARN("send failed\n");
653 return FALSE;
656 return TRUE;
659 /******************************************************************************
660 * NETCON_send
661 * Basically calls 'send()' unless we should use SSL
662 * number of chars send is put in *sent
664 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
665 int *sent /* out */)
667 /* send is always blocking. */
668 set_socket_blocking(connection, TRUE);
670 if(!connection->secure)
672 *sent = sock_send(connection->socket, msg, len, flags);
673 return *sent == -1 ? WSAGetLastError() : ERROR_SUCCESS;
675 else
677 const BYTE *ptr = msg;
678 size_t chunk_size;
680 *sent = 0;
682 while(len) {
683 chunk_size = min(len, connection->ssl_sizes.cbMaximumMessage);
684 if(!send_ssl_chunk(connection, ptr, chunk_size))
685 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
687 *sent += chunk_size;
688 ptr += chunk_size;
689 len -= chunk_size;
692 return ERROR_SUCCESS;
696 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, BOOL blocking, SIZE_T *ret_size, BOOL *eof)
698 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
699 SecBuffer bufs[4];
700 SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs};
701 SSIZE_T size, buf_len = 0;
702 int i;
703 SECURITY_STATUS res;
705 assert(conn->extra_len < ssl_buf_size);
707 if(conn->extra_len) {
708 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
709 buf_len = conn->extra_len;
710 conn->extra_len = 0;
711 heap_free(conn->extra_buf);
712 conn->extra_buf = NULL;
715 set_socket_blocking(conn, blocking && !buf_len);
716 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
717 if(size < 0) {
718 if(!buf_len) {
719 if(WSAGetLastError() == WSAEWOULDBLOCK) {
720 TRACE("would block\n");
721 return WSAEWOULDBLOCK;
723 WARN("recv failed\n");
724 return ERROR_INTERNET_CONNECTION_ABORTED;
726 }else {
727 buf_len += size;
730 if(!buf_len) {
731 TRACE("EOF\n");
732 *eof = TRUE;
733 *ret_size = 0;
734 return ERROR_SUCCESS;
737 *eof = FALSE;
739 do {
740 memset(bufs, 0, sizeof(bufs));
741 bufs[0].BufferType = SECBUFFER_DATA;
742 bufs[0].cbBuffer = buf_len;
743 bufs[0].pvBuffer = conn->ssl_buf;
745 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
746 switch(res) {
747 case SEC_E_OK:
748 break;
749 case SEC_I_CONTEXT_EXPIRED:
750 TRACE("context expired\n");
751 *eof = TRUE;
752 return ERROR_SUCCESS;
753 case SEC_E_INCOMPLETE_MESSAGE:
754 assert(buf_len < ssl_buf_size);
756 set_socket_blocking(conn, blocking);
757 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
758 if(size < 1) {
759 if(size < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
760 TRACE("would block\n");
762 /* FIXME: Optimize extra_buf usage. */
763 conn->extra_buf = heap_alloc(buf_len);
764 if(!conn->extra_buf)
765 return ERROR_NOT_ENOUGH_MEMORY;
767 conn->extra_len = buf_len;
768 memcpy(conn->extra_buf, conn->ssl_buf, conn->extra_len);
769 return WSAEWOULDBLOCK;
772 return ERROR_INTERNET_CONNECTION_ABORTED;
775 buf_len += size;
776 continue;
777 default:
778 WARN("failed: %08x\n", res);
779 return ERROR_INTERNET_CONNECTION_ABORTED;
781 } while(res != SEC_E_OK);
783 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
784 if(bufs[i].BufferType == SECBUFFER_DATA) {
785 size = min(buf_size, bufs[i].cbBuffer);
786 memcpy(buf, bufs[i].pvBuffer, size);
787 if(size < bufs[i].cbBuffer) {
788 assert(!conn->peek_len);
789 conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size);
790 if(!conn->peek_msg)
791 return ERROR_NOT_ENOUGH_MEMORY;
792 conn->peek_len = bufs[i].cbBuffer-size;
793 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
796 *ret_size = size;
800 for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) {
801 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
802 conn->extra_buf = heap_alloc(bufs[i].cbBuffer);
803 if(!conn->extra_buf)
804 return ERROR_NOT_ENOUGH_MEMORY;
806 conn->extra_len = bufs[i].cbBuffer;
807 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
811 return ERROR_SUCCESS;
814 /******************************************************************************
815 * NETCON_recv
816 * Basically calls 'recv()' unless we should use SSL
817 * number of chars received is put in *recvd
819 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, BOOL blocking, int *recvd)
821 *recvd = 0;
822 if (!len)
823 return ERROR_SUCCESS;
825 if (!connection->secure)
827 set_socket_blocking(connection, blocking);
828 *recvd = sock_recv(connection->socket, buf, len, 0);
829 return *recvd == -1 ? WSAGetLastError() : ERROR_SUCCESS;
831 else
833 SIZE_T size = 0;
834 BOOL eof;
835 DWORD res;
837 if(connection->peek_msg) {
838 size = min(len, connection->peek_len);
839 memcpy(buf, connection->peek_msg, size);
840 connection->peek_len -= size;
841 connection->peek_msg += size;
843 if(!connection->peek_len) {
844 heap_free(connection->peek_msg_mem);
845 connection->peek_msg_mem = connection->peek_msg = NULL;
848 *recvd = size;
849 return ERROR_SUCCESS;
852 do {
853 res = read_ssl_chunk(connection, (BYTE*)buf, len, blocking, &size, &eof);
854 if(res != ERROR_SUCCESS) {
855 if(res == WSAEWOULDBLOCK) {
856 if(size)
857 res = ERROR_SUCCESS;
858 }else {
859 WARN("read_ssl_chunk failed\n");
861 break;
863 }while(!size && !eof);
865 TRACE("received %ld bytes\n", size);
866 *recvd = size;
867 return res;
871 /******************************************************************************
872 * NETCON_query_data_available
873 * Returns the number of bytes of peeked data plus the number of bytes of
874 * queued, but unread data.
876 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
878 *available = 0;
880 if(!connection->secure)
882 ULONG unread;
883 int retval = ioctlsocket(connection->socket, FIONREAD, &unread);
884 if (!retval)
886 TRACE("%d bytes of queued, but unread data\n", unread);
887 *available += unread;
890 else
892 *available = connection->peek_len;
894 return TRUE;
897 BOOL NETCON_is_alive(netconn_t *netconn)
899 int len;
900 char b;
902 set_socket_blocking(netconn, FALSE);
903 len = sock_recv(netconn->socket, &b, 1, MSG_PEEK);
905 return len == 1 || (len == -1 && WSAGetLastError() == WSAEWOULDBLOCK);
908 LPCVOID NETCON_GetCert(netconn_t *connection)
910 const CERT_CONTEXT *ret;
911 SECURITY_STATUS res;
913 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
914 return res == SEC_E_OK ? ret : NULL;
917 int NETCON_GetCipherStrength(netconn_t *connection)
919 SecPkgContext_ConnectionInfo conn_info;
920 SECURITY_STATUS res;
922 if (!connection->secure)
923 return 0;
925 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
926 if(res != SEC_E_OK)
927 WARN("QueryContextAttributesW failed: %08x\n", res);
928 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
931 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
933 int result;
935 result = setsockopt(connection->socket, SOL_SOCKET,
936 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&value,
937 sizeof(value));
938 if (result == -1)
940 WARN("setsockopt failed\n");
941 return WSAGetLastError();
943 return ERROR_SUCCESS;