widl: Add support for function parameter flags to SLTG typelib generator.
[wine.git] / dlls / wininet / netconnection.c
blob06aa5c82f6cefdabed6569f84b36af8336128f10
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 #include "ws2tcpip.h"
26 #include <time.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <assert.h>
33 #include "windef.h"
34 #include "winbase.h"
35 #include "wininet.h"
36 #include "winerror.h"
38 #include "wine/debug.h"
39 #include "internet.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
43 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
45 BOOL ret;
46 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
47 PCCERT_CHAIN_CONTEXT chain;
48 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
49 char *server_auth[] = { oid_server_auth };
50 DWORD err = ERROR_SUCCESS, errors;
52 static const DWORD supportedErrors =
53 CERT_TRUST_IS_NOT_TIME_VALID |
54 CERT_TRUST_IS_UNTRUSTED_ROOT |
55 CERT_TRUST_IS_PARTIAL_CHAIN |
56 CERT_TRUST_IS_NOT_SIGNATURE_VALID |
57 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
59 TRACE("verifying %s\n", debugstr_w(conn->server->name));
61 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
62 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
63 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
64 TRACE("failed\n");
65 return GetLastError();
68 errors = chain->TrustStatus.dwErrorStatus;
70 do {
71 /* This seems strange, but that's what tests show */
72 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
73 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
74 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
75 if(conn->mask_errors)
76 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
77 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
78 break;
81 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
82 WARN("error status %lx\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
83 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
84 errors &= supportedErrors;
85 if(!conn->mask_errors)
86 break;
87 WARN("unknown error flags\n");
90 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
91 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
92 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
93 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
94 if(!conn->mask_errors)
95 break;
96 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
98 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
101 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
102 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
103 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
104 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
105 if(!conn->mask_errors)
106 break;
107 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
109 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
112 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
113 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
114 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
115 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
116 if(!conn->mask_errors)
117 break;
118 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
120 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
123 if(errors & CERT_TRUST_IS_NOT_SIGNATURE_VALID) {
124 WARN("CERT_TRUST_IS_NOT_SIGNATURE_VALID\n");
125 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
126 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
127 if(!conn->mask_errors)
128 break;
129 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
131 errors &= ~CERT_TRUST_IS_NOT_SIGNATURE_VALID;
134 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
135 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
136 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
137 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
138 if(!conn->mask_errors)
139 break;
140 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
142 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
145 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
146 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
147 err = ERROR_SUCCESS;
149 }while(0);
151 if(!err || conn->mask_errors) {
152 CERT_CHAIN_POLICY_PARA policyPara;
153 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
154 CERT_CHAIN_POLICY_STATUS policyStatus;
155 CERT_CHAIN_CONTEXT chainCopy;
157 /* Clear chain->TrustStatus.dwErrorStatus so
158 * CertVerifyCertificateChainPolicy will verify additional checks
159 * rather than stopping with an existing, ignored error.
161 memcpy(&chainCopy, chain, sizeof(chainCopy));
162 chainCopy.TrustStatus.dwErrorStatus = 0;
163 sslExtraPolicyPara.cbSize = sizeof(sslExtraPolicyPara);
164 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
165 sslExtraPolicyPara.pwszServerName = conn->server->name;
166 sslExtraPolicyPara.fdwChecks = conn->security_flags;
167 policyPara.cbSize = sizeof(policyPara);
168 policyPara.dwFlags = 0;
169 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
170 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
171 &chainCopy, &policyPara, &policyStatus);
172 /* Any error in the policy status indicates that the
173 * policy couldn't be verified.
175 if(ret) {
176 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
177 WARN("CERT_E_CN_NO_MATCH\n");
178 if(conn->mask_errors)
179 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
180 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
181 }else if(policyStatus.dwError) {
182 WARN("policyStatus.dwError %lx\n", policyStatus.dwError);
183 if(conn->mask_errors)
184 WARN("unknown error flags for policy status %lx\n", policyStatus.dwError);
185 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
187 }else {
188 err = GetLastError();
192 if(err) {
193 WARN("failed %lu\n", err);
194 CertFreeCertificateChain(chain);
195 if(conn->server->cert_chain) {
196 CertFreeCertificateChain(conn->server->cert_chain);
197 conn->server->cert_chain = NULL;
199 if(conn->mask_errors)
200 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
201 return err;
204 /* FIXME: Reuse cached chain */
205 if(conn->server->cert_chain)
206 CertFreeCertificateChain(chain);
207 else
208 conn->server->cert_chain = chain;
209 return ERROR_SUCCESS;
212 static SecHandle cred_handle, compat_cred_handle;
213 static BOOL cred_handle_initialized, have_compat_cred_handle;
215 static CRITICAL_SECTION init_sechandle_cs;
216 static CRITICAL_SECTION_DEBUG init_sechandle_cs_debug = {
217 0, 0, &init_sechandle_cs,
218 { &init_sechandle_cs_debug.ProcessLocksList,
219 &init_sechandle_cs_debug.ProcessLocksList },
220 0, 0, { (DWORD_PTR)(__FILE__ ": init_sechandle_cs") }
222 static CRITICAL_SECTION init_sechandle_cs = { &init_sechandle_cs_debug, -1, 0, 0, 0, 0 };
224 static BOOL ensure_cred_handle(void)
226 SECURITY_STATUS res = SEC_E_OK;
228 EnterCriticalSection(&init_sechandle_cs);
230 if(!cred_handle_initialized) {
231 SCHANNEL_CRED cred = {SCHANNEL_CRED_VERSION};
232 SecPkgCred_SupportedProtocols prots;
234 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
235 NULL, NULL, &cred_handle, NULL);
236 if(res == SEC_E_OK) {
237 res = QueryCredentialsAttributesA(&cred_handle, SECPKG_ATTR_SUPPORTED_PROTOCOLS, &prots);
238 if(res != SEC_E_OK || (prots.grbitProtocol & SP_PROT_TLS1_1PLUS_CLIENT)) {
239 cred.grbitEnabledProtocols = prots.grbitProtocol & ~SP_PROT_TLS1_1PLUS_CLIENT;
240 res = AcquireCredentialsHandleW(NULL, (WCHAR*)UNISP_NAME_W, SECPKG_CRED_OUTBOUND, NULL, &cred,
241 NULL, NULL, &compat_cred_handle, NULL);
242 have_compat_cred_handle = res == SEC_E_OK;
246 cred_handle_initialized = res == SEC_E_OK;
249 LeaveCriticalSection(&init_sechandle_cs);
251 if(res != SEC_E_OK) {
252 WARN("Failed: %08lx\n", res);
253 return FALSE;
256 return TRUE;
259 static BOOL winsock_loaded = FALSE;
261 static BOOL WINAPI winsock_startup(INIT_ONCE *once, void *param, void **context)
263 WSADATA wsa_data;
264 DWORD res;
266 res = WSAStartup(MAKEWORD(1,1), &wsa_data);
267 if(res == ERROR_SUCCESS)
268 winsock_loaded = TRUE;
269 else
270 ERR("WSAStartup failed: %lu\n", res);
271 return TRUE;
274 void init_winsock(void)
276 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
277 InitOnceExecuteOnce(&init_once, winsock_startup, NULL, NULL);
280 static void set_socket_blocking(netconn_t *conn, BOOL is_blocking)
282 if(conn->is_blocking != is_blocking) {
283 ULONG arg = !is_blocking;
284 ioctlsocket(conn->socket, FIONBIO, &arg);
286 conn->is_blocking = is_blocking;
289 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
291 int result;
292 ULONG flag;
293 DWORD res;
295 init_winsock();
297 assert(server->addr_len);
298 result = netconn->socket = socket(server->addr.ss_family, SOCK_STREAM, 0);
299 if(result != -1) {
300 set_socket_blocking(netconn, FALSE);
301 result = connect(netconn->socket, (struct sockaddr*)&server->addr, server->addr_len);
302 if(result == -1)
304 res = WSAGetLastError();
305 if (res == WSAEINPROGRESS || res == WSAEWOULDBLOCK) {
306 FD_SET set;
307 int res;
308 socklen_t len = sizeof(res);
309 TIMEVAL timeout_timeval = {0, timeout*1000};
311 FD_ZERO(&set);
312 FD_SET(netconn->socket, &set);
313 res = select(netconn->socket+1, NULL, &set, NULL, &timeout_timeval);
314 if(!res || res == SOCKET_ERROR) {
315 closesocket(netconn->socket);
316 netconn->socket = -1;
317 return ERROR_INTERNET_CANNOT_CONNECT;
319 if (!getsockopt(netconn->socket, SOL_SOCKET, SO_ERROR, (void *)&res, &len) && !res)
320 result = 0;
323 if(result == -1)
325 closesocket(netconn->socket);
326 netconn->socket = -1;
329 if(result == -1)
330 return ERROR_INTERNET_CANNOT_CONNECT;
332 flag = 1;
333 result = setsockopt(netconn->socket, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
334 if(result < 0)
335 WARN("setsockopt(TCP_NODELAY) failed\n");
337 return ERROR_SUCCESS;
340 DWORD create_netconn(server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
342 netconn_t *netconn;
343 int result;
345 netconn = calloc(1, sizeof(*netconn));
346 if(!netconn)
347 return ERROR_OUTOFMEMORY;
349 netconn->socket = -1;
350 netconn->security_flags = security_flags | server->security_flags;
351 netconn->mask_errors = mask_errors;
352 list_init(&netconn->pool_entry);
353 SecInvalidateHandle(&netconn->ssl_ctx);
355 result = create_netconn_socket(server, netconn, timeout);
356 if (result != ERROR_SUCCESS) {
357 free(netconn);
358 return result;
361 server_addref(server);
362 netconn->server = server;
363 *ret = netconn;
364 return result;
367 BOOL is_valid_netconn(netconn_t *netconn)
369 return netconn && netconn->socket != -1;
372 void close_netconn(netconn_t *netconn)
374 closesocket(netconn->socket);
375 netconn->socket = -1;
378 void free_netconn(netconn_t *netconn)
380 server_release(netconn->server);
382 if (netconn->secure) {
383 free(netconn->peek_msg_mem);
384 netconn->peek_msg_mem = NULL;
385 netconn->peek_msg = NULL;
386 netconn->peek_len = 0;
387 free(netconn->ssl_buf);
388 netconn->ssl_buf = NULL;
389 free(netconn->extra_buf);
390 netconn->extra_buf = NULL;
391 netconn->extra_len = 0;
393 if (SecIsValidHandle(&netconn->ssl_ctx))
394 DeleteSecurityContext(&netconn->ssl_ctx);
396 close_netconn(netconn);
397 free(netconn);
400 void NETCON_unload(void)
402 if(cred_handle_initialized)
403 FreeCredentialsHandle(&cred_handle);
404 if(have_compat_cred_handle)
405 FreeCredentialsHandle(&compat_cred_handle);
406 DeleteCriticalSection(&init_sechandle_cs);
407 if(winsock_loaded)
408 WSACleanup();
411 int sock_send(int fd, const void *msg, size_t len, int flags)
413 int ret;
416 ret = send(fd, msg, len, flags);
418 while(ret == -1 && WSAGetLastError() == WSAEINTR);
419 return ret;
422 int sock_recv(int fd, void *msg, size_t len, int flags)
424 int ret;
427 ret = recv(fd, msg, len, flags);
429 while(ret == -1 && WSAGetLastError() == WSAEINTR);
430 return ret;
433 static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode)
435 SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}};
436 SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs};
437 SecHandle *cred = &cred_handle;
438 BYTE *read_buf;
439 SIZE_T read_buf_size = 2048;
440 ULONG attrs = 0;
441 CtxtHandle ctx;
442 SSIZE_T size;
443 int bits;
444 const CERT_CONTEXT *cert;
445 SECURITY_STATUS status;
446 DWORD res = ERROR_SUCCESS;
448 const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY
449 |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION;
451 if(!ensure_cred_handle())
452 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
454 if(compat_mode) {
455 if(!have_compat_cred_handle)
456 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
457 cred = &compat_cred_handle;
460 read_buf = malloc(read_buf_size);
461 if(!read_buf)
462 return ERROR_OUTOFMEMORY;
464 status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0,
465 &ctx, &out_desc, &attrs, NULL);
467 assert(status != SEC_E_OK);
469 set_socket_blocking(connection, TRUE);
471 while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) {
472 if(out_buf.cbBuffer) {
473 assert(status == SEC_I_CONTINUE_NEEDED);
475 TRACE("sending %lu bytes\n", out_buf.cbBuffer);
477 size = sock_send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0);
478 if(size != out_buf.cbBuffer) {
479 ERR("send failed\n");
480 status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
481 break;
484 FreeContextBuffer(out_buf.pvBuffer);
485 out_buf.pvBuffer = NULL;
486 out_buf.cbBuffer = 0;
489 if(status == SEC_I_CONTINUE_NEEDED) {
490 assert(in_bufs[1].cbBuffer < read_buf_size);
492 memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer);
493 in_bufs[0].cbBuffer = in_bufs[1].cbBuffer;
496 assert(in_bufs[0].BufferType == SECBUFFER_TOKEN);
497 in_bufs[1].BufferType = SECBUFFER_EMPTY;
498 in_bufs[1].cbBuffer = 0;
499 in_bufs[1].pvBuffer = NULL;
501 if(in_bufs[0].cbBuffer + 1024 > read_buf_size) {
502 BYTE *new_read_buf;
504 new_read_buf = realloc(read_buf, read_buf_size + 1024);
505 if(!new_read_buf) {
506 status = E_OUTOFMEMORY;
507 break;
510 in_bufs[0].pvBuffer = read_buf = new_read_buf;
511 read_buf_size += 1024;
514 size = sock_recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0);
515 if(size < 1) {
516 WARN("recv error\n");
517 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
518 break;
521 TRACE("recv %Iu bytes\n", size);
523 in_bufs[0].cbBuffer += size;
524 in_bufs[0].pvBuffer = read_buf;
525 status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc,
526 0, NULL, &out_desc, &attrs, NULL);
527 TRACE("InitializeSecurityContext ret %08lx\n", status);
529 if(status == SEC_E_OK) {
530 if(SecIsValidHandle(&connection->ssl_ctx))
531 DeleteSecurityContext(&connection->ssl_ctx);
532 connection->ssl_ctx = ctx;
534 if(in_bufs[1].BufferType == SECBUFFER_EXTRA)
535 FIXME("SECBUFFER_EXTRA not supported\n");
537 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes);
538 if(status != SEC_E_OK) {
539 WARN("Could not get sizes\n");
540 break;
543 status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert);
544 if(status == SEC_E_OK) {
545 res = netconn_verify_cert(connection, cert, cert->hCertStore);
546 CertFreeCertificateContext(cert);
547 if(res != ERROR_SUCCESS) {
548 WARN("cert verify failed: %lu\n", res);
549 break;
551 }else {
552 WARN("Could not get cert\n");
553 break;
556 connection->ssl_buf = malloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage
557 + connection->ssl_sizes.cbTrailer);
558 if(!connection->ssl_buf) {
559 res = GetLastError();
560 break;
565 free(read_buf);
567 if(status != SEC_E_OK || res != ERROR_SUCCESS) {
568 WARN("Failed to establish SSL connection: %08lx (%lu)\n", status, res);
569 free(connection->ssl_buf);
570 connection->ssl_buf = NULL;
571 return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
574 TRACE("established SSL connection\n");
575 connection->secure = TRUE;
576 connection->security_flags |= SECURITY_FLAG_SECURE;
578 bits = NETCON_GetCipherStrength(connection);
579 if (bits >= 128)
580 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
581 else if (bits >= 56)
582 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
583 else
584 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
586 if(connection->mask_errors)
587 connection->server->security_flags = connection->security_flags;
588 return ERROR_SUCCESS;
591 /******************************************************************************
592 * NETCON_secure_connect
593 * Initiates a secure connection over an existing plaintext connection.
595 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
597 DWORD res;
599 /* can't connect if we are already connected */
600 if(connection->secure) {
601 ERR("already connected\n");
602 return ERROR_INTERNET_CANNOT_CONNECT;
605 if(server != connection->server) {
606 server_release(connection->server);
607 server_addref(server);
608 connection->server = server;
611 /* connect with given TLS options */
612 res = netcon_secure_connect_setup(connection, FALSE);
613 if (res == ERROR_SUCCESS)
614 return res;
616 /* FIXME: when got version alert and FIN from server */
617 /* fallback to connect without TLSv1.1/TLSv1.2 */
618 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR && have_compat_cred_handle)
620 closesocket(connection->socket);
621 res = create_netconn_socket(connection->server, connection, 500);
622 if (res != ERROR_SUCCESS)
623 return res;
624 res = netcon_secure_connect_setup(connection, TRUE);
626 return res;
629 static BOOL send_ssl_chunk(netconn_t *conn, const void *msg, size_t size)
631 SecBuffer bufs[4] = {
632 {conn->ssl_sizes.cbHeader, SECBUFFER_STREAM_HEADER, conn->ssl_buf},
633 {size, SECBUFFER_DATA, conn->ssl_buf+conn->ssl_sizes.cbHeader},
634 {conn->ssl_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, conn->ssl_buf+conn->ssl_sizes.cbHeader+size},
635 {0, SECBUFFER_EMPTY, NULL}
637 SecBufferDesc buf_desc = {SECBUFFER_VERSION, ARRAY_SIZE(bufs), bufs};
638 SECURITY_STATUS res;
640 memcpy(bufs[1].pvBuffer, msg, size);
641 res = EncryptMessage(&conn->ssl_ctx, 0, &buf_desc, 0);
642 if(res != SEC_E_OK) {
643 WARN("EncryptMessage failed\n");
644 return FALSE;
647 if(sock_send(conn->socket, conn->ssl_buf, bufs[0].cbBuffer+bufs[1].cbBuffer+bufs[2].cbBuffer, 0) < 1) {
648 WARN("send failed\n");
649 return FALSE;
652 return TRUE;
655 /******************************************************************************
656 * NETCON_send
657 * Basically calls 'send()' unless we should use SSL
658 * number of chars send is put in *sent
660 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
661 int *sent /* out */)
663 /* send is always blocking. */
664 set_socket_blocking(connection, TRUE);
666 if(!connection->secure)
668 *sent = sock_send(connection->socket, msg, len, flags);
669 return *sent == -1 ? WSAGetLastError() : ERROR_SUCCESS;
671 else
673 const BYTE *ptr = msg;
674 size_t chunk_size;
676 *sent = 0;
678 while(len) {
679 chunk_size = min(len, connection->ssl_sizes.cbMaximumMessage);
680 if(!send_ssl_chunk(connection, ptr, chunk_size))
681 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
683 *sent += chunk_size;
684 ptr += chunk_size;
685 len -= chunk_size;
688 return ERROR_SUCCESS;
692 static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, BOOL blocking, SIZE_T *ret_size, BOOL *eof)
694 const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer;
695 SecBuffer bufs[4];
696 SecBufferDesc buf_desc = {SECBUFFER_VERSION, ARRAY_SIZE(bufs), bufs};
697 SSIZE_T size, buf_len = 0;
698 int i;
699 SECURITY_STATUS res;
701 assert(conn->extra_len < ssl_buf_size);
703 if(conn->extra_len) {
704 memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len);
705 buf_len = conn->extra_len;
706 conn->extra_len = 0;
707 free(conn->extra_buf);
708 conn->extra_buf = NULL;
711 set_socket_blocking(conn, blocking && !buf_len);
712 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
713 if(size < 0) {
714 if(!buf_len) {
715 if(WSAGetLastError() == WSAEWOULDBLOCK) {
716 TRACE("would block\n");
717 return WSAEWOULDBLOCK;
719 WARN("recv failed\n");
720 return ERROR_INTERNET_CONNECTION_ABORTED;
722 }else {
723 buf_len += size;
726 if(!buf_len) {
727 TRACE("EOF\n");
728 *eof = TRUE;
729 *ret_size = 0;
730 return ERROR_SUCCESS;
733 *eof = FALSE;
735 do {
736 memset(bufs, 0, sizeof(bufs));
737 bufs[0].BufferType = SECBUFFER_DATA;
738 bufs[0].cbBuffer = buf_len;
739 bufs[0].pvBuffer = conn->ssl_buf;
741 res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL);
742 switch(res) {
743 case SEC_E_OK:
744 break;
745 case SEC_I_CONTEXT_EXPIRED:
746 TRACE("context expired\n");
747 *eof = TRUE;
748 return ERROR_SUCCESS;
749 case SEC_E_INCOMPLETE_MESSAGE:
750 assert(buf_len < ssl_buf_size);
752 set_socket_blocking(conn, blocking);
753 size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0);
754 if(size < 1) {
755 if(size < 0 && WSAGetLastError() == WSAEWOULDBLOCK) {
756 TRACE("would block\n");
758 /* FIXME: Optimize extra_buf usage. */
759 conn->extra_buf = malloc(buf_len);
760 if(!conn->extra_buf)
761 return ERROR_NOT_ENOUGH_MEMORY;
763 conn->extra_len = buf_len;
764 memcpy(conn->extra_buf, conn->ssl_buf, conn->extra_len);
765 return WSAEWOULDBLOCK;
768 return ERROR_INTERNET_CONNECTION_ABORTED;
771 buf_len += size;
772 continue;
773 default:
774 WARN("failed: %08lx\n", res);
775 return ERROR_INTERNET_CONNECTION_ABORTED;
777 } while(res != SEC_E_OK);
779 for(i = 0; i < ARRAY_SIZE(bufs); i++) {
780 if(bufs[i].BufferType == SECBUFFER_DATA) {
781 size = min(buf_size, bufs[i].cbBuffer);
782 memcpy(buf, bufs[i].pvBuffer, size);
783 if(size < bufs[i].cbBuffer) {
784 assert(!conn->peek_len);
785 conn->peek_msg_mem = conn->peek_msg = malloc(bufs[i].cbBuffer - size);
786 if(!conn->peek_msg)
787 return ERROR_NOT_ENOUGH_MEMORY;
788 conn->peek_len = bufs[i].cbBuffer-size;
789 memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len);
792 *ret_size = size;
796 for(i = 0; i < ARRAY_SIZE(bufs); i++) {
797 if(bufs[i].BufferType == SECBUFFER_EXTRA) {
798 conn->extra_buf = malloc(bufs[i].cbBuffer);
799 if(!conn->extra_buf)
800 return ERROR_NOT_ENOUGH_MEMORY;
802 conn->extra_len = bufs[i].cbBuffer;
803 memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len);
807 return ERROR_SUCCESS;
810 /******************************************************************************
811 * NETCON_recv
812 * Basically calls 'recv()' unless we should use SSL
813 * number of chars received is put in *recvd
815 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, BOOL blocking, int *recvd)
817 *recvd = 0;
818 if (!len)
819 return ERROR_SUCCESS;
821 if (!connection->secure)
823 set_socket_blocking(connection, blocking);
824 *recvd = sock_recv(connection->socket, buf, len, 0);
825 return *recvd == -1 ? WSAGetLastError() : ERROR_SUCCESS;
827 else
829 SIZE_T size = 0;
830 BOOL eof;
831 DWORD res;
833 if(connection->peek_msg) {
834 size = min(len, connection->peek_len);
835 memcpy(buf, connection->peek_msg, size);
836 connection->peek_len -= size;
837 connection->peek_msg += size;
839 if(!connection->peek_len) {
840 free(connection->peek_msg_mem);
841 connection->peek_msg_mem = connection->peek_msg = NULL;
844 *recvd = size;
845 return ERROR_SUCCESS;
848 do {
849 res = read_ssl_chunk(connection, (BYTE*)buf, len, blocking, &size, &eof);
850 if(res != ERROR_SUCCESS) {
851 if(res == WSAEWOULDBLOCK) {
852 if(size)
853 res = ERROR_SUCCESS;
854 }else {
855 WARN("read_ssl_chunk failed\n");
857 break;
859 }while(!size && !eof);
861 TRACE("received %Id bytes\n", size);
862 *recvd = size;
863 return res;
867 BOOL NETCON_is_alive(netconn_t *netconn)
869 int len;
870 char b;
872 set_socket_blocking(netconn, FALSE);
873 len = sock_recv(netconn->socket, &b, 1, MSG_PEEK);
875 return len == 1 || (len == -1 && WSAGetLastError() == WSAEWOULDBLOCK);
878 LPCVOID NETCON_GetCert(netconn_t *connection)
880 const CERT_CONTEXT *ret;
881 SECURITY_STATUS res;
883 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&ret);
884 return res == SEC_E_OK ? ret : NULL;
887 int NETCON_GetCipherStrength(netconn_t *connection)
889 SecPkgContext_ConnectionInfo conn_info;
890 SECURITY_STATUS res;
892 if (!connection->secure)
893 return 0;
895 res = QueryContextAttributesW(&connection->ssl_ctx, SECPKG_ATTR_CONNECTION_INFO, (void*)&conn_info);
896 if(res != SEC_E_OK)
897 WARN("QueryContextAttributesW failed: %08lx\n", res);
898 return res == SEC_E_OK ? conn_info.dwCipherStrength : 0;
901 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
903 int result;
905 result = setsockopt(connection->socket, SOL_SOCKET,
906 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&value,
907 sizeof(value));
908 if (result == -1)
910 WARN("setsockopt failed\n");
911 return WSAGetLastError();
913 return ERROR_SUCCESS;