winhttp: Honor more SECURITY_FLAG_IGNORE flags.
[wine/multimedia.git] / dlls / winhttp / net.c
blob398c0b7ff311ca21d21615b80b9f1f9c5cdb43b6
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 else
313 CERT_CHAIN_POLICY_PARA policyPara;
314 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
315 CERT_CHAIN_POLICY_STATUS policyStatus;
317 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
318 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
319 sslExtraPolicyPara.pwszServerName = server;
320 policyPara.cbSize = sizeof(policyPara);
321 policyPara.dwFlags = 0;
322 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
323 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
324 chain, &policyPara,
325 &policyStatus );
326 /* Any error in the policy status indicates that the
327 * policy couldn't be verified.
329 if (ret && policyStatus.dwError)
331 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
333 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
334 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
336 else
337 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
340 CertFreeCertificateChain( chain );
342 else
343 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
344 TRACE("returning %08x\n", err);
345 return err;
348 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
350 SSL *ssl;
351 WCHAR *server;
352 BOOL ret = FALSE;
353 netconn_t *conn;
354 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
355 CERT_STORE_CREATE_NEW_FLAG, NULL );
357 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
358 server = pSSL_get_ex_data( ssl, hostname_idx );
359 conn = pSSL_get_ex_data( ssl, conn_idx );
360 if (store)
362 X509 *cert;
363 int i;
364 PCCERT_CONTEXT endCert = NULL;
366 ret = TRUE;
367 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
369 PCCERT_CONTEXT context;
371 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
372 if ((context = X509_to_cert_context( cert )))
374 if (i == 0)
375 ret = CertAddCertificateContextToStore( store, context,
376 CERT_STORE_ADD_ALWAYS, &endCert );
377 else
378 ret = CertAddCertificateContextToStore( store, context,
379 CERT_STORE_ADD_ALWAYS, NULL );
380 CertFreeCertificateContext( context );
383 if (!endCert) ret = FALSE;
384 if (ret)
386 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
387 conn->security_flags );
389 if (err)
391 pSSL_set_ex_data( ssl, error_idx, (void *)err );
392 ret = FALSE;
395 CertFreeCertificateContext( endCert );
396 CertCloseStore( store, 0 );
398 return ret;
400 #endif
402 BOOL netconn_init( netconn_t *conn, BOOL secure )
404 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
405 int i;
406 #endif
408 conn->socket = -1;
409 if (!secure) return TRUE;
411 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
412 EnterCriticalSection( &init_ssl_cs );
413 if (libssl_handle)
415 LeaveCriticalSection( &init_ssl_cs );
416 return TRUE;
418 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
420 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
421 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
422 LeaveCriticalSection( &init_ssl_cs );
423 return FALSE;
425 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
427 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
428 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
429 LeaveCriticalSection( &init_ssl_cs );
430 return FALSE;
432 #define LOAD_FUNCPTR(x) \
433 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
435 ERR("Failed to load symbol %s\n", #x); \
436 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
437 LeaveCriticalSection( &init_ssl_cs ); \
438 return FALSE; \
440 LOAD_FUNCPTR( SSL_library_init );
441 LOAD_FUNCPTR( SSL_load_error_strings );
442 LOAD_FUNCPTR( SSLv23_method );
443 LOAD_FUNCPTR( SSL_CTX_free );
444 LOAD_FUNCPTR( SSL_CTX_new );
445 LOAD_FUNCPTR( SSL_new );
446 LOAD_FUNCPTR( SSL_free );
447 LOAD_FUNCPTR( SSL_set_fd );
448 LOAD_FUNCPTR( SSL_connect );
449 LOAD_FUNCPTR( SSL_shutdown );
450 LOAD_FUNCPTR( SSL_write );
451 LOAD_FUNCPTR( SSL_read );
452 LOAD_FUNCPTR( SSL_get_error );
453 LOAD_FUNCPTR( SSL_get_ex_new_index );
454 LOAD_FUNCPTR( SSL_get_ex_data );
455 LOAD_FUNCPTR( SSL_set_ex_data );
456 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
457 LOAD_FUNCPTR( SSL_get_peer_certificate );
458 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
459 LOAD_FUNCPTR( SSL_CTX_set_verify );
460 #undef LOAD_FUNCPTR
462 #define LOAD_FUNCPTR(x) \
463 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
465 ERR("Failed to load symbol %s\n", #x); \
466 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
467 LeaveCriticalSection( &init_ssl_cs ); \
468 return FALSE; \
470 LOAD_FUNCPTR( CRYPTO_num_locks );
471 LOAD_FUNCPTR( CRYPTO_set_id_callback );
472 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
473 LOAD_FUNCPTR( ERR_free_strings );
474 LOAD_FUNCPTR( ERR_get_error );
475 LOAD_FUNCPTR( ERR_error_string );
476 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
477 LOAD_FUNCPTR( i2d_X509 );
478 LOAD_FUNCPTR( sk_value );
479 LOAD_FUNCPTR( sk_num );
480 #undef LOAD_FUNCPTR
482 pSSL_library_init();
483 pSSL_load_error_strings();
485 method = pSSLv23_method();
486 ctx = pSSL_CTX_new( method );
487 if (!pSSL_CTX_set_default_verify_paths( ctx ))
489 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
490 set_last_error( ERROR_OUTOFMEMORY );
491 LeaveCriticalSection( &init_ssl_cs );
492 return FALSE;
494 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
495 if (hostname_idx == -1)
497 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
498 set_last_error( ERROR_OUTOFMEMORY );
499 LeaveCriticalSection( &init_ssl_cs );
500 return FALSE;
502 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
503 if (error_idx == -1)
505 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
506 set_last_error( ERROR_OUTOFMEMORY );
507 LeaveCriticalSection( &init_ssl_cs );
508 return FALSE;
510 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
511 if (conn_idx == -1)
513 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
514 set_last_error( ERROR_OUTOFMEMORY );
515 LeaveCriticalSection( &init_ssl_cs );
516 return FALSE;
518 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
520 pCRYPTO_set_id_callback(ssl_thread_id);
521 num_ssl_locks = pCRYPTO_num_locks();
522 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
523 if (!ssl_locks)
525 set_last_error( ERROR_OUTOFMEMORY );
526 LeaveCriticalSection( &init_ssl_cs );
527 return FALSE;
529 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
530 pCRYPTO_set_locking_callback(ssl_lock_callback);
532 LeaveCriticalSection( &init_ssl_cs );
533 #else
534 WARN("SSL support not compiled in.\n");
535 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
536 return FALSE;
537 #endif
538 return TRUE;
541 void netconn_unload( void )
543 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
544 if (libcrypto_handle)
546 pERR_free_strings();
547 wine_dlclose( libcrypto_handle, NULL, 0 );
549 if (libssl_handle)
551 if (ctx)
552 pSSL_CTX_free( ctx );
553 wine_dlclose( libssl_handle, NULL, 0 );
555 if (ssl_locks)
557 int i;
558 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
559 HeapFree( GetProcessHeap(), 0, ssl_locks );
561 #endif
564 BOOL netconn_connected( netconn_t *conn )
566 return (conn->socket != -1);
569 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
571 if ((conn->socket = socket( domain, type, protocol )) == -1)
573 WARN("unable to create socket (%s)\n", strerror(errno));
574 set_last_error( sock_get_error( errno ) );
575 return FALSE;
577 return TRUE;
580 BOOL netconn_close( netconn_t *conn )
582 int res;
584 #ifdef SONAME_LIBSSL
585 if (conn->secure)
587 heap_free( conn->peek_msg_mem );
588 conn->peek_msg_mem = NULL;
589 conn->peek_msg = NULL;
590 conn->peek_len = 0;
592 pSSL_shutdown( conn->ssl_conn );
593 pSSL_free( conn->ssl_conn );
595 conn->ssl_conn = NULL;
596 conn->secure = FALSE;
598 #endif
599 res = closesocket( conn->socket );
600 conn->socket = -1;
601 if (res == -1)
603 set_last_error( sock_get_error( errno ) );
604 return FALSE;
606 return TRUE;
609 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
611 BOOL ret = FALSE;
612 int res = 0, state;
614 if (timeout > 0)
616 state = 1;
617 ioctlsocket( conn->socket, FIONBIO, &state );
619 if (connect( conn->socket, sockaddr, addr_len ) < 0)
621 res = sock_get_error( errno );
622 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
624 struct pollfd pfd;
626 pfd.fd = conn->socket;
627 pfd.events = POLLOUT;
628 if (poll( &pfd, 1, timeout ) > 0)
629 ret = TRUE;
630 else
631 res = sock_get_error( errno );
634 else
635 ret = TRUE;
636 if (timeout > 0)
638 state = 0;
639 ioctlsocket( conn->socket, FIONBIO, &state );
641 if (!ret)
643 WARN("unable to connect to host (%d)\n", res);
644 set_last_error( res );
646 return ret;
649 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
651 #ifdef SONAME_LIBSSL
652 if (!(conn->ssl_conn = pSSL_new( ctx )))
654 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
655 set_last_error( ERROR_OUTOFMEMORY );
656 goto fail;
658 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
660 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
661 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
662 goto fail;
664 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
666 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
667 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
668 return FALSE;
670 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
672 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
673 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
674 goto fail;
676 if (pSSL_connect( conn->ssl_conn ) <= 0)
678 DWORD err;
680 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
681 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
682 ERR("couldn't verify server certificate (%d)\n", err);
683 set_last_error( err );
684 goto fail;
686 TRACE("established SSL connection\n");
687 conn->secure = TRUE;
688 return TRUE;
690 fail:
691 if (conn->ssl_conn)
693 pSSL_shutdown( conn->ssl_conn );
694 pSSL_free( conn->ssl_conn );
695 conn->ssl_conn = NULL;
697 #endif
698 return FALSE;
701 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
703 if (!netconn_connected( conn )) return FALSE;
704 if (conn->secure)
706 #ifdef SONAME_LIBSSL
707 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
708 *sent = pSSL_write( conn->ssl_conn, msg, len );
709 if (*sent < 1 && len) return FALSE;
710 return TRUE;
711 #else
712 return FALSE;
713 #endif
715 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
717 set_last_error( sock_get_error( errno ) );
718 return FALSE;
720 return TRUE;
723 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
725 int ret;
727 *recvd = 0;
728 if (!netconn_connected( conn )) return FALSE;
729 if (!len) return TRUE;
731 if (conn->secure)
733 #ifdef SONAME_LIBSSL
734 if (flags & ~(MSG_PEEK | MSG_WAITALL))
735 FIXME("SSL_read does not support the following flags: %08x\n", flags);
737 /* this ugly hack is all for MSG_PEEK */
738 if (flags & MSG_PEEK && !conn->peek_msg)
740 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
742 else if (flags & MSG_PEEK && conn->peek_msg)
744 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
745 *recvd = min( len, conn->peek_len );
746 memcpy( buf, conn->peek_msg, *recvd );
747 return TRUE;
749 else if (conn->peek_msg)
751 *recvd = min( len, conn->peek_len );
752 memcpy( buf, conn->peek_msg, *recvd );
753 conn->peek_len -= *recvd;
754 conn->peek_msg += *recvd;
756 if (conn->peek_len == 0)
758 heap_free( conn->peek_msg_mem );
759 conn->peek_msg_mem = NULL;
760 conn->peek_msg = NULL;
762 /* check if we have enough data from the peek buffer */
763 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
765 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
766 if (ret < 0)
767 return FALSE;
769 /* check if EOF was received */
770 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
771 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
773 netconn_close( conn );
774 return TRUE;
776 if (flags & MSG_PEEK) /* must copy into buffer */
778 conn->peek_len = ret;
779 if (!ret)
781 heap_free( conn->peek_msg_mem );
782 conn->peek_msg_mem = NULL;
783 conn->peek_msg = NULL;
785 else memcpy( conn->peek_msg, buf, ret );
787 *recvd = ret;
788 return TRUE;
789 #else
790 return FALSE;
791 #endif
793 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
795 set_last_error( sock_get_error( errno ) );
796 return FALSE;
798 return TRUE;
801 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
803 #ifdef FIONREAD
804 int ret, unread;
805 #endif
806 *available = 0;
807 if (!netconn_connected( conn )) return FALSE;
809 if (conn->secure)
811 #ifdef SONAME_LIBSSL
812 if (conn->peek_msg) *available = conn->peek_len;
813 #endif
814 return TRUE;
816 #ifdef FIONREAD
817 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
818 #endif
819 return TRUE;
822 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
824 struct pollfd pfd;
825 BOOL ret = FALSE;
826 DWORD recvd = 0;
828 if (!netconn_connected( conn )) return FALSE;
830 if (conn->secure)
832 #ifdef SONAME_LIBSSL
833 while (recvd < *buflen)
835 int dummy;
836 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
838 set_last_error( ERROR_CONNECTION_ABORTED );
839 break;
841 if (buffer[recvd] == '\n')
843 ret = TRUE;
844 break;
846 if (buffer[recvd] != '\r') recvd++;
848 if (ret)
850 buffer[recvd++] = 0;
851 *buflen = recvd;
852 TRACE("received line %s\n", debugstr_a(buffer));
854 return ret;
855 #else
856 return FALSE;
857 #endif
860 pfd.fd = conn->socket;
861 pfd.events = POLLIN;
862 while (recvd < *buflen)
864 int timeout, res;
865 struct timeval tv;
866 socklen_t len = sizeof(tv);
868 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
869 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
870 else
871 timeout = -1;
872 if (poll( &pfd, 1, timeout ) > 0)
874 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
876 if (res == -1) set_last_error( sock_get_error( errno ) );
877 break;
879 if (buffer[recvd] == '\n')
881 ret = TRUE;
882 break;
884 if (buffer[recvd] != '\r') recvd++;
886 else
888 set_last_error( ERROR_WINHTTP_TIMEOUT );
889 break;
892 if (ret)
894 buffer[recvd++] = 0;
895 *buflen = recvd;
896 TRACE("received line %s\n", debugstr_a(buffer));
898 return ret;
901 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
903 int res;
904 struct timeval tv;
906 /* value is in milliseconds, convert to struct timeval */
907 tv.tv_sec = value / 1000;
908 tv.tv_usec = (value % 1000) * 1000;
910 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
912 WARN("setsockopt failed (%s)\n", strerror( errno ));
913 return sock_get_error( errno );
915 return ERROR_SUCCESS;
918 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
920 char *hostname;
921 #ifdef HAVE_GETADDRINFO
922 struct addrinfo *res, hints;
923 int ret;
924 #else
925 struct hostent *he;
926 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
927 #endif
929 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
931 #ifdef HAVE_GETADDRINFO
932 memset( &hints, 0, sizeof(struct addrinfo) );
933 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
934 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
936 hints.ai_family = AF_INET;
938 ret = getaddrinfo( hostname, NULL, &hints, &res );
939 if (ret != 0)
941 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
942 hints.ai_family = AF_INET6;
943 ret = getaddrinfo( hostname, NULL, &hints, &res );
944 if (ret != 0)
946 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
947 heap_free( hostname );
948 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
951 heap_free( hostname );
952 if (*sa_len < res->ai_addrlen)
954 WARN("address too small\n");
955 freeaddrinfo( res );
956 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
958 *sa_len = res->ai_addrlen;
959 memcpy( sa, res->ai_addr, res->ai_addrlen );
960 /* Copy port */
961 switch (res->ai_family)
963 case AF_INET:
964 ((struct sockaddr_in *)sa)->sin_port = htons( port );
965 break;
966 case AF_INET6:
967 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
968 break;
971 freeaddrinfo( res );
972 return ERROR_SUCCESS;
973 #else
974 EnterCriticalSection( &cs_gethostbyname );
976 he = gethostbyname( hostname );
977 heap_free( hostname );
978 if (!he)
980 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
981 LeaveCriticalSection( &cs_gethostbyname );
982 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
984 if (*sa_len < sizeof(struct sockaddr_in))
986 WARN("address too small\n");
987 LeaveCriticalSection( &cs_gethostbyname );
988 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
990 *sa_len = sizeof(struct sockaddr_in);
991 memset( sa, 0, sizeof(struct sockaddr_in) );
992 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
993 sin->sin_family = he->h_addrtype;
994 sin->sin_port = htons( port );
996 LeaveCriticalSection( &cs_gethostbyname );
997 return ERROR_SUCCESS;
998 #endif
1001 struct resolve_args
1003 WCHAR *hostname;
1004 INTERNET_PORT port;
1005 struct sockaddr *sa;
1006 socklen_t *sa_len;
1009 static DWORD CALLBACK resolve_proc( LPVOID arg )
1011 struct resolve_args *ra = arg;
1012 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1015 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1017 DWORD ret;
1019 if (timeout)
1021 DWORD status;
1022 HANDLE thread;
1023 struct resolve_args ra;
1025 ra.hostname = hostname;
1026 ra.port = port;
1027 ra.sa = sa;
1028 ra.sa_len = sa_len;
1030 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1031 if (!thread) return FALSE;
1033 status = WaitForSingleObject( thread, timeout );
1034 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1035 else ret = ERROR_WINHTTP_TIMEOUT;
1036 CloseHandle( thread );
1038 else ret = resolve_hostname( hostname, port, sa, sa_len );
1040 if (ret)
1042 set_last_error( ret );
1043 return FALSE;
1045 return TRUE;
1048 const void *netconn_get_certificate( netconn_t *conn )
1050 #ifdef SONAME_LIBSSL
1051 X509 *cert;
1052 const CERT_CONTEXT *ret;
1054 if (!conn->secure) return NULL;
1056 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1057 ret = X509_to_cert_context( cert );
1058 return ret;
1059 #else
1060 return NULL;
1061 #endif