winhttp: Verify SSL policy of chains whose errors were ignored.
[wine.git] / dlls / winhttp / net.c
blob4812979199c55da969e4ca84cdb9e3df2907649b
1 /*
2 * Copyright 2008 Hans Leidekker for CodeWeavers
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "config.h"
20 #include "wine/port.h"
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <errno.h>
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
29 #endif
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
32 #endif
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
35 #endif
36 #ifdef HAVE_POLL_H
37 # include <poll.h>
38 #endif
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
41 # include <openssl/opensslv.h>
42 #undef FAR
43 #undef DSA
44 #endif
46 #define NONAMELESSUNION
48 #include "wine/debug.h"
49 #include "wine/library.h"
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winhttp.h"
54 #include "wincrypt.h"
56 #include "winhttp_private.h"
58 /* to avoid conflicts with the Unix socket headers */
59 #define USE_WS_PREFIX
60 #include "winsock2.h"
62 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
64 #ifndef HAVE_GETADDRINFO
66 /* critical section to protect non-reentrant gethostbyname() */
67 static CRITICAL_SECTION cs_gethostbyname;
68 static CRITICAL_SECTION_DEBUG critsect_debug =
70 0, 0, &cs_gethostbyname,
71 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
72 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
74 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
76 #endif
78 #ifdef SONAME_LIBSSL
80 #include <openssl/err.h>
82 static CRITICAL_SECTION init_ssl_cs;
83 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
85 0, 0, &init_ssl_cs,
86 { &init_ssl_cs_debug.ProcessLocksList,
87 &init_ssl_cs_debug.ProcessLocksList },
88 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
90 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
92 static void *libssl_handle;
93 static void *libcrypto_handle;
95 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER> 0x1000000)
96 static const SSL_METHOD *method;
97 #else
98 static SSL_METHOD *method;
99 #endif
100 static SSL_CTX *ctx;
101 static int hostname_idx;
102 static int error_idx;
103 static int conn_idx;
105 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
107 MAKE_FUNCPTR( SSL_library_init );
108 MAKE_FUNCPTR( SSL_load_error_strings );
109 MAKE_FUNCPTR( SSLv23_method );
110 MAKE_FUNCPTR( SSL_CTX_free );
111 MAKE_FUNCPTR( SSL_CTX_new );
112 MAKE_FUNCPTR( SSL_new );
113 MAKE_FUNCPTR( SSL_free );
114 MAKE_FUNCPTR( SSL_set_fd );
115 MAKE_FUNCPTR( SSL_connect );
116 MAKE_FUNCPTR( SSL_shutdown );
117 MAKE_FUNCPTR( SSL_write );
118 MAKE_FUNCPTR( SSL_read );
119 MAKE_FUNCPTR( SSL_get_error );
120 MAKE_FUNCPTR( SSL_get_ex_new_index );
121 MAKE_FUNCPTR( SSL_get_ex_data );
122 MAKE_FUNCPTR( SSL_set_ex_data );
123 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
124 MAKE_FUNCPTR( SSL_get_peer_certificate );
125 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
126 MAKE_FUNCPTR( SSL_CTX_set_verify );
128 MAKE_FUNCPTR( CRYPTO_num_locks );
129 MAKE_FUNCPTR( CRYPTO_set_id_callback );
130 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
131 MAKE_FUNCPTR( ERR_free_strings );
132 MAKE_FUNCPTR( ERR_get_error );
133 MAKE_FUNCPTR( ERR_error_string );
134 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
135 MAKE_FUNCPTR( i2d_X509 );
136 MAKE_FUNCPTR( sk_value );
137 MAKE_FUNCPTR( sk_num );
138 #undef MAKE_FUNCPTR
140 static CRITICAL_SECTION *ssl_locks;
141 static unsigned int num_ssl_locks;
143 static unsigned long ssl_thread_id(void)
145 return GetCurrentThreadId();
148 static void ssl_lock_callback(int mode, int type, const char *file, int line)
150 if (mode & CRYPTO_LOCK)
151 EnterCriticalSection( &ssl_locks[type] );
152 else
153 LeaveCriticalSection( &ssl_locks[type] );
156 #endif
158 /* translate a unix error code into a winsock error code */
159 static int sock_get_error( int err )
161 #if !defined(__MINGW32__) && !defined (_MSC_VER)
162 switch (err)
164 case EINTR: return WSAEINTR;
165 case EBADF: return WSAEBADF;
166 case EPERM:
167 case EACCES: return WSAEACCES;
168 case EFAULT: return WSAEFAULT;
169 case EINVAL: return WSAEINVAL;
170 case EMFILE: return WSAEMFILE;
171 case EWOULDBLOCK: return WSAEWOULDBLOCK;
172 case EINPROGRESS: return WSAEINPROGRESS;
173 case EALREADY: return WSAEALREADY;
174 case ENOTSOCK: return WSAENOTSOCK;
175 case EDESTADDRREQ: return WSAEDESTADDRREQ;
176 case EMSGSIZE: return WSAEMSGSIZE;
177 case EPROTOTYPE: return WSAEPROTOTYPE;
178 case ENOPROTOOPT: return WSAENOPROTOOPT;
179 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
180 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
181 case EOPNOTSUPP: return WSAEOPNOTSUPP;
182 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
183 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
184 case EADDRINUSE: return WSAEADDRINUSE;
185 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
186 case ENETDOWN: return WSAENETDOWN;
187 case ENETUNREACH: return WSAENETUNREACH;
188 case ENETRESET: return WSAENETRESET;
189 case ECONNABORTED: return WSAECONNABORTED;
190 case EPIPE:
191 case ECONNRESET: return WSAECONNRESET;
192 case ENOBUFS: return WSAENOBUFS;
193 case EISCONN: return WSAEISCONN;
194 case ENOTCONN: return WSAENOTCONN;
195 case ESHUTDOWN: return WSAESHUTDOWN;
196 case ETOOMANYREFS: return WSAETOOMANYREFS;
197 case ETIMEDOUT: return WSAETIMEDOUT;
198 case ECONNREFUSED: return WSAECONNREFUSED;
199 case ELOOP: return WSAELOOP;
200 case ENAMETOOLONG: return WSAENAMETOOLONG;
201 case EHOSTDOWN: return WSAEHOSTDOWN;
202 case EHOSTUNREACH: return WSAEHOSTUNREACH;
203 case ENOTEMPTY: return WSAENOTEMPTY;
204 #ifdef EPROCLIM
205 case EPROCLIM: return WSAEPROCLIM;
206 #endif
207 #ifdef EUSERS
208 case EUSERS: return WSAEUSERS;
209 #endif
210 #ifdef EDQUOT
211 case EDQUOT: return WSAEDQUOT;
212 #endif
213 #ifdef ESTALE
214 case ESTALE: return WSAESTALE;
215 #endif
216 #ifdef EREMOTE
217 case EREMOTE: return WSAEREMOTE;
218 #endif
219 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
221 #endif
222 return err;
225 #ifdef SONAME_LIBSSL
226 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
228 unsigned char *buffer, *p;
229 int len;
230 BOOL malloc = FALSE;
231 PCCERT_CONTEXT ret;
233 p = NULL;
234 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
236 * SSL 0.9.7 and above malloc the buffer if it is null.
237 * however earlier version do not and so we would need to alloc the buffer.
239 * see the i2d_X509 man page for more details.
241 if (!p)
243 if (!(buffer = heap_alloc( len ))) return NULL;
244 p = buffer;
245 len = pi2d_X509( cert, &p );
247 else
249 buffer = p;
250 malloc = TRUE;
253 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
255 if (malloc) free( buffer );
256 else heap_free( buffer );
258 return ret;
261 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
262 WCHAR *server, DWORD security_flags )
264 BOOL ret;
265 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
266 PCCERT_CHAIN_CONTEXT chain;
267 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
268 char *server_auth[] = { oid_server_auth };
269 DWORD err = ERROR_SUCCESS;
271 TRACE("verifying %s\n", debugstr_w( server ));
272 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
273 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
274 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
275 NULL, &chain )))
277 if (chain->TrustStatus.dwErrorStatus)
279 static const DWORD supportedErrors =
280 CERT_TRUST_IS_NOT_TIME_VALID |
281 CERT_TRUST_IS_UNTRUSTED_ROOT |
282 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
284 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
286 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
287 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
289 else if (chain->TrustStatus.dwErrorStatus &
290 CERT_TRUST_IS_UNTRUSTED_ROOT)
292 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
293 err = ERROR_WINHTTP_SECURE_INVALID_CA;
295 else if ((chain->TrustStatus.dwErrorStatus &
296 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
297 (chain->TrustStatus.dwErrorStatus &
298 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
299 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
300 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
301 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
302 else if (chain->TrustStatus.dwErrorStatus &
303 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
305 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
306 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
308 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
309 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
311 if (!err)
313 CERT_CHAIN_POLICY_PARA policyPara;
314 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
315 CERT_CHAIN_POLICY_STATUS policyStatus;
316 CERT_CHAIN_CONTEXT chainCopy;
318 /* Clear chain->TrustStatus.dwErrorStatus so
319 * CertVerifyCertificateChainPolicy will verify additional checks
320 * rather than stopping with an existing, ignored error.
322 memcpy(&chainCopy, chain, sizeof(chainCopy));
323 chainCopy.TrustStatus.dwErrorStatus = 0;
324 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
325 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
326 sslExtraPolicyPara.pwszServerName = server;
327 policyPara.cbSize = sizeof(policyPara);
328 policyPara.dwFlags = 0;
329 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
330 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
331 &chainCopy, &policyPara,
332 &policyStatus );
333 /* Any error in the policy status indicates that the
334 * policy couldn't be verified.
336 if (ret && policyStatus.dwError)
338 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
340 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
341 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
343 else
344 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
347 CertFreeCertificateChain( chain );
349 else
350 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
351 TRACE("returning %08x\n", err);
352 return err;
355 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
357 SSL *ssl;
358 WCHAR *server;
359 BOOL ret = FALSE;
360 netconn_t *conn;
361 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
362 CERT_STORE_CREATE_NEW_FLAG, NULL );
364 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
365 server = pSSL_get_ex_data( ssl, hostname_idx );
366 conn = pSSL_get_ex_data( ssl, conn_idx );
367 if (store)
369 X509 *cert;
370 int i;
371 PCCERT_CONTEXT endCert = NULL;
373 ret = TRUE;
374 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
376 PCCERT_CONTEXT context;
378 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
379 if ((context = X509_to_cert_context( cert )))
381 if (i == 0)
382 ret = CertAddCertificateContextToStore( store, context,
383 CERT_STORE_ADD_ALWAYS, &endCert );
384 else
385 ret = CertAddCertificateContextToStore( store, context,
386 CERT_STORE_ADD_ALWAYS, NULL );
387 CertFreeCertificateContext( context );
390 if (!endCert) ret = FALSE;
391 if (ret)
393 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
394 conn->security_flags );
396 if (err)
398 pSSL_set_ex_data( ssl, error_idx, (void *)err );
399 ret = FALSE;
402 CertFreeCertificateContext( endCert );
403 CertCloseStore( store, 0 );
405 return ret;
407 #endif
409 BOOL netconn_init( netconn_t *conn, BOOL secure )
411 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
412 int i;
413 #endif
415 conn->socket = -1;
416 if (!secure) return TRUE;
418 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
419 EnterCriticalSection( &init_ssl_cs );
420 if (libssl_handle)
422 LeaveCriticalSection( &init_ssl_cs );
423 return TRUE;
425 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
427 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
428 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
429 LeaveCriticalSection( &init_ssl_cs );
430 return FALSE;
432 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
434 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
435 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
436 LeaveCriticalSection( &init_ssl_cs );
437 return FALSE;
439 #define LOAD_FUNCPTR(x) \
440 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
442 ERR("Failed to load symbol %s\n", #x); \
443 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
444 LeaveCriticalSection( &init_ssl_cs ); \
445 return FALSE; \
447 LOAD_FUNCPTR( SSL_library_init );
448 LOAD_FUNCPTR( SSL_load_error_strings );
449 LOAD_FUNCPTR( SSLv23_method );
450 LOAD_FUNCPTR( SSL_CTX_free );
451 LOAD_FUNCPTR( SSL_CTX_new );
452 LOAD_FUNCPTR( SSL_new );
453 LOAD_FUNCPTR( SSL_free );
454 LOAD_FUNCPTR( SSL_set_fd );
455 LOAD_FUNCPTR( SSL_connect );
456 LOAD_FUNCPTR( SSL_shutdown );
457 LOAD_FUNCPTR( SSL_write );
458 LOAD_FUNCPTR( SSL_read );
459 LOAD_FUNCPTR( SSL_get_error );
460 LOAD_FUNCPTR( SSL_get_ex_new_index );
461 LOAD_FUNCPTR( SSL_get_ex_data );
462 LOAD_FUNCPTR( SSL_set_ex_data );
463 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
464 LOAD_FUNCPTR( SSL_get_peer_certificate );
465 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
466 LOAD_FUNCPTR( SSL_CTX_set_verify );
467 #undef LOAD_FUNCPTR
469 #define LOAD_FUNCPTR(x) \
470 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
472 ERR("Failed to load symbol %s\n", #x); \
473 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
474 LeaveCriticalSection( &init_ssl_cs ); \
475 return FALSE; \
477 LOAD_FUNCPTR( CRYPTO_num_locks );
478 LOAD_FUNCPTR( CRYPTO_set_id_callback );
479 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
480 LOAD_FUNCPTR( ERR_free_strings );
481 LOAD_FUNCPTR( ERR_get_error );
482 LOAD_FUNCPTR( ERR_error_string );
483 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
484 LOAD_FUNCPTR( i2d_X509 );
485 LOAD_FUNCPTR( sk_value );
486 LOAD_FUNCPTR( sk_num );
487 #undef LOAD_FUNCPTR
489 pSSL_library_init();
490 pSSL_load_error_strings();
492 method = pSSLv23_method();
493 ctx = pSSL_CTX_new( method );
494 if (!pSSL_CTX_set_default_verify_paths( ctx ))
496 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
497 set_last_error( ERROR_OUTOFMEMORY );
498 LeaveCriticalSection( &init_ssl_cs );
499 return FALSE;
501 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
502 if (hostname_idx == -1)
504 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
505 set_last_error( ERROR_OUTOFMEMORY );
506 LeaveCriticalSection( &init_ssl_cs );
507 return FALSE;
509 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
510 if (error_idx == -1)
512 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
513 set_last_error( ERROR_OUTOFMEMORY );
514 LeaveCriticalSection( &init_ssl_cs );
515 return FALSE;
517 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
518 if (conn_idx == -1)
520 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
521 set_last_error( ERROR_OUTOFMEMORY );
522 LeaveCriticalSection( &init_ssl_cs );
523 return FALSE;
525 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
527 pCRYPTO_set_id_callback(ssl_thread_id);
528 num_ssl_locks = pCRYPTO_num_locks();
529 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
530 if (!ssl_locks)
532 set_last_error( ERROR_OUTOFMEMORY );
533 LeaveCriticalSection( &init_ssl_cs );
534 return FALSE;
536 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
537 pCRYPTO_set_locking_callback(ssl_lock_callback);
539 LeaveCriticalSection( &init_ssl_cs );
540 #else
541 WARN("SSL support not compiled in.\n");
542 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
543 return FALSE;
544 #endif
545 return TRUE;
548 void netconn_unload( void )
550 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
551 if (libcrypto_handle)
553 pERR_free_strings();
554 wine_dlclose( libcrypto_handle, NULL, 0 );
556 if (libssl_handle)
558 if (ctx)
559 pSSL_CTX_free( ctx );
560 wine_dlclose( libssl_handle, NULL, 0 );
562 if (ssl_locks)
564 int i;
565 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
566 HeapFree( GetProcessHeap(), 0, ssl_locks );
568 #endif
571 BOOL netconn_connected( netconn_t *conn )
573 return (conn->socket != -1);
576 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
578 if ((conn->socket = socket( domain, type, protocol )) == -1)
580 WARN("unable to create socket (%s)\n", strerror(errno));
581 set_last_error( sock_get_error( errno ) );
582 return FALSE;
584 return TRUE;
587 BOOL netconn_close( netconn_t *conn )
589 int res;
591 #ifdef SONAME_LIBSSL
592 if (conn->secure)
594 heap_free( conn->peek_msg_mem );
595 conn->peek_msg_mem = NULL;
596 conn->peek_msg = NULL;
597 conn->peek_len = 0;
599 pSSL_shutdown( conn->ssl_conn );
600 pSSL_free( conn->ssl_conn );
602 conn->ssl_conn = NULL;
603 conn->secure = FALSE;
605 #endif
606 res = closesocket( conn->socket );
607 conn->socket = -1;
608 if (res == -1)
610 set_last_error( sock_get_error( errno ) );
611 return FALSE;
613 return TRUE;
616 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
618 BOOL ret = FALSE;
619 int res = 0, state;
621 if (timeout > 0)
623 state = 1;
624 ioctlsocket( conn->socket, FIONBIO, &state );
626 if (connect( conn->socket, sockaddr, addr_len ) < 0)
628 res = sock_get_error( errno );
629 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
631 struct pollfd pfd;
633 pfd.fd = conn->socket;
634 pfd.events = POLLOUT;
635 if (poll( &pfd, 1, timeout ) > 0)
636 ret = TRUE;
637 else
638 res = sock_get_error( errno );
641 else
642 ret = TRUE;
643 if (timeout > 0)
645 state = 0;
646 ioctlsocket( conn->socket, FIONBIO, &state );
648 if (!ret)
650 WARN("unable to connect to host (%d)\n", res);
651 set_last_error( res );
653 return ret;
656 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
658 #ifdef SONAME_LIBSSL
659 if (!(conn->ssl_conn = pSSL_new( ctx )))
661 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
662 set_last_error( ERROR_OUTOFMEMORY );
663 goto fail;
665 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
667 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
668 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
669 goto fail;
671 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
673 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
674 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
675 return FALSE;
677 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
679 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
680 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
681 goto fail;
683 if (pSSL_connect( conn->ssl_conn ) <= 0)
685 DWORD err;
687 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
688 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
689 ERR("couldn't verify server certificate (%d)\n", err);
690 set_last_error( err );
691 goto fail;
693 TRACE("established SSL connection\n");
694 conn->secure = TRUE;
695 return TRUE;
697 fail:
698 if (conn->ssl_conn)
700 pSSL_shutdown( conn->ssl_conn );
701 pSSL_free( conn->ssl_conn );
702 conn->ssl_conn = NULL;
704 #endif
705 return FALSE;
708 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
710 if (!netconn_connected( conn )) return FALSE;
711 if (conn->secure)
713 #ifdef SONAME_LIBSSL
714 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
715 *sent = pSSL_write( conn->ssl_conn, msg, len );
716 if (*sent < 1 && len) return FALSE;
717 return TRUE;
718 #else
719 return FALSE;
720 #endif
722 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
724 set_last_error( sock_get_error( errno ) );
725 return FALSE;
727 return TRUE;
730 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
732 int ret;
734 *recvd = 0;
735 if (!netconn_connected( conn )) return FALSE;
736 if (!len) return TRUE;
738 if (conn->secure)
740 #ifdef SONAME_LIBSSL
741 if (flags & ~(MSG_PEEK | MSG_WAITALL))
742 FIXME("SSL_read does not support the following flags: %08x\n", flags);
744 /* this ugly hack is all for MSG_PEEK */
745 if (flags & MSG_PEEK && !conn->peek_msg)
747 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
749 else if (flags & MSG_PEEK && conn->peek_msg)
751 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
752 *recvd = min( len, conn->peek_len );
753 memcpy( buf, conn->peek_msg, *recvd );
754 return TRUE;
756 else if (conn->peek_msg)
758 *recvd = min( len, conn->peek_len );
759 memcpy( buf, conn->peek_msg, *recvd );
760 conn->peek_len -= *recvd;
761 conn->peek_msg += *recvd;
763 if (conn->peek_len == 0)
765 heap_free( conn->peek_msg_mem );
766 conn->peek_msg_mem = NULL;
767 conn->peek_msg = NULL;
769 /* check if we have enough data from the peek buffer */
770 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
772 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
773 if (ret < 0)
774 return FALSE;
776 /* check if EOF was received */
777 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
778 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
780 netconn_close( conn );
781 return TRUE;
783 if (flags & MSG_PEEK) /* must copy into buffer */
785 conn->peek_len = ret;
786 if (!ret)
788 heap_free( conn->peek_msg_mem );
789 conn->peek_msg_mem = NULL;
790 conn->peek_msg = NULL;
792 else memcpy( conn->peek_msg, buf, ret );
794 *recvd = ret;
795 return TRUE;
796 #else
797 return FALSE;
798 #endif
800 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
802 set_last_error( sock_get_error( errno ) );
803 return FALSE;
805 return TRUE;
808 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
810 #ifdef FIONREAD
811 int ret, unread;
812 #endif
813 *available = 0;
814 if (!netconn_connected( conn )) return FALSE;
816 if (conn->secure)
818 #ifdef SONAME_LIBSSL
819 if (conn->peek_msg) *available = conn->peek_len;
820 #endif
821 return TRUE;
823 #ifdef FIONREAD
824 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
825 #endif
826 return TRUE;
829 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
831 struct pollfd pfd;
832 BOOL ret = FALSE;
833 DWORD recvd = 0;
835 if (!netconn_connected( conn )) return FALSE;
837 if (conn->secure)
839 #ifdef SONAME_LIBSSL
840 while (recvd < *buflen)
842 int dummy;
843 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
845 set_last_error( ERROR_CONNECTION_ABORTED );
846 break;
848 if (buffer[recvd] == '\n')
850 ret = TRUE;
851 break;
853 if (buffer[recvd] != '\r') recvd++;
855 if (ret)
857 buffer[recvd++] = 0;
858 *buflen = recvd;
859 TRACE("received line %s\n", debugstr_a(buffer));
861 return ret;
862 #else
863 return FALSE;
864 #endif
867 pfd.fd = conn->socket;
868 pfd.events = POLLIN;
869 while (recvd < *buflen)
871 int timeout, res;
872 struct timeval tv;
873 socklen_t len = sizeof(tv);
875 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
876 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
877 else
878 timeout = -1;
879 if (poll( &pfd, 1, timeout ) > 0)
881 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
883 if (res == -1) set_last_error( sock_get_error( errno ) );
884 break;
886 if (buffer[recvd] == '\n')
888 ret = TRUE;
889 break;
891 if (buffer[recvd] != '\r') recvd++;
893 else
895 set_last_error( ERROR_WINHTTP_TIMEOUT );
896 break;
899 if (ret)
901 buffer[recvd++] = 0;
902 *buflen = recvd;
903 TRACE("received line %s\n", debugstr_a(buffer));
905 return ret;
908 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
910 int res;
911 struct timeval tv;
913 /* value is in milliseconds, convert to struct timeval */
914 tv.tv_sec = value / 1000;
915 tv.tv_usec = (value % 1000) * 1000;
917 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
919 WARN("setsockopt failed (%s)\n", strerror( errno ));
920 return sock_get_error( errno );
922 return ERROR_SUCCESS;
925 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
927 char *hostname;
928 #ifdef HAVE_GETADDRINFO
929 struct addrinfo *res, hints;
930 int ret;
931 #else
932 struct hostent *he;
933 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
934 #endif
936 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
938 #ifdef HAVE_GETADDRINFO
939 memset( &hints, 0, sizeof(struct addrinfo) );
940 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
941 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
943 hints.ai_family = AF_INET;
945 ret = getaddrinfo( hostname, NULL, &hints, &res );
946 if (ret != 0)
948 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
949 hints.ai_family = AF_INET6;
950 ret = getaddrinfo( hostname, NULL, &hints, &res );
951 if (ret != 0)
953 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
954 heap_free( hostname );
955 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
958 heap_free( hostname );
959 if (*sa_len < res->ai_addrlen)
961 WARN("address too small\n");
962 freeaddrinfo( res );
963 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
965 *sa_len = res->ai_addrlen;
966 memcpy( sa, res->ai_addr, res->ai_addrlen );
967 /* Copy port */
968 switch (res->ai_family)
970 case AF_INET:
971 ((struct sockaddr_in *)sa)->sin_port = htons( port );
972 break;
973 case AF_INET6:
974 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
975 break;
978 freeaddrinfo( res );
979 return ERROR_SUCCESS;
980 #else
981 EnterCriticalSection( &cs_gethostbyname );
983 he = gethostbyname( hostname );
984 heap_free( hostname );
985 if (!he)
987 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
988 LeaveCriticalSection( &cs_gethostbyname );
989 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
991 if (*sa_len < sizeof(struct sockaddr_in))
993 WARN("address too small\n");
994 LeaveCriticalSection( &cs_gethostbyname );
995 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
997 *sa_len = sizeof(struct sockaddr_in);
998 memset( sa, 0, sizeof(struct sockaddr_in) );
999 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
1000 sin->sin_family = he->h_addrtype;
1001 sin->sin_port = htons( port );
1003 LeaveCriticalSection( &cs_gethostbyname );
1004 return ERROR_SUCCESS;
1005 #endif
1008 struct resolve_args
1010 WCHAR *hostname;
1011 INTERNET_PORT port;
1012 struct sockaddr *sa;
1013 socklen_t *sa_len;
1016 static DWORD CALLBACK resolve_proc( LPVOID arg )
1018 struct resolve_args *ra = arg;
1019 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1022 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1024 DWORD ret;
1026 if (timeout)
1028 DWORD status;
1029 HANDLE thread;
1030 struct resolve_args ra;
1032 ra.hostname = hostname;
1033 ra.port = port;
1034 ra.sa = sa;
1035 ra.sa_len = sa_len;
1037 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1038 if (!thread) return FALSE;
1040 status = WaitForSingleObject( thread, timeout );
1041 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1042 else ret = ERROR_WINHTTP_TIMEOUT;
1043 CloseHandle( thread );
1045 else ret = resolve_hostname( hostname, port, sa, sa_len );
1047 if (ret)
1049 set_last_error( ret );
1050 return FALSE;
1052 return TRUE;
1055 const void *netconn_get_certificate( netconn_t *conn )
1057 #ifdef SONAME_LIBSSL
1058 X509 *cert;
1059 const CERT_CONTEXT *ret;
1061 if (!conn->secure) return NULL;
1063 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1064 ret = X509_to_cert_context( cert );
1065 return ret;
1066 #else
1067 return NULL;
1068 #endif