winhttp: Fix const qualifier warning for OpenSSL 1.0.0.
[wine/multimedia.git] / dlls / winhttp / net.c
blob7826fbbcc3ab7a3dae37ca2fd36f3caf4dceb308
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 );
127 MAKE_FUNCPTR( SSL_get_current_cipher );
128 MAKE_FUNCPTR( SSL_CIPHER_get_bits );
130 MAKE_FUNCPTR( CRYPTO_num_locks );
131 MAKE_FUNCPTR( CRYPTO_set_id_callback );
132 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
133 MAKE_FUNCPTR( ERR_free_strings );
134 MAKE_FUNCPTR( ERR_get_error );
135 MAKE_FUNCPTR( ERR_error_string );
136 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
137 MAKE_FUNCPTR( i2d_X509 );
138 MAKE_FUNCPTR( sk_value );
139 MAKE_FUNCPTR( sk_num );
140 #undef MAKE_FUNCPTR
142 static CRITICAL_SECTION *ssl_locks;
143 static unsigned int num_ssl_locks;
145 static unsigned long ssl_thread_id(void)
147 return GetCurrentThreadId();
150 static void ssl_lock_callback(int mode, int type, const char *file, int line)
152 if (mode & CRYPTO_LOCK)
153 EnterCriticalSection( &ssl_locks[type] );
154 else
155 LeaveCriticalSection( &ssl_locks[type] );
158 #endif
160 /* translate a unix error code into a winsock error code */
161 static int sock_get_error( int err )
163 #if !defined(__MINGW32__) && !defined (_MSC_VER)
164 switch (err)
166 case EINTR: return WSAEINTR;
167 case EBADF: return WSAEBADF;
168 case EPERM:
169 case EACCES: return WSAEACCES;
170 case EFAULT: return WSAEFAULT;
171 case EINVAL: return WSAEINVAL;
172 case EMFILE: return WSAEMFILE;
173 case EWOULDBLOCK: return WSAEWOULDBLOCK;
174 case EINPROGRESS: return WSAEINPROGRESS;
175 case EALREADY: return WSAEALREADY;
176 case ENOTSOCK: return WSAENOTSOCK;
177 case EDESTADDRREQ: return WSAEDESTADDRREQ;
178 case EMSGSIZE: return WSAEMSGSIZE;
179 case EPROTOTYPE: return WSAEPROTOTYPE;
180 case ENOPROTOOPT: return WSAENOPROTOOPT;
181 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
182 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
183 case EOPNOTSUPP: return WSAEOPNOTSUPP;
184 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
185 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
186 case EADDRINUSE: return WSAEADDRINUSE;
187 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
188 case ENETDOWN: return WSAENETDOWN;
189 case ENETUNREACH: return WSAENETUNREACH;
190 case ENETRESET: return WSAENETRESET;
191 case ECONNABORTED: return WSAECONNABORTED;
192 case EPIPE:
193 case ECONNRESET: return WSAECONNRESET;
194 case ENOBUFS: return WSAENOBUFS;
195 case EISCONN: return WSAEISCONN;
196 case ENOTCONN: return WSAENOTCONN;
197 case ESHUTDOWN: return WSAESHUTDOWN;
198 case ETOOMANYREFS: return WSAETOOMANYREFS;
199 case ETIMEDOUT: return WSAETIMEDOUT;
200 case ECONNREFUSED: return WSAECONNREFUSED;
201 case ELOOP: return WSAELOOP;
202 case ENAMETOOLONG: return WSAENAMETOOLONG;
203 case EHOSTDOWN: return WSAEHOSTDOWN;
204 case EHOSTUNREACH: return WSAEHOSTUNREACH;
205 case ENOTEMPTY: return WSAENOTEMPTY;
206 #ifdef EPROCLIM
207 case EPROCLIM: return WSAEPROCLIM;
208 #endif
209 #ifdef EUSERS
210 case EUSERS: return WSAEUSERS;
211 #endif
212 #ifdef EDQUOT
213 case EDQUOT: return WSAEDQUOT;
214 #endif
215 #ifdef ESTALE
216 case ESTALE: return WSAESTALE;
217 #endif
218 #ifdef EREMOTE
219 case EREMOTE: return WSAEREMOTE;
220 #endif
221 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
223 #endif
224 return err;
227 #ifdef SONAME_LIBSSL
228 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
230 unsigned char *buffer, *p;
231 int len;
232 BOOL malloc = FALSE;
233 PCCERT_CONTEXT ret;
235 p = NULL;
236 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
238 * SSL 0.9.7 and above malloc the buffer if it is null.
239 * however earlier version do not and so we would need to alloc the buffer.
241 * see the i2d_X509 man page for more details.
243 if (!p)
245 if (!(buffer = heap_alloc( len ))) return NULL;
246 p = buffer;
247 len = pi2d_X509( cert, &p );
249 else
251 buffer = p;
252 malloc = TRUE;
255 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
257 if (malloc) free( buffer );
258 else heap_free( buffer );
260 return ret;
263 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
264 WCHAR *server, DWORD security_flags )
266 BOOL ret;
267 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
268 PCCERT_CHAIN_CONTEXT chain;
269 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
270 char *server_auth[] = { oid_server_auth };
271 DWORD err = ERROR_SUCCESS;
273 TRACE("verifying %s\n", debugstr_w( server ));
274 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
275 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
276 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
277 NULL, &chain )))
279 if (chain->TrustStatus.dwErrorStatus)
281 static const DWORD supportedErrors =
282 CERT_TRUST_IS_NOT_TIME_VALID |
283 CERT_TRUST_IS_UNTRUSTED_ROOT |
284 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
286 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
288 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
289 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
291 else if (chain->TrustStatus.dwErrorStatus &
292 CERT_TRUST_IS_UNTRUSTED_ROOT)
294 if (!(security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA))
295 err = ERROR_WINHTTP_SECURE_INVALID_CA;
297 else if ((chain->TrustStatus.dwErrorStatus &
298 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
299 (chain->TrustStatus.dwErrorStatus &
300 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
301 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
302 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
303 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
304 else if (chain->TrustStatus.dwErrorStatus &
305 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
307 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
308 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
310 else if (chain->TrustStatus.dwErrorStatus & ~supportedErrors)
311 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
313 if (!err)
315 CERT_CHAIN_POLICY_PARA policyPara;
316 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
317 CERT_CHAIN_POLICY_STATUS policyStatus;
318 CERT_CHAIN_CONTEXT chainCopy;
320 /* Clear chain->TrustStatus.dwErrorStatus so
321 * CertVerifyCertificateChainPolicy will verify additional checks
322 * rather than stopping with an existing, ignored error.
324 memcpy(&chainCopy, chain, sizeof(chainCopy));
325 chainCopy.TrustStatus.dwErrorStatus = 0;
326 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
327 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
328 sslExtraPolicyPara.pwszServerName = server;
329 sslExtraPolicyPara.fdwChecks = security_flags;
330 policyPara.cbSize = sizeof(policyPara);
331 policyPara.dwFlags = 0;
332 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
333 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
334 &chainCopy, &policyPara,
335 &policyStatus );
336 /* Any error in the policy status indicates that the
337 * policy couldn't be verified.
339 if (ret && policyStatus.dwError)
341 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
342 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 LOAD_FUNCPTR( SSL_get_current_cipher );
468 LOAD_FUNCPTR( SSL_CIPHER_get_bits );
469 #undef LOAD_FUNCPTR
471 #define LOAD_FUNCPTR(x) \
472 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
474 ERR("Failed to load symbol %s\n", #x); \
475 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
476 LeaveCriticalSection( &init_ssl_cs ); \
477 return FALSE; \
479 LOAD_FUNCPTR( CRYPTO_num_locks );
480 LOAD_FUNCPTR( CRYPTO_set_id_callback );
481 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
482 LOAD_FUNCPTR( ERR_free_strings );
483 LOAD_FUNCPTR( ERR_get_error );
484 LOAD_FUNCPTR( ERR_error_string );
485 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
486 LOAD_FUNCPTR( i2d_X509 );
487 LOAD_FUNCPTR( sk_value );
488 LOAD_FUNCPTR( sk_num );
489 #undef LOAD_FUNCPTR
491 pSSL_library_init();
492 pSSL_load_error_strings();
494 method = pSSLv23_method();
495 ctx = pSSL_CTX_new( method );
496 if (!pSSL_CTX_set_default_verify_paths( ctx ))
498 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
499 set_last_error( ERROR_OUTOFMEMORY );
500 LeaveCriticalSection( &init_ssl_cs );
501 return FALSE;
503 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
504 if (hostname_idx == -1)
506 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
507 set_last_error( ERROR_OUTOFMEMORY );
508 LeaveCriticalSection( &init_ssl_cs );
509 return FALSE;
511 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
512 if (error_idx == -1)
514 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
515 set_last_error( ERROR_OUTOFMEMORY );
516 LeaveCriticalSection( &init_ssl_cs );
517 return FALSE;
519 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
520 if (conn_idx == -1)
522 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
523 set_last_error( ERROR_OUTOFMEMORY );
524 LeaveCriticalSection( &init_ssl_cs );
525 return FALSE;
527 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
529 pCRYPTO_set_id_callback(ssl_thread_id);
530 num_ssl_locks = pCRYPTO_num_locks();
531 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
532 if (!ssl_locks)
534 set_last_error( ERROR_OUTOFMEMORY );
535 LeaveCriticalSection( &init_ssl_cs );
536 return FALSE;
538 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
539 pCRYPTO_set_locking_callback(ssl_lock_callback);
541 LeaveCriticalSection( &init_ssl_cs );
542 #else
543 WARN("SSL support not compiled in.\n");
544 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
545 return FALSE;
546 #endif
547 return TRUE;
550 void netconn_unload( void )
552 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
553 if (libcrypto_handle)
555 pERR_free_strings();
556 wine_dlclose( libcrypto_handle, NULL, 0 );
558 if (libssl_handle)
560 if (ctx)
561 pSSL_CTX_free( ctx );
562 wine_dlclose( libssl_handle, NULL, 0 );
564 if (ssl_locks)
566 int i;
567 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
568 HeapFree( GetProcessHeap(), 0, ssl_locks );
570 #endif
573 BOOL netconn_connected( netconn_t *conn )
575 return (conn->socket != -1);
578 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
580 if ((conn->socket = socket( domain, type, protocol )) == -1)
582 WARN("unable to create socket (%s)\n", strerror(errno));
583 set_last_error( sock_get_error( errno ) );
584 return FALSE;
586 return TRUE;
589 BOOL netconn_close( netconn_t *conn )
591 int res;
593 #ifdef SONAME_LIBSSL
594 if (conn->secure)
596 heap_free( conn->peek_msg_mem );
597 conn->peek_msg_mem = NULL;
598 conn->peek_msg = NULL;
599 conn->peek_len = 0;
601 pSSL_shutdown( conn->ssl_conn );
602 pSSL_free( conn->ssl_conn );
604 conn->ssl_conn = NULL;
605 conn->secure = FALSE;
607 #endif
608 res = closesocket( conn->socket );
609 conn->socket = -1;
610 if (res == -1)
612 set_last_error( sock_get_error( errno ) );
613 return FALSE;
615 return TRUE;
618 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
620 BOOL ret = FALSE;
621 int res = 0, state;
623 if (timeout > 0)
625 state = 1;
626 ioctlsocket( conn->socket, FIONBIO, &state );
628 if (connect( conn->socket, sockaddr, addr_len ) < 0)
630 res = sock_get_error( errno );
631 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
633 struct pollfd pfd;
635 pfd.fd = conn->socket;
636 pfd.events = POLLOUT;
637 if (poll( &pfd, 1, timeout ) > 0)
638 ret = TRUE;
639 else
640 res = sock_get_error( errno );
643 else
644 ret = TRUE;
645 if (timeout > 0)
647 state = 0;
648 ioctlsocket( conn->socket, FIONBIO, &state );
650 if (!ret)
652 WARN("unable to connect to host (%d)\n", res);
653 set_last_error( res );
655 return ret;
658 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
660 #ifdef SONAME_LIBSSL
661 if (!(conn->ssl_conn = pSSL_new( ctx )))
663 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
664 set_last_error( ERROR_OUTOFMEMORY );
665 goto fail;
667 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
669 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
670 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
671 goto fail;
673 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
675 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
676 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
677 return FALSE;
679 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
681 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
682 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
683 goto fail;
685 if (pSSL_connect( conn->ssl_conn ) <= 0)
687 DWORD err;
689 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
690 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
691 ERR("couldn't verify server certificate (%d)\n", err);
692 set_last_error( err );
693 goto fail;
695 TRACE("established SSL connection\n");
696 conn->secure = TRUE;
697 return TRUE;
699 fail:
700 if (conn->ssl_conn)
702 pSSL_shutdown( conn->ssl_conn );
703 pSSL_free( conn->ssl_conn );
704 conn->ssl_conn = NULL;
706 #endif
707 return FALSE;
710 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
712 if (!netconn_connected( conn )) return FALSE;
713 if (conn->secure)
715 #ifdef SONAME_LIBSSL
716 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
717 *sent = pSSL_write( conn->ssl_conn, msg, len );
718 if (*sent < 1 && len) return FALSE;
719 return TRUE;
720 #else
721 return FALSE;
722 #endif
724 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
726 set_last_error( sock_get_error( errno ) );
727 return FALSE;
729 return TRUE;
732 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
734 int ret;
736 *recvd = 0;
737 if (!netconn_connected( conn )) return FALSE;
738 if (!len) return TRUE;
740 if (conn->secure)
742 #ifdef SONAME_LIBSSL
743 if (flags & ~(MSG_PEEK | MSG_WAITALL))
744 FIXME("SSL_read does not support the following flags: %08x\n", flags);
746 /* this ugly hack is all for MSG_PEEK */
747 if (flags & MSG_PEEK && !conn->peek_msg)
749 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
751 else if (flags & MSG_PEEK && conn->peek_msg)
753 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
754 *recvd = min( len, conn->peek_len );
755 memcpy( buf, conn->peek_msg, *recvd );
756 return TRUE;
758 else if (conn->peek_msg)
760 *recvd = min( len, conn->peek_len );
761 memcpy( buf, conn->peek_msg, *recvd );
762 conn->peek_len -= *recvd;
763 conn->peek_msg += *recvd;
765 if (conn->peek_len == 0)
767 heap_free( conn->peek_msg_mem );
768 conn->peek_msg_mem = NULL;
769 conn->peek_msg = NULL;
771 /* check if we have enough data from the peek buffer */
772 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
774 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
775 if (ret < 0)
776 return FALSE;
778 /* check if EOF was received */
779 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
780 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
782 netconn_close( conn );
783 return TRUE;
785 if (flags & MSG_PEEK) /* must copy into buffer */
787 conn->peek_len = ret;
788 if (!ret)
790 heap_free( conn->peek_msg_mem );
791 conn->peek_msg_mem = NULL;
792 conn->peek_msg = NULL;
794 else memcpy( conn->peek_msg, buf, ret );
796 *recvd = ret;
797 return TRUE;
798 #else
799 return FALSE;
800 #endif
802 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
804 set_last_error( sock_get_error( errno ) );
805 return FALSE;
807 return TRUE;
810 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
812 #ifdef FIONREAD
813 int ret, unread;
814 #endif
815 *available = 0;
816 if (!netconn_connected( conn )) return FALSE;
818 if (conn->secure)
820 #ifdef SONAME_LIBSSL
821 if (conn->peek_msg) *available = conn->peek_len;
822 #endif
823 return TRUE;
825 #ifdef FIONREAD
826 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
827 #endif
828 return TRUE;
831 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
833 struct pollfd pfd;
834 BOOL ret = FALSE;
835 DWORD recvd = 0;
837 if (!netconn_connected( conn )) return FALSE;
839 if (conn->secure)
841 #ifdef SONAME_LIBSSL
842 while (recvd < *buflen)
844 int dummy;
845 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
847 set_last_error( ERROR_CONNECTION_ABORTED );
848 break;
850 if (buffer[recvd] == '\n')
852 ret = TRUE;
853 break;
855 if (buffer[recvd] != '\r') recvd++;
857 if (ret)
859 buffer[recvd++] = 0;
860 *buflen = recvd;
861 TRACE("received line %s\n", debugstr_a(buffer));
863 return ret;
864 #else
865 return FALSE;
866 #endif
869 pfd.fd = conn->socket;
870 pfd.events = POLLIN;
871 while (recvd < *buflen)
873 int timeout, res;
874 struct timeval tv;
875 socklen_t len = sizeof(tv);
877 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
878 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
879 else
880 timeout = -1;
881 if (poll( &pfd, 1, timeout ) > 0)
883 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
885 if (res == -1) set_last_error( sock_get_error( errno ) );
886 break;
888 if (buffer[recvd] == '\n')
890 ret = TRUE;
891 break;
893 if (buffer[recvd] != '\r') recvd++;
895 else
897 set_last_error( ERROR_WINHTTP_TIMEOUT );
898 break;
901 if (ret)
903 buffer[recvd++] = 0;
904 *buflen = recvd;
905 TRACE("received line %s\n", debugstr_a(buffer));
907 return ret;
910 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
912 int res;
913 struct timeval tv;
915 /* value is in milliseconds, convert to struct timeval */
916 tv.tv_sec = value / 1000;
917 tv.tv_usec = (value % 1000) * 1000;
919 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
921 WARN("setsockopt failed (%s)\n", strerror( errno ));
922 return sock_get_error( errno );
924 return ERROR_SUCCESS;
927 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
929 char *hostname;
930 #ifdef HAVE_GETADDRINFO
931 struct addrinfo *res, hints;
932 int ret;
933 #else
934 struct hostent *he;
935 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
936 #endif
938 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
940 #ifdef HAVE_GETADDRINFO
941 memset( &hints, 0, sizeof(struct addrinfo) );
942 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
943 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
945 hints.ai_family = AF_INET;
947 ret = getaddrinfo( hostname, NULL, &hints, &res );
948 if (ret != 0)
950 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
951 hints.ai_family = AF_INET6;
952 ret = getaddrinfo( hostname, NULL, &hints, &res );
953 if (ret != 0)
955 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
956 heap_free( hostname );
957 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
960 heap_free( hostname );
961 if (*sa_len < res->ai_addrlen)
963 WARN("address too small\n");
964 freeaddrinfo( res );
965 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
967 *sa_len = res->ai_addrlen;
968 memcpy( sa, res->ai_addr, res->ai_addrlen );
969 /* Copy port */
970 switch (res->ai_family)
972 case AF_INET:
973 ((struct sockaddr_in *)sa)->sin_port = htons( port );
974 break;
975 case AF_INET6:
976 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
977 break;
980 freeaddrinfo( res );
981 return ERROR_SUCCESS;
982 #else
983 EnterCriticalSection( &cs_gethostbyname );
985 he = gethostbyname( hostname );
986 heap_free( hostname );
987 if (!he)
989 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
990 LeaveCriticalSection( &cs_gethostbyname );
991 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
993 if (*sa_len < sizeof(struct sockaddr_in))
995 WARN("address too small\n");
996 LeaveCriticalSection( &cs_gethostbyname );
997 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
999 *sa_len = sizeof(struct sockaddr_in);
1000 memset( sa, 0, sizeof(struct sockaddr_in) );
1001 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
1002 sin->sin_family = he->h_addrtype;
1003 sin->sin_port = htons( port );
1005 LeaveCriticalSection( &cs_gethostbyname );
1006 return ERROR_SUCCESS;
1007 #endif
1010 struct resolve_args
1012 WCHAR *hostname;
1013 INTERNET_PORT port;
1014 struct sockaddr *sa;
1015 socklen_t *sa_len;
1018 static DWORD CALLBACK resolve_proc( LPVOID arg )
1020 struct resolve_args *ra = arg;
1021 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1024 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1026 DWORD ret;
1028 if (timeout)
1030 DWORD status;
1031 HANDLE thread;
1032 struct resolve_args ra;
1034 ra.hostname = hostname;
1035 ra.port = port;
1036 ra.sa = sa;
1037 ra.sa_len = sa_len;
1039 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1040 if (!thread) return FALSE;
1042 status = WaitForSingleObject( thread, timeout );
1043 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1044 else ret = ERROR_WINHTTP_TIMEOUT;
1045 CloseHandle( thread );
1047 else ret = resolve_hostname( hostname, port, sa, sa_len );
1049 if (ret)
1051 set_last_error( ret );
1052 return FALSE;
1054 return TRUE;
1057 const void *netconn_get_certificate( netconn_t *conn )
1059 #ifdef SONAME_LIBSSL
1060 X509 *cert;
1061 const CERT_CONTEXT *ret;
1063 if (!conn->secure) return NULL;
1065 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1066 ret = X509_to_cert_context( cert );
1067 return ret;
1068 #else
1069 return NULL;
1070 #endif
1073 int netconn_get_cipher_strength( netconn_t *conn )
1075 #ifdef SONAME_LIBSSL
1076 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1077 const SSL_CIPHER *cipher;
1078 #else
1079 SSL_CIPHER *cipher;
1080 #endif
1081 int bits = 0;
1083 if (!conn->secure) return 0;
1084 if (!(cipher = pSSL_get_current_cipher( conn->ssl_conn ))) return 0;
1085 pSSL_CIPHER_get_bits( cipher, &bits );
1086 return bits;
1087 #else
1088 return 0;
1089 #endif