2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
4 * Copyright 2002 TransGaming Technologies Inc.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "wine/port.h"
26 #define NONAMELESSUNION
28 #if defined(__MINGW32__) || defined (_MSC_VER)
32 #include <sys/types.h>
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
61 #ifdef HAVE_NETINET_TCP_H
62 # include <netinet/tcp.h>
64 #ifdef HAVE_OPENSSL_SSL_H
65 # include <openssl/ssl.h>
66 # include <openssl/opensslv.h>
78 #include "wine/library.h"
84 #include "wine/debug.h"
87 /* To avoid conflicts with the Unix socket headers. we only need it for
88 * the error codes anyway. */
92 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
98 * This should use winsock - To use winsock the functions will have to change a bit
99 * as they are designed for unix sockets.
100 * SSL stuff should use crypt32.dll
105 #include <openssl/err.h>
107 static void *OpenSSL_ssl_handle;
108 static void *OpenSSL_crypto_handle;
110 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
111 static const SSL_METHOD *meth;
113 static SSL_METHOD *meth;
116 static int error_idx;
119 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
121 /* OpenSSL functions that we use */
122 MAKE_FUNCPTR(SSL_library_init);
123 MAKE_FUNCPTR(SSL_load_error_strings);
124 MAKE_FUNCPTR(SSLv23_method);
125 MAKE_FUNCPTR(SSL_CTX_free);
126 MAKE_FUNCPTR(SSL_CTX_new);
127 MAKE_FUNCPTR(SSL_CTX_ctrl);
128 MAKE_FUNCPTR(SSL_new);
129 MAKE_FUNCPTR(SSL_free);
130 MAKE_FUNCPTR(SSL_ctrl);
131 MAKE_FUNCPTR(SSL_set_fd);
132 MAKE_FUNCPTR(SSL_connect);
133 MAKE_FUNCPTR(SSL_shutdown);
134 MAKE_FUNCPTR(SSL_write);
135 MAKE_FUNCPTR(SSL_read);
136 MAKE_FUNCPTR(SSL_pending);
137 MAKE_FUNCPTR(SSL_get_error);
138 MAKE_FUNCPTR(SSL_get_ex_new_index);
139 MAKE_FUNCPTR(SSL_get_ex_data);
140 MAKE_FUNCPTR(SSL_set_ex_data);
141 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
142 MAKE_FUNCPTR(SSL_get_peer_certificate);
143 MAKE_FUNCPTR(SSL_CTX_get_timeout);
144 MAKE_FUNCPTR(SSL_CTX_set_timeout);
145 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
146 MAKE_FUNCPTR(SSL_CTX_set_verify);
147 MAKE_FUNCPTR(SSL_get_current_cipher);
148 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
150 /* OpenSSL's libcrypto functions that we use */
151 MAKE_FUNCPTR(BIO_new_fp);
152 MAKE_FUNCPTR(CRYPTO_num_locks);
153 MAKE_FUNCPTR(CRYPTO_set_id_callback);
154 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
155 MAKE_FUNCPTR(ERR_free_strings);
156 MAKE_FUNCPTR(ERR_get_error);
157 MAKE_FUNCPTR(ERR_error_string);
158 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
159 MAKE_FUNCPTR(X509_STORE_CTX_get_chain);
160 MAKE_FUNCPTR(i2d_X509);
161 MAKE_FUNCPTR(sk_num);
162 MAKE_FUNCPTR(sk_value);
165 static CRITICAL_SECTION *ssl_locks;
166 static unsigned int num_ssl_locks;
168 static unsigned long ssl_thread_id(void)
170 return GetCurrentThreadId();
173 static void ssl_lock_callback(int mode, int type, const char *file, int line)
175 if (mode & CRYPTO_LOCK)
176 EnterCriticalSection(&ssl_locks[type]);
178 LeaveCriticalSection(&ssl_locks[type]);
181 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
183 unsigned char* buffer,*p;
185 BOOL malloced = FALSE;
189 len = pi2d_X509(cert,&p);
191 * SSL 0.9.7 and above malloc the buffer if it is null.
192 * however earlier version do not and so we would need to alloc the buffer.
194 * see the i2d_X509 man page for more details.
198 buffer = heap_alloc(len);
200 len = pi2d_X509(cert,&p);
208 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
218 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
221 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
222 PCCERT_CHAIN_CONTEXT chain;
223 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
224 char *server_auth[] = { oid_server_auth };
225 DWORD err = ERROR_SUCCESS, errors;
227 static const DWORD supportedErrors =
228 CERT_TRUST_IS_NOT_TIME_VALID |
229 CERT_TRUST_IS_UNTRUSTED_ROOT |
230 CERT_TRUST_IS_PARTIAL_CHAIN |
231 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
233 TRACE("verifying %s\n", debugstr_w(conn->server->name));
235 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
236 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
237 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, 0, NULL, &chain))) {
239 return GetLastError();
242 errors = chain->TrustStatus.dwErrorStatus;
245 /* This seems strange, but that's what tests show */
246 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
247 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
248 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
249 if(conn->mask_errors)
250 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
251 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
255 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
256 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
257 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
258 errors &= supportedErrors;
259 if(!conn->mask_errors)
261 WARN("unknown error flags\n");
264 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
265 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
266 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
267 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
268 if(!conn->mask_errors)
270 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
272 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
275 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
276 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
277 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
278 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
279 if(!conn->mask_errors)
281 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
283 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
286 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
287 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
288 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
289 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
290 if(!conn->mask_errors)
292 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
294 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
297 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
298 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
299 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
300 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
301 if(!conn->mask_errors)
303 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
305 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
308 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
309 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
314 if(!err || conn->mask_errors) {
315 CERT_CHAIN_POLICY_PARA policyPara;
316 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
317 CERT_CHAIN_POLICY_STATUS policyStatus;
318 CERT_CHAIN_CONTEXT chainCopy;
320 /* Clear chain->TrustStatus.dwErrorStatus so
321 * CertVerifyCertificateChainPolicy will verify additional checks
322 * rather than stopping with an existing, ignored error.
324 memcpy(&chainCopy, chain, sizeof(chainCopy));
325 chainCopy.TrustStatus.dwErrorStatus = 0;
326 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
327 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
328 sslExtraPolicyPara.pwszServerName = conn->server->name;
329 sslExtraPolicyPara.fdwChecks = conn->security_flags;
330 policyPara.cbSize = sizeof(policyPara);
331 policyPara.dwFlags = 0;
332 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
333 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
334 &chainCopy, &policyPara, &policyStatus);
335 /* Any error in the policy status indicates that the
336 * policy couldn't be verified.
339 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
340 WARN("CERT_E_CN_NO_MATCH\n");
341 if(conn->mask_errors)
342 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
343 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
344 }else if(policyStatus.dwError) {
345 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
346 if(conn->mask_errors)
347 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
348 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
351 err = GetLastError();
356 WARN("failed %u\n", err);
357 CertFreeCertificateChain(chain);
358 if(conn->server->cert_chain) {
359 CertFreeCertificateChain(conn->server->cert_chain);
360 conn->server->cert_chain = NULL;
362 if(conn->mask_errors)
363 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
367 /* FIXME: Reuse cached chain */
368 if(conn->server->cert_chain)
369 CertFreeCertificateChain(chain);
371 conn->server->cert_chain = chain;
372 return ERROR_SUCCESS;
375 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
379 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
380 CERT_STORE_CREATE_NEW_FLAG, NULL);
383 ssl = pX509_STORE_CTX_get_ex_data(ctx,
384 pSSL_get_ex_data_X509_STORE_CTX_idx());
385 conn = pSSL_get_ex_data(ssl, conn_idx);
390 PCCERT_CONTEXT endCert = NULL;
391 struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
394 for (i = 0; ret && i < psk_num(chain); i++)
396 PCCERT_CONTEXT context;
398 cert = (X509 *)psk_value(chain, i);
399 if ((context = X509_to_cert_context(cert)))
401 ret = CertAddCertificateContextToStore(store, context,
402 CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
403 CertFreeCertificateContext(context);
406 if (!endCert) ret = FALSE;
409 DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
413 pSSL_set_ex_data(ssl, error_idx, (void *)err);
417 CertFreeCertificateContext(endCert);
418 CertCloseStore(store, 0);
423 static long get_tls_option(void) {
424 long tls_option = SSL_OP_NO_SSLv2; /* disable SSLv2 for security reason, secur32/Schannel(GnuTLS) don't support it */
425 #ifdef SSL_OP_NO_TLSv1_2
426 DWORD type, val, size;
427 HKEY hkey,tls12_client,tls11_client;
429 const WCHAR Schannel_Prot[] = { /* SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCANNEL\\Protocols */
430 'S','Y','S','T','E','M','\\',
431 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
432 'C','o','n','t','r','o','l','\\',
433 'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
434 'S','C','H','A','N','N','E','L','\\',
435 'P','r','o','t','o','c','o','l','s',0 };
436 const WCHAR TLS12_Client[] = {'T','L','S',' ','1','.','2','\\','C','l','i','e','n','t',0};
437 const WCHAR TLS11_Client[] = {'T','L','S',' ','1','.','1','\\','C','l','i','e','n','t',0};
438 const WCHAR DisabledByDefault[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
440 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
443 if (res != ERROR_SUCCESS) { /* enabled TLSv1.1/1.2 when no registry entry */
446 if (RegOpenKeyExW(hkey, TLS12_Client, 0, KEY_READ, &tls12_client) == ERROR_SUCCESS) {
447 size = sizeof(DWORD);
448 if (RegQueryValueExW(tls12_client, DisabledByDefault, NULL, &type, (LPBYTE) &val, &size) == ERROR_SUCCESS
449 && type == REG_DWORD) {
450 tls_option |= val?SSL_OP_NO_TLSv1_2:0;
452 RegCloseKey(tls12_client);
454 if (RegOpenKeyExW(hkey, TLS11_Client, 0, KEY_READ, &tls11_client) == ERROR_SUCCESS) {
455 size = sizeof(DWORD);
456 if (RegQueryValueExW(tls11_client, DisabledByDefault, NULL, &type, (LPBYTE) &val, &size) == ERROR_SUCCESS
457 && type == REG_DWORD) {
458 tls_option |= val?SSL_OP_NO_TLSv1_1:0;
460 RegCloseKey(tls11_client);
466 #endif /* SONAME_LIBSSL */
468 static CRITICAL_SECTION init_ssl_cs;
469 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
472 { &init_ssl_cs_debug.ProcessLocksList,
473 &init_ssl_cs_debug.ProcessLocksList },
474 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
476 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
478 static DWORD init_openssl(void)
480 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
483 if(OpenSSL_ssl_handle)
484 return ERROR_SUCCESS;
486 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
487 if(!OpenSSL_ssl_handle) {
488 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
489 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
492 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
493 if(!OpenSSL_crypto_handle) {
494 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
495 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
498 /* mmm nice ugly macroness */
500 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
502 ERR("failed to load symbol %s\n", #x); \
503 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
506 DYNSSL(SSL_library_init);
507 DYNSSL(SSL_load_error_strings);
508 DYNSSL(SSLv23_method);
509 DYNSSL(SSL_CTX_free);
511 DYNSSL(SSL_CTX_ctrl);
517 DYNSSL(SSL_shutdown);
521 DYNSSL(SSL_get_error);
522 DYNSSL(SSL_get_ex_new_index);
523 DYNSSL(SSL_get_ex_data);
524 DYNSSL(SSL_set_ex_data);
525 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
526 DYNSSL(SSL_get_peer_certificate);
527 DYNSSL(SSL_CTX_get_timeout);
528 DYNSSL(SSL_CTX_set_timeout);
529 DYNSSL(SSL_CTX_set_default_verify_paths);
530 DYNSSL(SSL_CTX_set_verify);
531 DYNSSL(SSL_get_current_cipher);
532 DYNSSL(SSL_CIPHER_get_bits);
535 #define DYNCRYPTO(x) \
536 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
538 ERR("failed to load symbol %s\n", #x); \
539 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
542 DYNCRYPTO(BIO_new_fp);
543 DYNCRYPTO(CRYPTO_num_locks);
544 DYNCRYPTO(CRYPTO_set_id_callback);
545 DYNCRYPTO(CRYPTO_set_locking_callback);
546 DYNCRYPTO(ERR_free_strings);
547 DYNCRYPTO(ERR_get_error);
548 DYNCRYPTO(ERR_error_string);
549 DYNCRYPTO(X509_STORE_CTX_get_ex_data);
550 DYNCRYPTO(X509_STORE_CTX_get_chain);
556 #define pSSL_CTX_set_options(ctx,op) \
557 pSSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
558 #define pSSL_set_options(ssl,op) \
559 pSSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
562 pSSL_load_error_strings();
563 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
565 meth = pSSLv23_method();
566 ctx = pSSL_CTX_new(meth);
567 pSSL_CTX_set_options(ctx, get_tls_option());
568 if(!pSSL_CTX_set_default_verify_paths(ctx)) {
569 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
570 pERR_error_string(pERR_get_error(), 0));
571 return ERROR_OUTOFMEMORY;
574 error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
575 if(error_idx == -1) {
576 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
577 return ERROR_OUTOFMEMORY;
580 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
582 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
583 return ERROR_OUTOFMEMORY;
586 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
588 pCRYPTO_set_id_callback(ssl_thread_id);
589 num_ssl_locks = pCRYPTO_num_locks();
590 ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
592 return ERROR_OUTOFMEMORY;
594 for(i = 0; i < num_ssl_locks; i++)
596 InitializeCriticalSection(&ssl_locks[i]);
597 ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
599 pCRYPTO_set_locking_callback(ssl_lock_callback);
601 return ERROR_SUCCESS;
603 FIXME("can't use SSL, not compiled in.\n");
604 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
608 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
612 assert(server->addr_len);
613 result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
616 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
617 result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
620 if (sock_get_error(errno) == WSAEINPROGRESS) {
624 pfd.fd = netconn->socketFD;
625 pfd.events = POLLOUT;
626 res = poll(&pfd, 1, timeout);
629 closesocket(netconn->socketFD);
630 return ERROR_INTERNET_CANNOT_CONNECT;
635 socklen_t len = sizeof(err);
636 if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
642 closesocket(netconn->socketFD);
645 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
649 return ERROR_INTERNET_CANNOT_CONNECT;
653 result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
655 WARN("setsockopt(TCP_NODELAY) failed\n");
658 return ERROR_SUCCESS;
661 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
669 TRACE("using SSL connection\n");
671 EnterCriticalSection(&init_ssl_cs);
672 res = init_openssl();
673 LeaveCriticalSection(&init_ssl_cs);
674 if(res != ERROR_SUCCESS)
678 netconn = heap_alloc_zero(sizeof(*netconn));
680 return ERROR_OUTOFMEMORY;
682 netconn->socketFD = -1;
683 netconn->security_flags = security_flags | server->security_flags;
684 netconn->mask_errors = mask_errors;
685 list_init(&netconn->pool_entry);
687 result = create_netconn_socket(server, netconn, timeout);
688 if (result != ERROR_SUCCESS) {
693 server_addref(server);
694 netconn->server = server;
699 void free_netconn(netconn_t *netconn)
701 server_release(netconn->server);
704 if (netconn->ssl_s) {
705 pSSL_shutdown(netconn->ssl_s);
706 pSSL_free(netconn->ssl_s);
710 closesocket(netconn->socketFD);
714 void NETCON_unload(void)
716 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
717 if (OpenSSL_crypto_handle)
720 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
722 if (OpenSSL_ssl_handle)
726 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
731 for (i = 0; i < num_ssl_locks; i++)
733 ssl_locks[i].DebugInfo->Spare[0] = 0;
734 DeleteCriticalSection(&ssl_locks[i]);
736 heap_free(ssl_locks);
741 /* translate a unix error code into a winsock one */
742 int sock_get_error( int err )
744 #if !defined(__MINGW32__) && !defined (_MSC_VER)
747 case EINTR: return WSAEINTR;
748 case EBADF: return WSAEBADF;
750 case EACCES: return WSAEACCES;
751 case EFAULT: return WSAEFAULT;
752 case EINVAL: return WSAEINVAL;
753 case EMFILE: return WSAEMFILE;
754 case EWOULDBLOCK: return WSAEWOULDBLOCK;
755 case EINPROGRESS: return WSAEINPROGRESS;
756 case EALREADY: return WSAEALREADY;
757 case ENOTSOCK: return WSAENOTSOCK;
758 case EDESTADDRREQ: return WSAEDESTADDRREQ;
759 case EMSGSIZE: return WSAEMSGSIZE;
760 case EPROTOTYPE: return WSAEPROTOTYPE;
761 case ENOPROTOOPT: return WSAENOPROTOOPT;
762 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
763 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
764 case EOPNOTSUPP: return WSAEOPNOTSUPP;
765 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
766 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
767 case EADDRINUSE: return WSAEADDRINUSE;
768 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
769 case ENETDOWN: return WSAENETDOWN;
770 case ENETUNREACH: return WSAENETUNREACH;
771 case ENETRESET: return WSAENETRESET;
772 case ECONNABORTED: return WSAECONNABORTED;
774 case ECONNRESET: return WSAECONNRESET;
775 case ENOBUFS: return WSAENOBUFS;
776 case EISCONN: return WSAEISCONN;
777 case ENOTCONN: return WSAENOTCONN;
778 case ESHUTDOWN: return WSAESHUTDOWN;
779 case ETOOMANYREFS: return WSAETOOMANYREFS;
780 case ETIMEDOUT: return WSAETIMEDOUT;
781 case ECONNREFUSED: return WSAECONNREFUSED;
782 case ELOOP: return WSAELOOP;
783 case ENAMETOOLONG: return WSAENAMETOOLONG;
784 case EHOSTDOWN: return WSAEHOSTDOWN;
785 case EHOSTUNREACH: return WSAEHOSTUNREACH;
786 case ENOTEMPTY: return WSAENOTEMPTY;
788 case EPROCLIM: return WSAEPROCLIM;
791 case EUSERS: return WSAEUSERS;
794 case EDQUOT: return WSAEDQUOT;
797 case ESTALE: return WSAESTALE;
800 case EREMOTE: return WSAEREMOTE;
802 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
809 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
815 ssl_s = pSSL_new(ctx);
818 ERR("SSL_new failed: %s\n",
819 pERR_error_string(pERR_get_error(), 0));
820 return ERROR_OUTOFMEMORY;
823 pSSL_set_options(ssl_s, tls_option);
824 if (!pSSL_set_fd(ssl_s, connection->socketFD))
826 ERR("SSL_set_fd failed: %s\n",
827 pERR_error_string(pERR_get_error(), 0));
828 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
832 if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
834 ERR("SSL_set_ex_data failed: %s\n",
835 pERR_error_string(pERR_get_error(), 0));
836 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
839 if (pSSL_connect(ssl_s) <= 0)
841 res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
843 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
844 ERR("SSL_connect failed: %d\n", res);
848 connection->ssl_s = ssl_s;
850 bits = NETCON_GetCipherStrength(connection);
852 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
854 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
856 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
857 connection->security_flags |= SECURITY_FLAG_SECURE;
859 if(connection->mask_errors)
860 connection->server->security_flags = connection->security_flags;
861 return ERROR_SUCCESS;
866 pSSL_shutdown(ssl_s);
873 /******************************************************************************
874 * NETCON_secure_connect
875 * Initiates a secure connection over an existing plaintext connection.
877 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
879 DWORD res = ERROR_NOT_SUPPORTED;
881 /* can't connect if we are already connected */
882 if (connection->ssl_s)
884 ERR("already connected\n");
885 return ERROR_INTERNET_CANNOT_CONNECT;
888 connection->useSSL = TRUE;
889 if(server != connection->server) {
890 server_release(connection->server);
891 server_addref(server);
892 connection->server = server;
895 /* connect with given TLS options */
896 res = netcon_secure_connect_setup(connection, get_tls_option());
897 if (res == ERROR_SUCCESS)
900 #ifdef SSL_OP_NO_TLSv1_2
901 /* FIXME: when got version alert and FIN from server */
902 /* fallback to connect without TLSv1.1/TLSv1.2 */
903 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
905 closesocket(connection->socketFD);
906 pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
907 res = create_netconn_socket(connection->server, connection, 500);
908 if (res != ERROR_SUCCESS)
910 res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
917 /******************************************************************************
919 * Basically calls 'send()' unless we should use SSL
920 * number of chars send is put in *sent
922 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
925 if (!connection->useSSL)
927 *sent = send(connection->socketFD, msg, len, flags);
929 return sock_get_error(errno);
930 return ERROR_SUCCESS;
935 if(!connection->ssl_s) {
936 FIXME("not connected\n");
937 return ERROR_NOT_SUPPORTED;
940 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
941 *sent = pSSL_write(connection->ssl_s, msg, len);
942 if (*sent < 1 && len)
943 return ERROR_INTERNET_CONNECTION_ABORTED;
944 return ERROR_SUCCESS;
946 return ERROR_NOT_SUPPORTED;
951 /******************************************************************************
953 * Basically calls 'recv()' unless we should use SSL
954 * number of chars received is put in *recvd
956 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
957 int *recvd /* out */)
961 return ERROR_SUCCESS;
962 if (!connection->useSSL)
964 *recvd = recv(connection->socketFD, buf, len, flags);
965 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
970 if(!connection->ssl_s) {
971 FIXME("not connected\n");
972 return ERROR_NOT_SUPPORTED;
974 *recvd = pSSL_read(connection->ssl_s, buf, len);
976 /* Check if EOF was received */
977 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
978 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
979 return ERROR_SUCCESS;
981 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
983 return ERROR_NOT_SUPPORTED;
988 /******************************************************************************
989 * NETCON_query_data_available
990 * Returns the number of bytes of peeked data plus the number of bytes of
991 * queued, but unread data.
993 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
997 if (!connection->useSSL)
1001 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1004 TRACE("%d bytes of queued, but unread data\n", unread);
1005 *available += unread;
1011 #ifdef SONAME_LIBSSL
1012 *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1018 BOOL NETCON_is_alive(netconn_t *netconn)
1024 len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1025 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1026 #elif defined(__MINGW32__) || defined(_MSC_VER)
1032 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1035 len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1038 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1041 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1043 FIXME("not supported on this platform\n");
1048 LPCVOID NETCON_GetCert(netconn_t *connection)
1050 #ifdef SONAME_LIBSSL
1054 if (!connection->ssl_s)
1057 cert = pSSL_get_peer_certificate(connection->ssl_s);
1058 r = X509_to_cert_context(cert);
1065 int NETCON_GetCipherStrength(netconn_t *connection)
1067 #ifdef SONAME_LIBSSL
1068 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1069 const SSL_CIPHER *cipher;
1075 if (!connection->ssl_s)
1077 cipher = pSSL_get_current_cipher(connection->ssl_s);
1080 pSSL_CIPHER_get_bits(cipher, &bits);
1087 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1092 /* value is in milliseconds, convert to struct timeval */
1093 if (value == INFINITE)
1100 tv.tv_sec = value / 1000;
1101 tv.tv_usec = (value % 1000) * 1000;
1103 result = setsockopt(connection->socketFD, SOL_SOCKET,
1104 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1108 WARN("setsockopt failed (%s)\n", strerror(errno));
1109 return sock_get_error(errno);
1111 return ERROR_SUCCESS;