gdiplus/tests: Don't fail if we do find Microsoft Sans Serif on Wine.
[wine/hacks.git] / dlls / winhttp / net.c
blobab7a4a71a88754c7ac64eebba1a107cd55e68e90
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 #undef FAR
42 #undef DSA
43 #endif
45 #define NONAMELESSUNION
47 #include "wine/debug.h"
48 #include "wine/library.h"
50 #include "windef.h"
51 #include "winbase.h"
52 #include "winhttp.h"
53 #include "wincrypt.h"
55 #include "winhttp_private.h"
57 /* to avoid conflicts with the Unix socket headers */
58 #define USE_WS_PREFIX
59 #include "winsock2.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(winhttp);
63 #ifndef HAVE_GETADDRINFO
65 /* critical section to protect non-reentrant gethostbyname() */
66 static CRITICAL_SECTION cs_gethostbyname;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
69 0, 0, &cs_gethostbyname,
70 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71 0, 0, { (DWORD_PTR)(__FILE__ ": cs_gethostbyname") }
73 static CRITICAL_SECTION cs_gethostbyname = { &critsect_debug, -1, 0, 0, 0, 0 };
75 #endif
77 #ifdef SONAME_LIBSSL
79 #include <openssl/err.h>
81 static CRITICAL_SECTION init_ssl_cs;
82 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
84 0, 0, &init_ssl_cs,
85 { &init_ssl_cs_debug.ProcessLocksList,
86 &init_ssl_cs_debug.ProcessLocksList },
87 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
89 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
91 static void *libssl_handle;
92 static void *libcrypto_handle;
94 static SSL_METHOD *method;
95 static SSL_CTX *ctx;
96 static int hostname_idx;
97 static int error_idx;
98 static int conn_idx;
100 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
102 MAKE_FUNCPTR( SSL_library_init );
103 MAKE_FUNCPTR( SSL_load_error_strings );
104 MAKE_FUNCPTR( SSLv23_method );
105 MAKE_FUNCPTR( SSL_CTX_free );
106 MAKE_FUNCPTR( SSL_CTX_new );
107 MAKE_FUNCPTR( SSL_new );
108 MAKE_FUNCPTR( SSL_free );
109 MAKE_FUNCPTR( SSL_set_fd );
110 MAKE_FUNCPTR( SSL_connect );
111 MAKE_FUNCPTR( SSL_shutdown );
112 MAKE_FUNCPTR( SSL_write );
113 MAKE_FUNCPTR( SSL_read );
114 MAKE_FUNCPTR( SSL_get_ex_new_index );
115 MAKE_FUNCPTR( SSL_get_ex_data );
116 MAKE_FUNCPTR( SSL_set_ex_data );
117 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
118 MAKE_FUNCPTR( SSL_get_verify_result );
119 MAKE_FUNCPTR( SSL_get_peer_certificate );
120 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
121 MAKE_FUNCPTR( SSL_CTX_set_verify );
123 MAKE_FUNCPTR( CRYPTO_num_locks );
124 MAKE_FUNCPTR( CRYPTO_set_id_callback );
125 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
126 MAKE_FUNCPTR( ERR_free_strings );
127 MAKE_FUNCPTR( ERR_get_error );
128 MAKE_FUNCPTR( ERR_error_string );
129 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
130 MAKE_FUNCPTR( i2d_X509 );
131 MAKE_FUNCPTR( sk_value );
132 MAKE_FUNCPTR( sk_num );
133 #undef MAKE_FUNCPTR
135 static CRITICAL_SECTION *ssl_locks;
136 static unsigned int num_ssl_locks;
138 static unsigned long ssl_thread_id(void)
140 return GetCurrentThreadId();
143 static void ssl_lock_callback(int mode, int type, const char *file, int line)
145 if (mode & CRYPTO_LOCK)
146 EnterCriticalSection( &ssl_locks[type] );
147 else
148 LeaveCriticalSection( &ssl_locks[type] );
151 #endif
153 /* translate a unix error code into a winsock error code */
154 static int sock_get_error( int err )
156 #if !defined(__MINGW32__) && !defined (_MSC_VER)
157 switch (err)
159 case EINTR: return WSAEINTR;
160 case EBADF: return WSAEBADF;
161 case EPERM:
162 case EACCES: return WSAEACCES;
163 case EFAULT: return WSAEFAULT;
164 case EINVAL: return WSAEINVAL;
165 case EMFILE: return WSAEMFILE;
166 case EWOULDBLOCK: return WSAEWOULDBLOCK;
167 case EINPROGRESS: return WSAEINPROGRESS;
168 case EALREADY: return WSAEALREADY;
169 case ENOTSOCK: return WSAENOTSOCK;
170 case EDESTADDRREQ: return WSAEDESTADDRREQ;
171 case EMSGSIZE: return WSAEMSGSIZE;
172 case EPROTOTYPE: return WSAEPROTOTYPE;
173 case ENOPROTOOPT: return WSAENOPROTOOPT;
174 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
175 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
176 case EOPNOTSUPP: return WSAEOPNOTSUPP;
177 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
178 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
179 case EADDRINUSE: return WSAEADDRINUSE;
180 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
181 case ENETDOWN: return WSAENETDOWN;
182 case ENETUNREACH: return WSAENETUNREACH;
183 case ENETRESET: return WSAENETRESET;
184 case ECONNABORTED: return WSAECONNABORTED;
185 case EPIPE:
186 case ECONNRESET: return WSAECONNRESET;
187 case ENOBUFS: return WSAENOBUFS;
188 case EISCONN: return WSAEISCONN;
189 case ENOTCONN: return WSAENOTCONN;
190 case ESHUTDOWN: return WSAESHUTDOWN;
191 case ETOOMANYREFS: return WSAETOOMANYREFS;
192 case ETIMEDOUT: return WSAETIMEDOUT;
193 case ECONNREFUSED: return WSAECONNREFUSED;
194 case ELOOP: return WSAELOOP;
195 case ENAMETOOLONG: return WSAENAMETOOLONG;
196 case EHOSTDOWN: return WSAEHOSTDOWN;
197 case EHOSTUNREACH: return WSAEHOSTUNREACH;
198 case ENOTEMPTY: return WSAENOTEMPTY;
199 #ifdef EPROCLIM
200 case EPROCLIM: return WSAEPROCLIM;
201 #endif
202 #ifdef EUSERS
203 case EUSERS: return WSAEUSERS;
204 #endif
205 #ifdef EDQUOT
206 case EDQUOT: return WSAEDQUOT;
207 #endif
208 #ifdef ESTALE
209 case ESTALE: return WSAESTALE;
210 #endif
211 #ifdef EREMOTE
212 case EREMOTE: return WSAEREMOTE;
213 #endif
214 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
216 #endif
217 return err;
220 #ifdef SONAME_LIBSSL
221 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
223 unsigned char *buffer, *p;
224 int len;
225 BOOL malloc = FALSE;
226 PCCERT_CONTEXT ret;
228 p = NULL;
229 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
231 * SSL 0.9.7 and above malloc the buffer if it is null.
232 * however earlier version do not and so we would need to alloc the buffer.
234 * see the i2d_X509 man page for more details.
236 if (!p)
238 if (!(buffer = heap_alloc( len ))) return NULL;
239 p = buffer;
240 len = pi2d_X509( cert, &p );
242 else
244 buffer = p;
245 malloc = TRUE;
248 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
250 if (malloc) free( buffer );
251 else heap_free( buffer );
253 return ret;
256 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
257 WCHAR *server, DWORD security_flags )
259 BOOL ret;
260 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
261 PCCERT_CHAIN_CONTEXT chain;
262 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
263 char *server_auth[] = { oid_server_auth };
264 DWORD err = ERROR_SUCCESS;
266 TRACE("verifying %s\n", debugstr_w( server ));
267 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
268 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
269 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
270 NULL, &chain )))
272 if (chain->TrustStatus.dwErrorStatus)
274 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
276 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
277 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
279 else if (chain->TrustStatus.dwErrorStatus &
280 CERT_TRUST_IS_UNTRUSTED_ROOT)
281 err = ERROR_WINHTTP_SECURE_INVALID_CA;
282 else if ((chain->TrustStatus.dwErrorStatus &
283 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
284 (chain->TrustStatus.dwErrorStatus &
285 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
286 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
287 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
288 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
289 else if (chain->TrustStatus.dwErrorStatus &
290 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
292 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
293 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
295 else
296 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
298 else
300 CERT_CHAIN_POLICY_PARA policyPara;
301 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
302 CERT_CHAIN_POLICY_STATUS policyStatus;
304 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
305 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
306 sslExtraPolicyPara.pwszServerName = server;
307 policyPara.cbSize = sizeof(policyPara);
308 policyPara.dwFlags = 0;
309 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
310 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
311 chain, &policyPara,
312 &policyStatus );
313 /* Any error in the policy status indicates that the
314 * policy couldn't be verified.
316 if (ret && policyStatus.dwError)
318 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
320 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
321 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
323 else
324 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
327 CertFreeCertificateChain( chain );
329 else
330 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
331 TRACE("returning %08x\n", err);
332 return err;
335 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
337 SSL *ssl;
338 WCHAR *server;
339 BOOL ret = FALSE;
340 netconn_t *conn;
342 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
343 server = pSSL_get_ex_data( ssl, hostname_idx );
344 conn = pSSL_get_ex_data( ssl, conn_idx );
345 if (preverify_ok)
347 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
348 CERT_STORE_CREATE_NEW_FLAG, NULL );
350 if (store)
352 X509 *cert;
353 int i;
354 PCCERT_CONTEXT endCert = NULL;
356 ret = TRUE;
357 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
359 PCCERT_CONTEXT context;
361 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
362 if ((context = X509_to_cert_context( cert )))
364 if (i == 0)
365 ret = CertAddCertificateContextToStore( store, context,
366 CERT_STORE_ADD_ALWAYS, &endCert );
367 else
368 ret = CertAddCertificateContextToStore( store, context,
369 CERT_STORE_ADD_ALWAYS, NULL );
370 CertFreeCertificateContext( context );
373 if (!endCert) ret = FALSE;
374 if (ret)
376 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
377 conn->security_flags );
379 if (err)
381 pSSL_set_ex_data( ssl, error_idx, (void *)err );
382 ret = FALSE;
385 CertFreeCertificateContext( endCert );
386 CertCloseStore( store, 0 );
389 return ret;
391 #endif
393 BOOL netconn_init( netconn_t *conn, BOOL secure )
395 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
396 int i;
397 #endif
399 conn->socket = -1;
400 if (!secure) return TRUE;
402 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
403 EnterCriticalSection( &init_ssl_cs );
404 if (libssl_handle)
406 LeaveCriticalSection( &init_ssl_cs );
407 return TRUE;
409 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
411 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
412 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
413 LeaveCriticalSection( &init_ssl_cs );
414 return FALSE;
416 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
418 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
419 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
420 LeaveCriticalSection( &init_ssl_cs );
421 return FALSE;
423 #define LOAD_FUNCPTR(x) \
424 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
426 ERR("Failed to load symbol %s\n", #x); \
427 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
428 LeaveCriticalSection( &init_ssl_cs ); \
429 return FALSE; \
431 LOAD_FUNCPTR( SSL_library_init );
432 LOAD_FUNCPTR( SSL_load_error_strings );
433 LOAD_FUNCPTR( SSLv23_method );
434 LOAD_FUNCPTR( SSL_CTX_free );
435 LOAD_FUNCPTR( SSL_CTX_new );
436 LOAD_FUNCPTR( SSL_new );
437 LOAD_FUNCPTR( SSL_free );
438 LOAD_FUNCPTR( SSL_set_fd );
439 LOAD_FUNCPTR( SSL_connect );
440 LOAD_FUNCPTR( SSL_shutdown );
441 LOAD_FUNCPTR( SSL_write );
442 LOAD_FUNCPTR( SSL_read );
443 LOAD_FUNCPTR( SSL_get_ex_new_index );
444 LOAD_FUNCPTR( SSL_get_ex_data );
445 LOAD_FUNCPTR( SSL_set_ex_data );
446 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
447 LOAD_FUNCPTR( SSL_get_verify_result );
448 LOAD_FUNCPTR( SSL_get_peer_certificate );
449 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
450 LOAD_FUNCPTR( SSL_CTX_set_verify );
451 #undef LOAD_FUNCPTR
453 #define LOAD_FUNCPTR(x) \
454 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
456 ERR("Failed to load symbol %s\n", #x); \
457 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
458 LeaveCriticalSection( &init_ssl_cs ); \
459 return FALSE; \
461 LOAD_FUNCPTR( CRYPTO_num_locks );
462 LOAD_FUNCPTR( CRYPTO_set_id_callback );
463 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
464 LOAD_FUNCPTR( ERR_free_strings );
465 LOAD_FUNCPTR( ERR_get_error );
466 LOAD_FUNCPTR( ERR_error_string );
467 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
468 LOAD_FUNCPTR( i2d_X509 );
469 LOAD_FUNCPTR( sk_value );
470 LOAD_FUNCPTR( sk_num );
471 #undef LOAD_FUNCPTR
473 pSSL_library_init();
474 pSSL_load_error_strings();
476 method = pSSLv23_method();
477 ctx = pSSL_CTX_new( method );
478 if (!pSSL_CTX_set_default_verify_paths( ctx ))
480 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
481 set_last_error( ERROR_OUTOFMEMORY );
482 LeaveCriticalSection( &init_ssl_cs );
483 return FALSE;
485 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
486 if (hostname_idx == -1)
488 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
489 set_last_error( ERROR_OUTOFMEMORY );
490 LeaveCriticalSection( &init_ssl_cs );
491 return FALSE;
493 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
494 if (error_idx == -1)
496 ERR("SSL_get_ex_new_index 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 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
502 if (conn_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 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
511 pCRYPTO_set_id_callback(ssl_thread_id);
512 num_ssl_locks = pCRYPTO_num_locks();
513 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
514 if (!ssl_locks)
516 set_last_error( ERROR_OUTOFMEMORY );
517 LeaveCriticalSection( &init_ssl_cs );
518 return FALSE;
520 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
521 pCRYPTO_set_locking_callback(ssl_lock_callback);
523 LeaveCriticalSection( &init_ssl_cs );
524 #else
525 WARN("SSL support not compiled in.\n");
526 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
527 return FALSE;
528 #endif
529 return TRUE;
532 void netconn_unload( void )
534 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
535 if (libcrypto_handle)
537 pERR_free_strings();
538 wine_dlclose( libcrypto_handle, NULL, 0 );
540 if (libssl_handle)
542 if (ctx)
543 pSSL_CTX_free( ctx );
544 wine_dlclose( libssl_handle, NULL, 0 );
546 if (ssl_locks)
548 int i;
549 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
550 HeapFree( GetProcessHeap(), 0, ssl_locks );
552 #endif
555 BOOL netconn_connected( netconn_t *conn )
557 return (conn->socket != -1);
560 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
562 if ((conn->socket = socket( domain, type, protocol )) == -1)
564 WARN("unable to create socket (%s)\n", strerror(errno));
565 set_last_error( sock_get_error( errno ) );
566 return FALSE;
568 return TRUE;
571 BOOL netconn_close( netconn_t *conn )
573 int res;
575 #ifdef SONAME_LIBSSL
576 if (conn->secure)
578 heap_free( conn->peek_msg_mem );
579 conn->peek_msg_mem = NULL;
580 conn->peek_msg = NULL;
581 conn->peek_len = 0;
583 pSSL_shutdown( conn->ssl_conn );
584 pSSL_free( conn->ssl_conn );
586 conn->ssl_conn = NULL;
587 conn->secure = FALSE;
589 #endif
590 res = closesocket( conn->socket );
591 conn->socket = -1;
592 if (res == -1)
594 set_last_error( sock_get_error( errno ) );
595 return FALSE;
597 return TRUE;
600 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
602 BOOL ret = FALSE;
603 int res = 0, state;
605 if (timeout > 0)
607 state = 1;
608 ioctlsocket( conn->socket, FIONBIO, &state );
610 if (connect( conn->socket, sockaddr, addr_len ) < 0)
612 res = sock_get_error( errno );
613 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
615 struct pollfd pfd;
617 pfd.fd = conn->socket;
618 pfd.events = POLLOUT;
619 if (poll( &pfd, 1, timeout ) > 0)
620 ret = TRUE;
621 else
622 res = sock_get_error( errno );
625 else
626 ret = TRUE;
627 if (timeout > 0)
629 state = 0;
630 ioctlsocket( conn->socket, FIONBIO, &state );
632 if (!ret)
634 WARN("unable to connect to host (%d)\n", res);
635 set_last_error( res );
637 return ret;
640 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
642 #ifdef SONAME_LIBSSL
643 if (!(conn->ssl_conn = pSSL_new( ctx )))
645 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
646 set_last_error( ERROR_OUTOFMEMORY );
647 goto fail;
649 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
651 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
652 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
653 goto fail;
655 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
657 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
658 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
659 return FALSE;
661 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
663 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
664 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
665 goto fail;
667 if (pSSL_connect( conn->ssl_conn ) <= 0)
669 DWORD err;
671 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
672 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
673 ERR("couldn't verify server certificate (%d)\n", err);
674 set_last_error( err );
675 goto fail;
677 TRACE("established SSL connection\n");
678 conn->secure = TRUE;
679 return TRUE;
681 fail:
682 if (conn->ssl_conn)
684 pSSL_shutdown( conn->ssl_conn );
685 pSSL_free( conn->ssl_conn );
686 conn->ssl_conn = NULL;
688 #endif
689 return FALSE;
692 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
694 if (!netconn_connected( conn )) return FALSE;
695 if (conn->secure)
697 #ifdef SONAME_LIBSSL
698 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
699 *sent = pSSL_write( conn->ssl_conn, msg, len );
700 if (*sent < 1 && len) return FALSE;
701 return TRUE;
702 #else
703 return FALSE;
704 #endif
706 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
708 set_last_error( sock_get_error( errno ) );
709 return FALSE;
711 return TRUE;
714 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
716 *recvd = 0;
717 if (!netconn_connected( conn )) return FALSE;
718 if (!len) return TRUE;
720 if (conn->secure)
722 #ifdef SONAME_LIBSSL
723 if (flags & ~(MSG_PEEK | MSG_WAITALL))
724 FIXME("SSL_read does not support the following flags: %08x\n", flags);
726 /* this ugly hack is all for MSG_PEEK */
727 if (flags & MSG_PEEK && !conn->peek_msg)
729 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
731 else if (flags & MSG_PEEK && conn->peek_msg)
733 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
734 *recvd = min( len, conn->peek_len );
735 memcpy( buf, conn->peek_msg, *recvd );
736 return TRUE;
738 else if (conn->peek_msg)
740 *recvd = min( len, conn->peek_len );
741 memcpy( buf, conn->peek_msg, *recvd );
742 conn->peek_len -= *recvd;
743 conn->peek_msg += *recvd;
745 if (conn->peek_len == 0)
747 heap_free( conn->peek_msg_mem );
748 conn->peek_msg_mem = NULL;
749 conn->peek_msg = NULL;
751 /* check if we have enough data from the peek buffer */
752 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
754 *recvd += pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
755 if (flags & MSG_PEEK) /* must copy into buffer */
757 conn->peek_len = *recvd;
758 if (!*recvd)
760 heap_free( conn->peek_msg_mem );
761 conn->peek_msg_mem = NULL;
762 conn->peek_msg = NULL;
764 else memcpy( conn->peek_msg, buf, *recvd );
766 if (*recvd < 1) return FALSE;
767 return TRUE;
768 #else
769 return FALSE;
770 #endif
772 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
774 set_last_error( sock_get_error( errno ) );
775 return FALSE;
777 return TRUE;
780 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
782 #ifdef FIONREAD
783 int ret, unread;
784 #endif
785 *available = 0;
786 if (!netconn_connected( conn )) return FALSE;
788 if (conn->secure)
790 #ifdef SONAME_LIBSSL
791 if (conn->peek_msg) *available = conn->peek_len;
792 #endif
793 return TRUE;
795 #ifdef FIONREAD
796 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
797 #endif
798 return TRUE;
801 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
803 struct pollfd pfd;
804 BOOL ret = FALSE;
805 DWORD recvd = 0;
807 if (!netconn_connected( conn )) return FALSE;
809 if (conn->secure)
811 #ifdef SONAME_LIBSSL
812 while (recvd < *buflen)
814 int dummy;
815 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
817 set_last_error( ERROR_CONNECTION_ABORTED );
818 break;
820 if (buffer[recvd] == '\n')
822 ret = TRUE;
823 break;
825 if (buffer[recvd] != '\r') recvd++;
827 if (ret)
829 buffer[recvd++] = 0;
830 *buflen = recvd;
831 TRACE("received line %s\n", debugstr_a(buffer));
833 return ret;
834 #else
835 return FALSE;
836 #endif
839 pfd.fd = conn->socket;
840 pfd.events = POLLIN;
841 while (recvd < *buflen)
843 int timeout, res;
844 struct timeval tv;
845 socklen_t len = sizeof(tv);
847 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
848 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
849 else
850 timeout = -1;
851 if (poll( &pfd, 1, timeout ) > 0)
853 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
855 if (res == -1) set_last_error( sock_get_error( errno ) );
856 break;
858 if (buffer[recvd] == '\n')
860 ret = TRUE;
861 break;
863 if (buffer[recvd] != '\r') recvd++;
865 else
867 set_last_error( ERROR_WINHTTP_TIMEOUT );
868 break;
871 if (ret)
873 buffer[recvd++] = 0;
874 *buflen = recvd;
875 TRACE("received line %s\n", debugstr_a(buffer));
877 return ret;
880 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
882 int res;
883 struct timeval tv;
885 /* value is in milliseconds, convert to struct timeval */
886 tv.tv_sec = value / 1000;
887 tv.tv_usec = (value % 1000) * 1000;
889 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
891 WARN("setsockopt failed (%s)\n", strerror( errno ));
892 return sock_get_error( errno );
894 return ERROR_SUCCESS;
897 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
899 char *hostname;
900 #ifdef HAVE_GETADDRINFO
901 struct addrinfo *res, hints;
902 int ret;
903 #else
904 struct hostent *he;
905 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
906 #endif
908 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
910 #ifdef HAVE_GETADDRINFO
911 memset( &hints, 0, sizeof(struct addrinfo) );
912 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
913 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
915 hints.ai_family = AF_INET;
917 ret = getaddrinfo( hostname, NULL, &hints, &res );
918 if (ret != 0)
920 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
921 hints.ai_family = AF_INET6;
922 ret = getaddrinfo( hostname, NULL, &hints, &res );
923 if (ret != 0)
925 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
926 heap_free( hostname );
927 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
930 heap_free( hostname );
931 if (*sa_len < res->ai_addrlen)
933 WARN("address too small\n");
934 freeaddrinfo( res );
935 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
937 *sa_len = res->ai_addrlen;
938 memcpy( sa, res->ai_addr, res->ai_addrlen );
939 /* Copy port */
940 switch (res->ai_family)
942 case AF_INET:
943 ((struct sockaddr_in *)sa)->sin_port = htons( port );
944 break;
945 case AF_INET6:
946 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
947 break;
950 freeaddrinfo( res );
951 return ERROR_SUCCESS;
952 #else
953 EnterCriticalSection( &cs_gethostbyname );
955 he = gethostbyname( hostname );
956 heap_free( hostname );
957 if (!he)
959 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
960 LeaveCriticalSection( &cs_gethostbyname );
961 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
963 if (*sa_len < sizeof(struct sockaddr_in))
965 WARN("address too small\n");
966 LeaveCriticalSection( &cs_gethostbyname );
967 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
969 *sa_len = sizeof(struct sockaddr_in);
970 memset( sa, 0, sizeof(struct sockaddr_in) );
971 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
972 sin->sin_family = he->h_addrtype;
973 sin->sin_port = htons( port );
975 LeaveCriticalSection( &cs_gethostbyname );
976 return ERROR_SUCCESS;
977 #endif
980 struct resolve_args
982 WCHAR *hostname;
983 INTERNET_PORT port;
984 struct sockaddr *sa;
985 socklen_t *sa_len;
988 static DWORD CALLBACK resolve_proc( LPVOID arg )
990 struct resolve_args *ra = arg;
991 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
994 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
996 DWORD ret;
998 if (timeout)
1000 DWORD status;
1001 HANDLE thread;
1002 struct resolve_args ra;
1004 ra.hostname = hostname;
1005 ra.port = port;
1006 ra.sa = sa;
1007 ra.sa_len = sa_len;
1009 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1010 if (!thread) return FALSE;
1012 status = WaitForSingleObject( thread, timeout );
1013 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1014 else ret = ERROR_WINHTTP_TIMEOUT;
1015 CloseHandle( thread );
1017 else ret = resolve_hostname( hostname, port, sa, sa_len );
1019 if (ret)
1021 set_last_error( ret );
1022 return FALSE;
1024 return TRUE;
1027 const void *netconn_get_certificate( netconn_t *conn )
1029 #ifdef SONAME_LIBSSL
1030 X509 *cert;
1031 const CERT_CONTEXT *ret;
1033 if (!conn->secure) return NULL;
1035 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1036 ret = X509_to_cert_context( cert );
1037 return ret;
1038 #else
1039 return NULL;
1040 #endif