d3dx9/tests: Add basic tests for ID3DXRenderToEnvMap.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blobc944ff3576ba1eb4095c755c52c3a497ef17875f
1 /*
2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
4 * Copyright 2002 TransGaming Technologies Inc.
6 * David Hammerton
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
23 #include "config.h"
24 #include "wine/port.h"
26 #define NONAMELESSUNION
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 #include <ws2tcpip.h>
30 #endif
32 #include <sys/types.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
47 #endif
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
54 #include <time.h>
55 #ifdef HAVE_NETDB_H
56 # include <netdb.h>
57 #endif
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #ifdef HAVE_NETINET_TCP_H
62 # include <netinet/tcp.h>
63 #endif
64 #ifdef HAVE_OPENSSL_SSL_H
65 # include <openssl/ssl.h>
66 # include <openssl/opensslv.h>
67 #undef FAR
68 #undef DSA
69 #endif
71 #include <stdarg.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <stdio.h>
75 #include <errno.h>
76 #include <assert.h>
78 #include "wine/library.h"
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wininet.h"
82 #include "winerror.h"
84 #include "wine/debug.h"
85 #include "internet.h"
87 /* To avoid conflicts with the Unix socket headers. we only need it for
88 * the error codes anyway. */
89 #define USE_WS_PREFIX
90 #include "winsock2.h"
92 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
97 /* FIXME!!!!!!
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
103 #ifdef SONAME_LIBSSL
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;
112 #else
113 static SSL_METHOD *meth;
114 #endif
115 static SSL_CTX *ctx;
116 static int error_idx;
117 static int conn_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_new);
128 MAKE_FUNCPTR(SSL_free);
129 MAKE_FUNCPTR(SSL_set_fd);
130 MAKE_FUNCPTR(SSL_connect);
131 MAKE_FUNCPTR(SSL_shutdown);
132 MAKE_FUNCPTR(SSL_write);
133 MAKE_FUNCPTR(SSL_read);
134 MAKE_FUNCPTR(SSL_pending);
135 MAKE_FUNCPTR(SSL_get_error);
136 MAKE_FUNCPTR(SSL_get_ex_new_index);
137 MAKE_FUNCPTR(SSL_get_ex_data);
138 MAKE_FUNCPTR(SSL_set_ex_data);
139 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
140 MAKE_FUNCPTR(SSL_get_peer_certificate);
141 MAKE_FUNCPTR(SSL_CTX_get_timeout);
142 MAKE_FUNCPTR(SSL_CTX_set_timeout);
143 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
144 MAKE_FUNCPTR(SSL_CTX_set_verify);
145 MAKE_FUNCPTR(SSL_get_current_cipher);
146 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
148 /* OpenSSL's libcrypto functions that we use */
149 MAKE_FUNCPTR(BIO_new_fp);
150 MAKE_FUNCPTR(CRYPTO_num_locks);
151 MAKE_FUNCPTR(CRYPTO_set_id_callback);
152 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
153 MAKE_FUNCPTR(ERR_free_strings);
154 MAKE_FUNCPTR(ERR_get_error);
155 MAKE_FUNCPTR(ERR_error_string);
156 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
157 MAKE_FUNCPTR(X509_STORE_CTX_get_chain);
158 MAKE_FUNCPTR(i2d_X509);
159 MAKE_FUNCPTR(sk_num);
160 MAKE_FUNCPTR(sk_value);
161 #undef MAKE_FUNCPTR
163 static CRITICAL_SECTION *ssl_locks;
164 static unsigned int num_ssl_locks;
166 static unsigned long ssl_thread_id(void)
168 return GetCurrentThreadId();
171 static void ssl_lock_callback(int mode, int type, const char *file, int line)
173 if (mode & CRYPTO_LOCK)
174 EnterCriticalSection(&ssl_locks[type]);
175 else
176 LeaveCriticalSection(&ssl_locks[type]);
179 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
181 unsigned char* buffer,*p;
182 INT len;
183 BOOL malloced = FALSE;
184 PCCERT_CONTEXT ret;
186 p = NULL;
187 len = pi2d_X509(cert,&p);
189 * SSL 0.9.7 and above malloc the buffer if it is null.
190 * however earlier version do not and so we would need to alloc the buffer.
192 * see the i2d_X509 man page for more details.
194 if (!p)
196 buffer = heap_alloc(len);
197 p = buffer;
198 len = pi2d_X509(cert,&p);
200 else
202 buffer = p;
203 malloced = TRUE;
206 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
208 if (malloced)
209 free(buffer);
210 else
211 heap_free(buffer);
213 return ret;
216 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
218 BOOL ret;
219 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
220 PCCERT_CHAIN_CONTEXT chain;
221 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
222 char *server_auth[] = { oid_server_auth };
223 DWORD err = ERROR_SUCCESS, chainFlags = 0, errors;
225 static const DWORD supportedErrors =
226 CERT_TRUST_IS_NOT_TIME_VALID |
227 CERT_TRUST_IS_UNTRUSTED_ROOT |
228 CERT_TRUST_IS_PARTIAL_CHAIN |
229 CERT_TRUST_IS_OFFLINE_REVOCATION |
230 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
231 CERT_TRUST_IS_REVOKED |
232 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
234 TRACE("verifying %s\n", debugstr_w(conn->server->name));
236 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
237 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
238 if (!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
239 chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
241 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, chainFlags, NULL, &chain))) {
242 TRACE("failed\n");
243 return GetLastError();
246 errors = chain->TrustStatus.dwErrorStatus;
248 do {
249 /* This seems strange, but that's what tests show */
250 if(errors & (CERT_TRUST_IS_PARTIAL_CHAIN|CERT_TRUST_IS_OFFLINE_REVOCATION)) {
251 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
252 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
253 if(conn->mask_errors)
254 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
255 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
256 break;
259 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
260 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
261 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
262 errors &= supportedErrors;
263 if(!conn->mask_errors)
264 break;
265 WARN("unknown error flags\n");
268 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
269 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
270 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
271 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
272 if(!conn->mask_errors)
273 break;
274 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
276 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
279 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
280 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
281 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
282 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
283 if(!conn->mask_errors)
284 break;
285 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
287 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
290 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
291 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
292 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
293 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
294 if(!conn->mask_errors)
295 break;
296 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
298 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
301 if(errors & (CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN)) {
302 WARN("CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN\n");
303 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
304 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_NO_REV;
305 if(!conn->mask_errors)
306 break;
307 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
309 errors &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
312 if(errors & CERT_TRUST_IS_REVOKED) {
313 WARN("CERT_TRUST_IS_REVOKED\n");
314 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
315 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_REVOKED;
316 if(!conn->mask_errors)
317 break;
318 WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\n");
320 errors &= ~CERT_TRUST_IS_REVOKED;
323 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
324 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
325 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
326 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
327 if(!conn->mask_errors)
328 break;
329 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
331 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
334 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
335 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
336 err = ERROR_SUCCESS;
338 }while(0);
340 if(!err || conn->mask_errors) {
341 CERT_CHAIN_POLICY_PARA policyPara;
342 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
343 CERT_CHAIN_POLICY_STATUS policyStatus;
344 CERT_CHAIN_CONTEXT chainCopy;
346 /* Clear chain->TrustStatus.dwErrorStatus so
347 * CertVerifyCertificateChainPolicy will verify additional checks
348 * rather than stopping with an existing, ignored error.
350 memcpy(&chainCopy, chain, sizeof(chainCopy));
351 chainCopy.TrustStatus.dwErrorStatus = 0;
352 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
353 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
354 sslExtraPolicyPara.pwszServerName = conn->server->name;
355 sslExtraPolicyPara.fdwChecks = conn->security_flags;
356 policyPara.cbSize = sizeof(policyPara);
357 policyPara.dwFlags = 0;
358 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
359 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
360 &chainCopy, &policyPara, &policyStatus);
361 /* Any error in the policy status indicates that the
362 * policy couldn't be verified.
364 if(ret) {
365 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
366 WARN("CERT_E_CN_NO_MATCH\n");
367 if(conn->mask_errors)
368 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
369 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
370 }else if(policyStatus.dwError) {
371 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
372 if(conn->mask_errors)
373 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
374 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
376 }else {
377 err = GetLastError();
381 if(err) {
382 WARN("failed %u\n", err);
383 CertFreeCertificateChain(chain);
384 if(conn->server->cert_chain) {
385 CertFreeCertificateChain(conn->server->cert_chain);
386 conn->server->cert_chain = NULL;
388 if(conn->mask_errors)
389 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
390 return err;
393 /* FIXME: Reuse cached chain */
394 if(conn->server->cert_chain)
395 CertFreeCertificateChain(chain);
396 else
397 conn->server->cert_chain = chain;
398 return ERROR_SUCCESS;
401 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
403 SSL *ssl;
404 BOOL ret = FALSE;
405 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
406 CERT_STORE_CREATE_NEW_FLAG, NULL);
407 netconn_t *conn;
409 ssl = pX509_STORE_CTX_get_ex_data(ctx,
410 pSSL_get_ex_data_X509_STORE_CTX_idx());
411 conn = pSSL_get_ex_data(ssl, conn_idx);
412 if (store)
414 X509 *cert;
415 int i;
416 PCCERT_CONTEXT endCert = NULL;
417 struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
419 ret = TRUE;
420 for (i = 0; ret && i < psk_num(chain); i++)
422 PCCERT_CONTEXT context;
424 cert = (X509 *)psk_value(chain, i);
425 if ((context = X509_to_cert_context(cert)))
427 ret = CertAddCertificateContextToStore(store, context,
428 CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
429 CertFreeCertificateContext(context);
432 if (!endCert) ret = FALSE;
433 if (ret)
435 DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
437 if (err)
439 pSSL_set_ex_data(ssl, error_idx, (void *)err);
440 ret = FALSE;
443 CertFreeCertificateContext(endCert);
444 CertCloseStore(store, 0);
446 return ret;
449 #endif
451 static CRITICAL_SECTION init_ssl_cs;
452 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
454 0, 0, &init_ssl_cs,
455 { &init_ssl_cs_debug.ProcessLocksList,
456 &init_ssl_cs_debug.ProcessLocksList },
457 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
459 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
461 static DWORD init_openssl(void)
463 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
464 int i;
466 if(OpenSSL_ssl_handle)
467 return ERROR_SUCCESS;
469 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
470 if(!OpenSSL_ssl_handle) {
471 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
472 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
475 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
476 if(!OpenSSL_crypto_handle) {
477 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
478 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
481 /* mmm nice ugly macroness */
482 #define DYNSSL(x) \
483 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
484 if (!p##x) { \
485 ERR("failed to load symbol %s\n", #x); \
486 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
489 DYNSSL(SSL_library_init);
490 DYNSSL(SSL_load_error_strings);
491 DYNSSL(SSLv23_method);
492 DYNSSL(SSL_CTX_free);
493 DYNSSL(SSL_CTX_new);
494 DYNSSL(SSL_new);
495 DYNSSL(SSL_free);
496 DYNSSL(SSL_set_fd);
497 DYNSSL(SSL_connect);
498 DYNSSL(SSL_shutdown);
499 DYNSSL(SSL_write);
500 DYNSSL(SSL_read);
501 DYNSSL(SSL_pending);
502 DYNSSL(SSL_get_error);
503 DYNSSL(SSL_get_ex_new_index);
504 DYNSSL(SSL_get_ex_data);
505 DYNSSL(SSL_set_ex_data);
506 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
507 DYNSSL(SSL_get_peer_certificate);
508 DYNSSL(SSL_CTX_get_timeout);
509 DYNSSL(SSL_CTX_set_timeout);
510 DYNSSL(SSL_CTX_set_default_verify_paths);
511 DYNSSL(SSL_CTX_set_verify);
512 DYNSSL(SSL_get_current_cipher);
513 DYNSSL(SSL_CIPHER_get_bits);
514 #undef DYNSSL
516 #define DYNCRYPTO(x) \
517 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
518 if (!p##x) { \
519 ERR("failed to load symbol %s\n", #x); \
520 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
523 DYNCRYPTO(BIO_new_fp);
524 DYNCRYPTO(CRYPTO_num_locks);
525 DYNCRYPTO(CRYPTO_set_id_callback);
526 DYNCRYPTO(CRYPTO_set_locking_callback);
527 DYNCRYPTO(ERR_free_strings);
528 DYNCRYPTO(ERR_get_error);
529 DYNCRYPTO(ERR_error_string);
530 DYNCRYPTO(X509_STORE_CTX_get_ex_data);
531 DYNCRYPTO(X509_STORE_CTX_get_chain);
532 DYNCRYPTO(i2d_X509);
533 DYNCRYPTO(sk_num);
534 DYNCRYPTO(sk_value);
535 #undef DYNCRYPTO
537 pSSL_library_init();
538 pSSL_load_error_strings();
539 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
541 meth = pSSLv23_method();
542 ctx = pSSL_CTX_new(meth);
543 if(!pSSL_CTX_set_default_verify_paths(ctx)) {
544 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
545 pERR_error_string(pERR_get_error(), 0));
546 return ERROR_OUTOFMEMORY;
549 error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
550 if(error_idx == -1) {
551 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
552 return ERROR_OUTOFMEMORY;
555 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
556 if(conn_idx == -1) {
557 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
558 return ERROR_OUTOFMEMORY;
561 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
563 pCRYPTO_set_id_callback(ssl_thread_id);
564 num_ssl_locks = pCRYPTO_num_locks();
565 ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
566 if(!ssl_locks)
567 return ERROR_OUTOFMEMORY;
569 for(i = 0; i < num_ssl_locks; i++)
571 InitializeCriticalSection(&ssl_locks[i]);
572 ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
574 pCRYPTO_set_locking_callback(ssl_lock_callback);
576 return ERROR_SUCCESS;
577 #else
578 FIXME("can't use SSL, not compiled in.\n");
579 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
580 #endif
583 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
585 netconn_t *netconn;
586 int result, flag;
588 if(useSSL) {
589 DWORD res;
591 TRACE("using SSL connection\n");
593 EnterCriticalSection(&init_ssl_cs);
594 res = init_openssl();
595 LeaveCriticalSection(&init_ssl_cs);
596 if(res != ERROR_SUCCESS)
597 return res;
600 netconn = heap_alloc_zero(sizeof(*netconn));
601 if(!netconn)
602 return ERROR_OUTOFMEMORY;
604 netconn->useSSL = useSSL;
605 netconn->socketFD = -1;
606 netconn->security_flags = security_flags | server->security_flags;
607 netconn->mask_errors = mask_errors;
608 list_init(&netconn->pool_entry);
610 assert(server->addr_len);
611 result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
612 if(result != -1) {
613 flag = 1;
614 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
615 result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
616 if(result == -1)
618 if (sock_get_error(errno) == WSAEINPROGRESS) {
619 struct pollfd pfd;
620 int res;
622 pfd.fd = netconn->socketFD;
623 pfd.events = POLLOUT;
624 res = poll(&pfd, 1, timeout);
625 if (!res)
627 closesocket(netconn->socketFD);
628 heap_free(netconn);
629 return ERROR_INTERNET_CANNOT_CONNECT;
631 else if (res > 0)
633 int err;
634 socklen_t len = sizeof(err);
635 if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
636 result = 0;
640 if(result == -1)
641 closesocket(netconn->socketFD);
642 else {
643 flag = 0;
644 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
647 if(result == -1) {
648 heap_free(netconn);
649 return sock_get_error(errno);
652 #ifdef TCP_NODELAY
653 flag = 1;
654 result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
655 if(result < 0)
656 WARN("setsockopt(TCP_NODELAY) failed\n");
657 #endif
659 server_addref(server);
660 netconn->server = server;
662 *ret = netconn;
663 return ERROR_SUCCESS;
666 void free_netconn(netconn_t *netconn)
668 server_release(netconn->server);
670 #ifdef SONAME_LIBSSL
671 if (netconn->ssl_s) {
672 pSSL_shutdown(netconn->ssl_s);
673 pSSL_free(netconn->ssl_s);
675 #endif
677 closesocket(netconn->socketFD);
678 heap_free(netconn);
681 void NETCON_unload(void)
683 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
684 if (OpenSSL_crypto_handle)
686 pERR_free_strings();
687 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
689 if (OpenSSL_ssl_handle)
691 if (ctx)
692 pSSL_CTX_free(ctx);
693 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
695 if (ssl_locks)
697 int i;
698 for (i = 0; i < num_ssl_locks; i++)
700 ssl_locks[i].DebugInfo->Spare[0] = 0;
701 DeleteCriticalSection(&ssl_locks[i]);
703 heap_free(ssl_locks);
705 #endif
708 /* translate a unix error code into a winsock one */
709 int sock_get_error( int err )
711 #if !defined(__MINGW32__) && !defined (_MSC_VER)
712 switch (err)
714 case EINTR: return WSAEINTR;
715 case EBADF: return WSAEBADF;
716 case EPERM:
717 case EACCES: return WSAEACCES;
718 case EFAULT: return WSAEFAULT;
719 case EINVAL: return WSAEINVAL;
720 case EMFILE: return WSAEMFILE;
721 case EWOULDBLOCK: return WSAEWOULDBLOCK;
722 case EINPROGRESS: return WSAEINPROGRESS;
723 case EALREADY: return WSAEALREADY;
724 case ENOTSOCK: return WSAENOTSOCK;
725 case EDESTADDRREQ: return WSAEDESTADDRREQ;
726 case EMSGSIZE: return WSAEMSGSIZE;
727 case EPROTOTYPE: return WSAEPROTOTYPE;
728 case ENOPROTOOPT: return WSAENOPROTOOPT;
729 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
730 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
731 case EOPNOTSUPP: return WSAEOPNOTSUPP;
732 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
733 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
734 case EADDRINUSE: return WSAEADDRINUSE;
735 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
736 case ENETDOWN: return WSAENETDOWN;
737 case ENETUNREACH: return WSAENETUNREACH;
738 case ENETRESET: return WSAENETRESET;
739 case ECONNABORTED: return WSAECONNABORTED;
740 case EPIPE:
741 case ECONNRESET: return WSAECONNRESET;
742 case ENOBUFS: return WSAENOBUFS;
743 case EISCONN: return WSAEISCONN;
744 case ENOTCONN: return WSAENOTCONN;
745 case ESHUTDOWN: return WSAESHUTDOWN;
746 case ETOOMANYREFS: return WSAETOOMANYREFS;
747 case ETIMEDOUT: return WSAETIMEDOUT;
748 case ECONNREFUSED: return WSAECONNREFUSED;
749 case ELOOP: return WSAELOOP;
750 case ENAMETOOLONG: return WSAENAMETOOLONG;
751 case EHOSTDOWN: return WSAEHOSTDOWN;
752 case EHOSTUNREACH: return WSAEHOSTUNREACH;
753 case ENOTEMPTY: return WSAENOTEMPTY;
754 #ifdef EPROCLIM
755 case EPROCLIM: return WSAEPROCLIM;
756 #endif
757 #ifdef EUSERS
758 case EUSERS: return WSAEUSERS;
759 #endif
760 #ifdef EDQUOT
761 case EDQUOT: return WSAEDQUOT;
762 #endif
763 #ifdef ESTALE
764 case ESTALE: return WSAESTALE;
765 #endif
766 #ifdef EREMOTE
767 case EREMOTE: return WSAEREMOTE;
768 #endif
769 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
771 #endif
772 return err;
775 /******************************************************************************
776 * NETCON_secure_connect
777 * Initiates a secure connection over an existing plaintext connection.
779 DWORD NETCON_secure_connect(netconn_t *connection)
781 DWORD res = ERROR_NOT_SUPPORTED;
782 #ifdef SONAME_LIBSSL
783 void *ssl_s;
784 int bits;
786 /* can't connect if we are already connected */
787 if (connection->ssl_s)
789 ERR("already connected\n");
790 return ERROR_INTERNET_CANNOT_CONNECT;
793 ssl_s = pSSL_new(ctx);
794 if (!ssl_s)
796 ERR("SSL_new failed: %s\n",
797 pERR_error_string(pERR_get_error(), 0));
798 return ERROR_OUTOFMEMORY;
801 if (!pSSL_set_fd(ssl_s, connection->socketFD))
803 ERR("SSL_set_fd failed: %s\n",
804 pERR_error_string(pERR_get_error(), 0));
805 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
806 goto fail;
809 if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
811 ERR("SSL_set_ex_data failed: %s\n",
812 pERR_error_string(pERR_get_error(), 0));
813 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
814 goto fail;
816 if (pSSL_connect(ssl_s) <= 0)
818 res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
819 if (!res)
820 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
821 ERR("SSL_connect failed: %d\n", res);
822 goto fail;
825 connection->ssl_s = ssl_s;
827 bits = NETCON_GetCipherStrength(connection);
828 if (bits >= 128)
829 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
830 else if (bits >= 56)
831 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
832 else
833 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
834 connection->security_flags |= SECURITY_FLAG_SECURE;
836 if(connection->mask_errors)
837 connection->server->security_flags = connection->security_flags;
838 return ERROR_SUCCESS;
840 fail:
841 if (ssl_s)
843 pSSL_shutdown(ssl_s);
844 pSSL_free(ssl_s);
846 #endif
847 return res;
850 /******************************************************************************
851 * NETCON_send
852 * Basically calls 'send()' unless we should use SSL
853 * number of chars send is put in *sent
855 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
856 int *sent /* out */)
858 if (!connection->useSSL)
860 *sent = send(connection->socketFD, msg, len, flags);
861 if (*sent == -1)
862 return sock_get_error(errno);
863 return ERROR_SUCCESS;
865 else
867 #ifdef SONAME_LIBSSL
868 if(!connection->ssl_s) {
869 FIXME("not connected\n");
870 return ERROR_NOT_SUPPORTED;
872 if (flags)
873 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
874 *sent = pSSL_write(connection->ssl_s, msg, len);
875 if (*sent < 1 && len)
876 return ERROR_INTERNET_CONNECTION_ABORTED;
877 return ERROR_SUCCESS;
878 #else
879 return ERROR_NOT_SUPPORTED;
880 #endif
884 /******************************************************************************
885 * NETCON_recv
886 * Basically calls 'recv()' unless we should use SSL
887 * number of chars received is put in *recvd
889 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
890 int *recvd /* out */)
892 *recvd = 0;
893 if (!len)
894 return ERROR_SUCCESS;
895 if (!connection->useSSL)
897 *recvd = recv(connection->socketFD, buf, len, flags);
898 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
900 else
902 #ifdef SONAME_LIBSSL
903 if(!connection->ssl_s) {
904 FIXME("not connected\n");
905 return ERROR_NOT_SUPPORTED;
907 *recvd = pSSL_read(connection->ssl_s, buf, len);
909 /* Check if EOF was received */
910 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
911 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
912 return ERROR_SUCCESS;
914 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
915 #else
916 return ERROR_NOT_SUPPORTED;
917 #endif
921 /******************************************************************************
922 * NETCON_query_data_available
923 * Returns the number of bytes of peeked data plus the number of bytes of
924 * queued, but unread data.
926 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
928 *available = 0;
930 if (!connection->useSSL)
932 #ifdef FIONREAD
933 int unread;
934 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
935 if (!retval)
937 TRACE("%d bytes of queued, but unread data\n", unread);
938 *available += unread;
940 #endif
942 else
944 #ifdef SONAME_LIBSSL
945 *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
946 #endif
948 return TRUE;
951 BOOL NETCON_is_alive(netconn_t *netconn)
953 #ifdef MSG_DONTWAIT
954 ssize_t len;
955 BYTE b;
957 len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
958 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
959 #elif defined(__MINGW32__) || defined(_MSC_VER)
960 ULONG mode;
961 int len;
962 char b;
964 mode = 1;
965 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
966 return FALSE;
968 len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
970 mode = 0;
971 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
972 return FALSE;
974 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
975 #else
976 FIXME("not supported on this platform\n");
977 return TRUE;
978 #endif
981 LPCVOID NETCON_GetCert(netconn_t *connection)
983 #ifdef SONAME_LIBSSL
984 X509* cert;
985 LPCVOID r = NULL;
987 if (!connection->ssl_s)
988 return NULL;
990 cert = pSSL_get_peer_certificate(connection->ssl_s);
991 r = X509_to_cert_context(cert);
992 return r;
993 #else
994 return NULL;
995 #endif
998 int NETCON_GetCipherStrength(netconn_t *connection)
1000 #ifdef SONAME_LIBSSL
1001 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1002 const SSL_CIPHER *cipher;
1003 #else
1004 SSL_CIPHER *cipher;
1005 #endif
1006 int bits = 0;
1008 if (!connection->ssl_s)
1009 return 0;
1010 cipher = pSSL_get_current_cipher(connection->ssl_s);
1011 if (!cipher)
1012 return 0;
1013 pSSL_CIPHER_get_bits(cipher, &bits);
1014 return bits;
1015 #else
1016 return 0;
1017 #endif
1020 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1022 int result;
1023 struct timeval tv;
1025 /* value is in milliseconds, convert to struct timeval */
1026 if (value == INFINITE)
1028 tv.tv_sec = 0;
1029 tv.tv_usec = 0;
1031 else
1033 tv.tv_sec = value / 1000;
1034 tv.tv_usec = (value % 1000) * 1000;
1036 result = setsockopt(connection->socketFD, SOL_SOCKET,
1037 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1038 sizeof(tv));
1039 if (result == -1)
1041 WARN("setsockopt failed (%s)\n", strerror(errno));
1042 return sock_get_error(errno);
1044 return ERROR_SUCCESS;