comctl32/tests: Some tests for TVM_GETNEXTITEM and item toggle.
[wine/multimedia.git] / dlls / wininet / netconnection.c
blob1119e48c16c223da4ea6cfd050e91680e2b68d9e
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"
83 #include "wincrypt.h"
85 #include "wine/debug.h"
86 #include "internet.h"
88 /* To avoid conflicts with the Unix socket headers. we only need it for
89 * the error codes anyway. */
90 #define USE_WS_PREFIX
91 #include "winsock2.h"
93 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
96 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
98 /* FIXME!!!!!!
99 * This should use winsock - To use winsock the functions will have to change a bit
100 * as they are designed for unix sockets.
101 * SSL stuff should use crypt32.dll
104 #ifdef SONAME_LIBSSL
106 #include <openssl/err.h>
108 static void *OpenSSL_ssl_handle;
109 static void *OpenSSL_crypto_handle;
111 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
112 static const SSL_METHOD *meth;
113 #else
114 static SSL_METHOD *meth;
115 #endif
116 static SSL_CTX *ctx;
117 static int hostname_idx;
118 static int error_idx;
119 static int conn_idx;
121 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
123 /* OpenSSL functions that we use */
124 MAKE_FUNCPTR(SSL_library_init);
125 MAKE_FUNCPTR(SSL_load_error_strings);
126 MAKE_FUNCPTR(SSLv23_method);
127 MAKE_FUNCPTR(SSL_CTX_free);
128 MAKE_FUNCPTR(SSL_CTX_new);
129 MAKE_FUNCPTR(SSL_new);
130 MAKE_FUNCPTR(SSL_free);
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);
163 #undef MAKE_FUNCPTR
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]);
177 else
178 LeaveCriticalSection(&ssl_locks[type]);
181 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
183 unsigned char* buffer,*p;
184 INT len;
185 BOOL malloced = FALSE;
186 PCCERT_CONTEXT ret;
188 p = NULL;
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.
196 if (!p)
198 buffer = heap_alloc(len);
199 p = buffer;
200 len = pi2d_X509(cert,&p);
202 else
204 buffer = p;
205 malloced = TRUE;
208 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
210 if (malloced)
211 free(buffer);
212 else
213 HeapFree(GetProcessHeap(),0,buffer);
215 return ret;
218 static DWORD netconn_verify_cert(PCCERT_CONTEXT cert, HCERTSTORE store,
219 WCHAR *server, DWORD security_flags)
221 BOOL ret;
222 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
223 PCCERT_CHAIN_CONTEXT chain;
224 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
225 char *server_auth[] = { oid_server_auth };
226 DWORD err = ERROR_SUCCESS, chainFlags = 0;
228 TRACE("verifying %s\n", debugstr_w(server));
229 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
230 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
231 if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
232 chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
233 if ((ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara,
234 chainFlags, NULL, &chain)))
236 if (chain->TrustStatus.dwErrorStatus)
238 static const DWORD supportedErrors =
239 CERT_TRUST_IS_NOT_TIME_VALID |
240 CERT_TRUST_IS_UNTRUSTED_ROOT |
241 CERT_TRUST_IS_OFFLINE_REVOCATION |
242 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
243 CERT_TRUST_IS_REVOKED |
244 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
246 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID &&
247 !(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
248 err = ERROR_INTERNET_SEC_CERT_DATE_INVALID;
249 else if (chain->TrustStatus.dwErrorStatus &
250 CERT_TRUST_IS_UNTRUSTED_ROOT &&
251 !(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
252 err = ERROR_INTERNET_INVALID_CA;
253 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
254 ((chain->TrustStatus.dwErrorStatus &
255 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
256 (chain->TrustStatus.dwErrorStatus &
257 CERT_TRUST_REVOCATION_STATUS_UNKNOWN)))
258 err = ERROR_INTERNET_SEC_CERT_NO_REV;
259 else if (!(security_flags & SECURITY_FLAG_IGNORE_REVOCATION) &&
260 (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED))
261 err = ERROR_INTERNET_SEC_CERT_REVOKED;
262 else if (!(security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE) &&
263 (chain->TrustStatus.dwErrorStatus &
264 CERT_TRUST_IS_NOT_VALID_FOR_USAGE))
265 err = ERROR_INTERNET_SEC_INVALID_CERT;
266 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
267 err = ERROR_INTERNET_SEC_INVALID_CERT;
269 if (!err)
271 CERT_CHAIN_POLICY_PARA policyPara;
272 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
273 CERT_CHAIN_POLICY_STATUS policyStatus;
274 CERT_CHAIN_CONTEXT chainCopy;
276 /* Clear chain->TrustStatus.dwErrorStatus so
277 * CertVerifyCertificateChainPolicy will verify additional checks
278 * rather than stopping with an existing, ignored error.
280 memcpy(&chainCopy, chain, sizeof(chainCopy));
281 chainCopy.TrustStatus.dwErrorStatus = 0;
282 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
283 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
284 sslExtraPolicyPara.pwszServerName = server;
285 sslExtraPolicyPara.fdwChecks = security_flags;
286 policyPara.cbSize = sizeof(policyPara);
287 policyPara.dwFlags = 0;
288 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
289 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
290 &chainCopy, &policyPara, &policyStatus);
291 /* Any error in the policy status indicates that the
292 * policy couldn't be verified.
294 if (ret && policyStatus.dwError)
296 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
297 err = ERROR_INTERNET_SEC_CERT_CN_INVALID;
298 else
299 err = ERROR_INTERNET_SEC_INVALID_CERT;
302 CertFreeCertificateChain(chain);
304 TRACE("returning %08x\n", err);
305 return err;
308 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
310 SSL *ssl;
311 WCHAR *server;
312 BOOL ret = FALSE;
313 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
314 CERT_STORE_CREATE_NEW_FLAG, NULL);
315 netconn_t *conn;
317 ssl = pX509_STORE_CTX_get_ex_data(ctx,
318 pSSL_get_ex_data_X509_STORE_CTX_idx());
319 server = pSSL_get_ex_data(ssl, hostname_idx);
320 conn = pSSL_get_ex_data(ssl, conn_idx);
321 if (store)
323 X509 *cert;
324 int i;
325 PCCERT_CONTEXT endCert = NULL;
326 struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
328 ret = TRUE;
329 for (i = 0; ret && i < psk_num(chain); i++)
331 PCCERT_CONTEXT context;
333 cert = (X509 *)psk_value(chain, i);
334 if ((context = X509_to_cert_context(cert)))
336 if (i == 0)
337 ret = CertAddCertificateContextToStore(store, context,
338 CERT_STORE_ADD_ALWAYS, &endCert);
339 else
340 ret = CertAddCertificateContextToStore(store, context,
341 CERT_STORE_ADD_ALWAYS, NULL);
342 CertFreeCertificateContext(context);
345 if (!endCert) ret = FALSE;
346 if (ret)
348 DWORD_PTR err = netconn_verify_cert(endCert, store, server,
349 conn->security_flags);
351 if (err)
353 pSSL_set_ex_data(ssl, error_idx, (void *)err);
354 ret = FALSE;
357 CertFreeCertificateContext(endCert);
358 CertCloseStore(store, 0);
360 return ret;
363 #endif
365 static CRITICAL_SECTION init_ssl_cs;
366 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
368 0, 0, &init_ssl_cs,
369 { &init_ssl_cs_debug.ProcessLocksList,
370 &init_ssl_cs_debug.ProcessLocksList },
371 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
373 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
375 static DWORD init_openssl(void)
377 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
378 int i;
380 if(OpenSSL_ssl_handle)
381 return ERROR_SUCCESS;
383 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
384 if(!OpenSSL_ssl_handle) {
385 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
386 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
389 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
390 if(!OpenSSL_crypto_handle) {
391 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
392 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
395 /* mmm nice ugly macroness */
396 #define DYNSSL(x) \
397 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
398 if (!p##x) { \
399 ERR("failed to load symbol %s\n", #x); \
400 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
403 DYNSSL(SSL_library_init);
404 DYNSSL(SSL_load_error_strings);
405 DYNSSL(SSLv23_method);
406 DYNSSL(SSL_CTX_free);
407 DYNSSL(SSL_CTX_new);
408 DYNSSL(SSL_new);
409 DYNSSL(SSL_free);
410 DYNSSL(SSL_set_fd);
411 DYNSSL(SSL_connect);
412 DYNSSL(SSL_shutdown);
413 DYNSSL(SSL_write);
414 DYNSSL(SSL_read);
415 DYNSSL(SSL_pending);
416 DYNSSL(SSL_get_error);
417 DYNSSL(SSL_get_ex_new_index);
418 DYNSSL(SSL_get_ex_data);
419 DYNSSL(SSL_set_ex_data);
420 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
421 DYNSSL(SSL_get_peer_certificate);
422 DYNSSL(SSL_CTX_get_timeout);
423 DYNSSL(SSL_CTX_set_timeout);
424 DYNSSL(SSL_CTX_set_default_verify_paths);
425 DYNSSL(SSL_CTX_set_verify);
426 DYNSSL(SSL_get_current_cipher);
427 DYNSSL(SSL_CIPHER_get_bits);
428 #undef DYNSSL
430 #define DYNCRYPTO(x) \
431 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
432 if (!p##x) { \
433 ERR("failed to load symbol %s\n", #x); \
434 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
437 DYNCRYPTO(BIO_new_fp);
438 DYNCRYPTO(CRYPTO_num_locks);
439 DYNCRYPTO(CRYPTO_set_id_callback);
440 DYNCRYPTO(CRYPTO_set_locking_callback);
441 DYNCRYPTO(ERR_free_strings);
442 DYNCRYPTO(ERR_get_error);
443 DYNCRYPTO(ERR_error_string);
444 DYNCRYPTO(X509_STORE_CTX_get_ex_data);
445 DYNCRYPTO(X509_STORE_CTX_get_chain);
446 DYNCRYPTO(i2d_X509);
447 DYNCRYPTO(sk_num);
448 DYNCRYPTO(sk_value);
449 #undef DYNCRYPTO
451 pSSL_library_init();
452 pSSL_load_error_strings();
453 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
455 meth = pSSLv23_method();
456 ctx = pSSL_CTX_new(meth);
457 if(!pSSL_CTX_set_default_verify_paths(ctx)) {
458 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
459 pERR_error_string(pERR_get_error(), 0));
460 return ERROR_OUTOFMEMORY;
463 hostname_idx = pSSL_get_ex_new_index(0, (void *)"hostname index", NULL, NULL, NULL);
464 if(hostname_idx == -1) {
465 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
466 return ERROR_OUTOFMEMORY;
469 error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
470 if(error_idx == -1) {
471 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
472 return ERROR_OUTOFMEMORY;
475 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
476 if(conn_idx == -1) {
477 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
478 return ERROR_OUTOFMEMORY;
481 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
483 pCRYPTO_set_id_callback(ssl_thread_id);
484 num_ssl_locks = pCRYPTO_num_locks();
485 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
486 if(!ssl_locks)
487 return ERROR_OUTOFMEMORY;
489 for(i = 0; i < num_ssl_locks; i++)
490 InitializeCriticalSection(&ssl_locks[i]);
491 pCRYPTO_set_locking_callback(ssl_lock_callback);
493 return ERROR_SUCCESS;
494 #else
495 FIXME("can't use SSL, not compiled in.\n");
496 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
497 #endif
500 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, netconn_t **ret)
502 netconn_t *netconn;
503 int result, flag;
505 if(useSSL) {
506 DWORD res;
508 TRACE("using SSL connection\n");
510 EnterCriticalSection(&init_ssl_cs);
511 res = init_openssl();
512 LeaveCriticalSection(&init_ssl_cs);
513 if(res != ERROR_SUCCESS)
514 return res;
517 netconn = heap_alloc_zero(sizeof(*netconn));
518 if(!netconn)
519 return ERROR_OUTOFMEMORY;
521 netconn->useSSL = useSSL;
522 netconn->socketFD = -1;
523 netconn->security_flags = security_flags;
524 list_init(&netconn->pool_entry);
526 assert(server->addr_len);
527 result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
528 if(result != -1) {
529 result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
530 if(result == -1)
531 closesocket(netconn->socketFD);
533 if(result == -1) {
534 heap_free(netconn);
535 return sock_get_error(errno);
538 #ifdef TCP_NODELAY
539 flag = 1;
540 result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
541 if(result < 0)
542 WARN("setsockopt(TCP_NODELAY) failed\n");
543 #endif
545 server_addref(server);
546 netconn->server = server;
548 *ret = netconn;
549 return ERROR_SUCCESS;
552 void free_netconn(netconn_t *netconn)
554 server_release(netconn->server);
556 #ifdef SONAME_LIBSSL
557 if (netconn->ssl_s) {
558 pSSL_shutdown(netconn->ssl_s);
559 pSSL_free(netconn->ssl_s);
561 #endif
563 closesocket(netconn->socketFD);
564 heap_free(netconn);
567 void NETCON_unload(void)
569 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
570 if (OpenSSL_crypto_handle)
572 pERR_free_strings();
573 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
575 if (OpenSSL_ssl_handle)
577 if (ctx)
578 pSSL_CTX_free(ctx);
579 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
581 if (ssl_locks)
583 int i;
584 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection(&ssl_locks[i]);
585 HeapFree(GetProcessHeap(), 0, ssl_locks);
587 #endif
590 /* translate a unix error code into a winsock one */
591 int sock_get_error( int err )
593 #if !defined(__MINGW32__) && !defined (_MSC_VER)
594 switch (err)
596 case EINTR: return WSAEINTR;
597 case EBADF: return WSAEBADF;
598 case EPERM:
599 case EACCES: return WSAEACCES;
600 case EFAULT: return WSAEFAULT;
601 case EINVAL: return WSAEINVAL;
602 case EMFILE: return WSAEMFILE;
603 case EWOULDBLOCK: return WSAEWOULDBLOCK;
604 case EINPROGRESS: return WSAEINPROGRESS;
605 case EALREADY: return WSAEALREADY;
606 case ENOTSOCK: return WSAENOTSOCK;
607 case EDESTADDRREQ: return WSAEDESTADDRREQ;
608 case EMSGSIZE: return WSAEMSGSIZE;
609 case EPROTOTYPE: return WSAEPROTOTYPE;
610 case ENOPROTOOPT: return WSAENOPROTOOPT;
611 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
612 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
613 case EOPNOTSUPP: return WSAEOPNOTSUPP;
614 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
615 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
616 case EADDRINUSE: return WSAEADDRINUSE;
617 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
618 case ENETDOWN: return WSAENETDOWN;
619 case ENETUNREACH: return WSAENETUNREACH;
620 case ENETRESET: return WSAENETRESET;
621 case ECONNABORTED: return WSAECONNABORTED;
622 case EPIPE:
623 case ECONNRESET: return WSAECONNRESET;
624 case ENOBUFS: return WSAENOBUFS;
625 case EISCONN: return WSAEISCONN;
626 case ENOTCONN: return WSAENOTCONN;
627 case ESHUTDOWN: return WSAESHUTDOWN;
628 case ETOOMANYREFS: return WSAETOOMANYREFS;
629 case ETIMEDOUT: return WSAETIMEDOUT;
630 case ECONNREFUSED: return WSAECONNREFUSED;
631 case ELOOP: return WSAELOOP;
632 case ENAMETOOLONG: return WSAENAMETOOLONG;
633 case EHOSTDOWN: return WSAEHOSTDOWN;
634 case EHOSTUNREACH: return WSAEHOSTUNREACH;
635 case ENOTEMPTY: return WSAENOTEMPTY;
636 #ifdef EPROCLIM
637 case EPROCLIM: return WSAEPROCLIM;
638 #endif
639 #ifdef EUSERS
640 case EUSERS: return WSAEUSERS;
641 #endif
642 #ifdef EDQUOT
643 case EDQUOT: return WSAEDQUOT;
644 #endif
645 #ifdef ESTALE
646 case ESTALE: return WSAESTALE;
647 #endif
648 #ifdef EREMOTE
649 case EREMOTE: return WSAEREMOTE;
650 #endif
651 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
653 #endif
654 return err;
657 /******************************************************************************
658 * NETCON_secure_connect
659 * Initiates a secure connection over an existing plaintext connection.
661 DWORD NETCON_secure_connect(netconn_t *connection, LPWSTR hostname)
663 void *ssl_s;
664 DWORD res = ERROR_NOT_SUPPORTED;
666 #ifdef SONAME_LIBSSL
667 /* can't connect if we are already connected */
668 if (connection->ssl_s)
670 ERR("already connected\n");
671 return ERROR_INTERNET_CANNOT_CONNECT;
674 ssl_s = pSSL_new(ctx);
675 if (!ssl_s)
677 ERR("SSL_new failed: %s\n",
678 pERR_error_string(pERR_get_error(), 0));
679 return ERROR_OUTOFMEMORY;
682 if (!pSSL_set_fd(ssl_s, connection->socketFD))
684 ERR("SSL_set_fd failed: %s\n",
685 pERR_error_string(pERR_get_error(), 0));
686 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
687 goto fail;
690 if (!pSSL_set_ex_data(ssl_s, hostname_idx, hostname))
692 ERR("SSL_set_ex_data failed: %s\n",
693 pERR_error_string(pERR_get_error(), 0));
694 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
695 goto fail;
697 if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
699 ERR("SSL_set_ex_data failed: %s\n",
700 pERR_error_string(pERR_get_error(), 0));
701 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
702 goto fail;
704 if (pSSL_connect(ssl_s) <= 0)
706 res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
707 if (!res)
708 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
709 ERR("SSL_connect failed: %d\n", res);
710 goto fail;
713 connection->ssl_s = ssl_s;
714 return ERROR_SUCCESS;
716 fail:
717 if (ssl_s)
719 pSSL_shutdown(ssl_s);
720 pSSL_free(ssl_s);
722 #endif
723 return res;
726 /******************************************************************************
727 * NETCON_send
728 * Basically calls 'send()' unless we should use SSL
729 * number of chars send is put in *sent
731 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
732 int *sent /* out */)
734 if (!connection->useSSL)
736 *sent = send(connection->socketFD, msg, len, flags);
737 if (*sent == -1)
738 return sock_get_error(errno);
739 return ERROR_SUCCESS;
741 else
743 #ifdef SONAME_LIBSSL
744 if(!connection->ssl_s) {
745 FIXME("not connected\n");
746 return ERROR_NOT_SUPPORTED;
748 if (flags)
749 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
750 *sent = pSSL_write(connection->ssl_s, msg, len);
751 if (*sent < 1 && len)
752 return ERROR_INTERNET_CONNECTION_ABORTED;
753 return ERROR_SUCCESS;
754 #else
755 return ERROR_NOT_SUPPORTED;
756 #endif
760 /******************************************************************************
761 * NETCON_recv
762 * Basically calls 'recv()' unless we should use SSL
763 * number of chars received is put in *recvd
765 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
766 int *recvd /* out */)
768 *recvd = 0;
769 if (!len)
770 return ERROR_SUCCESS;
771 if (!connection->useSSL)
773 *recvd = recv(connection->socketFD, buf, len, flags);
774 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
776 else
778 #ifdef SONAME_LIBSSL
779 if(!connection->ssl_s) {
780 FIXME("not connected\n");
781 return ERROR_NOT_SUPPORTED;
783 *recvd = pSSL_read(connection->ssl_s, buf, len);
785 /* Check if EOF was received */
786 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
787 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
788 return ERROR_SUCCESS;
790 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
791 #else
792 return ERROR_NOT_SUPPORTED;
793 #endif
797 /******************************************************************************
798 * NETCON_query_data_available
799 * Returns the number of bytes of peeked data plus the number of bytes of
800 * queued, but unread data.
802 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
804 *available = 0;
806 if (!connection->useSSL)
808 #ifdef FIONREAD
809 int unread;
810 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
811 if (!retval)
813 TRACE("%d bytes of queued, but unread data\n", unread);
814 *available += unread;
816 #endif
818 else
820 #ifdef SONAME_LIBSSL
821 *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
822 #endif
824 return TRUE;
827 BOOL NETCON_is_alive(netconn_t *netconn)
829 #ifdef MSG_DONTWAIT
830 ssize_t len;
831 BYTE b;
833 len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
834 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
835 #elif defined(__MINGW32__) || defined(_MSC_VER)
836 ULONG mode;
837 int len;
838 char b;
840 mode = 1;
841 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
842 return FALSE;
844 len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
846 mode = 0;
847 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
848 return FALSE;
850 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
851 #else
852 FIXME("not supported on this platform\n");
853 return TRUE;
854 #endif
857 LPCVOID NETCON_GetCert(netconn_t *connection)
859 #ifdef SONAME_LIBSSL
860 X509* cert;
861 LPCVOID r = NULL;
863 if (!connection->ssl_s)
864 return NULL;
866 cert = pSSL_get_peer_certificate(connection->ssl_s);
867 r = X509_to_cert_context(cert);
868 return r;
869 #else
870 return NULL;
871 #endif
874 int NETCON_GetCipherStrength(netconn_t *connection)
876 #ifdef SONAME_LIBSSL
877 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
878 const SSL_CIPHER *cipher;
879 #else
880 SSL_CIPHER *cipher;
881 #endif
882 int bits = 0;
884 if (!connection->ssl_s)
885 return 0;
886 cipher = pSSL_get_current_cipher(connection->ssl_s);
887 if (!cipher)
888 return 0;
889 pSSL_CIPHER_get_bits(cipher, &bits);
890 return bits;
891 #else
892 return 0;
893 #endif
896 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, int value)
898 int result;
899 struct timeval tv;
901 /* value is in milliseconds, convert to struct timeval */
902 tv.tv_sec = value / 1000;
903 tv.tv_usec = (value % 1000) * 1000;
905 result = setsockopt(connection->socketFD, SOL_SOCKET,
906 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
907 sizeof(tv));
909 if (result == -1)
911 WARN("setsockopt failed (%s)\n", strerror(errno));
912 return sock_get_error(errno);
915 return ERROR_SUCCESS;