crypt32: Update Italian translation.
[wine/multimedia.git] / dlls / winhttp / net.c
blob573f108a7db0bfb787a0fd77c495231fb9c53cb0
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_verify_result );
125 MAKE_FUNCPTR( SSL_get_peer_certificate );
126 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
127 MAKE_FUNCPTR( SSL_CTX_set_verify );
129 MAKE_FUNCPTR( CRYPTO_num_locks );
130 MAKE_FUNCPTR( CRYPTO_set_id_callback );
131 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
132 MAKE_FUNCPTR( ERR_free_strings );
133 MAKE_FUNCPTR( ERR_get_error );
134 MAKE_FUNCPTR( ERR_error_string );
135 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
136 MAKE_FUNCPTR( i2d_X509 );
137 MAKE_FUNCPTR( sk_value );
138 MAKE_FUNCPTR( sk_num );
139 #undef MAKE_FUNCPTR
141 static CRITICAL_SECTION *ssl_locks;
142 static unsigned int num_ssl_locks;
144 static unsigned long ssl_thread_id(void)
146 return GetCurrentThreadId();
149 static void ssl_lock_callback(int mode, int type, const char *file, int line)
151 if (mode & CRYPTO_LOCK)
152 EnterCriticalSection( &ssl_locks[type] );
153 else
154 LeaveCriticalSection( &ssl_locks[type] );
157 #endif
159 /* translate a unix error code into a winsock error code */
160 static int sock_get_error( int err )
162 #if !defined(__MINGW32__) && !defined (_MSC_VER)
163 switch (err)
165 case EINTR: return WSAEINTR;
166 case EBADF: return WSAEBADF;
167 case EPERM:
168 case EACCES: return WSAEACCES;
169 case EFAULT: return WSAEFAULT;
170 case EINVAL: return WSAEINVAL;
171 case EMFILE: return WSAEMFILE;
172 case EWOULDBLOCK: return WSAEWOULDBLOCK;
173 case EINPROGRESS: return WSAEINPROGRESS;
174 case EALREADY: return WSAEALREADY;
175 case ENOTSOCK: return WSAENOTSOCK;
176 case EDESTADDRREQ: return WSAEDESTADDRREQ;
177 case EMSGSIZE: return WSAEMSGSIZE;
178 case EPROTOTYPE: return WSAEPROTOTYPE;
179 case ENOPROTOOPT: return WSAENOPROTOOPT;
180 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
181 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
182 case EOPNOTSUPP: return WSAEOPNOTSUPP;
183 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
184 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
185 case EADDRINUSE: return WSAEADDRINUSE;
186 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
187 case ENETDOWN: return WSAENETDOWN;
188 case ENETUNREACH: return WSAENETUNREACH;
189 case ENETRESET: return WSAENETRESET;
190 case ECONNABORTED: return WSAECONNABORTED;
191 case EPIPE:
192 case ECONNRESET: return WSAECONNRESET;
193 case ENOBUFS: return WSAENOBUFS;
194 case EISCONN: return WSAEISCONN;
195 case ENOTCONN: return WSAENOTCONN;
196 case ESHUTDOWN: return WSAESHUTDOWN;
197 case ETOOMANYREFS: return WSAETOOMANYREFS;
198 case ETIMEDOUT: return WSAETIMEDOUT;
199 case ECONNREFUSED: return WSAECONNREFUSED;
200 case ELOOP: return WSAELOOP;
201 case ENAMETOOLONG: return WSAENAMETOOLONG;
202 case EHOSTDOWN: return WSAEHOSTDOWN;
203 case EHOSTUNREACH: return WSAEHOSTUNREACH;
204 case ENOTEMPTY: return WSAENOTEMPTY;
205 #ifdef EPROCLIM
206 case EPROCLIM: return WSAEPROCLIM;
207 #endif
208 #ifdef EUSERS
209 case EUSERS: return WSAEUSERS;
210 #endif
211 #ifdef EDQUOT
212 case EDQUOT: return WSAEDQUOT;
213 #endif
214 #ifdef ESTALE
215 case ESTALE: return WSAESTALE;
216 #endif
217 #ifdef EREMOTE
218 case EREMOTE: return WSAEREMOTE;
219 #endif
220 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
222 #endif
223 return err;
226 #ifdef SONAME_LIBSSL
227 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
229 unsigned char *buffer, *p;
230 int len;
231 BOOL malloc = FALSE;
232 PCCERT_CONTEXT ret;
234 p = NULL;
235 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
237 * SSL 0.9.7 and above malloc the buffer if it is null.
238 * however earlier version do not and so we would need to alloc the buffer.
240 * see the i2d_X509 man page for more details.
242 if (!p)
244 if (!(buffer = heap_alloc( len ))) return NULL;
245 p = buffer;
246 len = pi2d_X509( cert, &p );
248 else
250 buffer = p;
251 malloc = TRUE;
254 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
256 if (malloc) free( buffer );
257 else heap_free( buffer );
259 return ret;
262 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
263 WCHAR *server, DWORD security_flags )
265 BOOL ret;
266 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
267 PCCERT_CHAIN_CONTEXT chain;
268 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
269 char *server_auth[] = { oid_server_auth };
270 DWORD err = ERROR_SUCCESS;
272 TRACE("verifying %s\n", debugstr_w( server ));
273 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
274 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
275 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
276 NULL, &chain )))
278 if (chain->TrustStatus.dwErrorStatus)
280 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
282 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
283 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
285 else if (chain->TrustStatus.dwErrorStatus &
286 CERT_TRUST_IS_UNTRUSTED_ROOT)
287 err = ERROR_WINHTTP_SECURE_INVALID_CA;
288 else if ((chain->TrustStatus.dwErrorStatus &
289 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
290 (chain->TrustStatus.dwErrorStatus &
291 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
292 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
293 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
294 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
295 else if (chain->TrustStatus.dwErrorStatus &
296 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
298 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
299 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
301 else
302 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
304 else
306 CERT_CHAIN_POLICY_PARA policyPara;
307 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
308 CERT_CHAIN_POLICY_STATUS policyStatus;
310 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
311 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
312 sslExtraPolicyPara.pwszServerName = server;
313 policyPara.cbSize = sizeof(policyPara);
314 policyPara.dwFlags = 0;
315 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
316 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
317 chain, &policyPara,
318 &policyStatus );
319 /* Any error in the policy status indicates that the
320 * policy couldn't be verified.
322 if (ret && policyStatus.dwError)
324 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
326 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
327 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
329 else
330 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
333 CertFreeCertificateChain( chain );
335 else
336 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
337 TRACE("returning %08x\n", err);
338 return err;
341 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
343 SSL *ssl;
344 WCHAR *server;
345 BOOL ret = FALSE;
346 netconn_t *conn;
348 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
349 server = pSSL_get_ex_data( ssl, hostname_idx );
350 conn = pSSL_get_ex_data( ssl, conn_idx );
351 if (preverify_ok)
353 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
354 CERT_STORE_CREATE_NEW_FLAG, NULL );
356 if (store)
358 X509 *cert;
359 int i;
360 PCCERT_CONTEXT endCert = NULL;
362 ret = TRUE;
363 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
365 PCCERT_CONTEXT context;
367 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
368 if ((context = X509_to_cert_context( cert )))
370 if (i == 0)
371 ret = CertAddCertificateContextToStore( store, context,
372 CERT_STORE_ADD_ALWAYS, &endCert );
373 else
374 ret = CertAddCertificateContextToStore( store, context,
375 CERT_STORE_ADD_ALWAYS, NULL );
376 CertFreeCertificateContext( context );
379 if (!endCert) ret = FALSE;
380 if (ret)
382 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
383 conn->security_flags );
385 if (err)
387 pSSL_set_ex_data( ssl, error_idx, (void *)err );
388 ret = FALSE;
391 CertFreeCertificateContext( endCert );
392 CertCloseStore( store, 0 );
395 return ret;
397 #endif
399 BOOL netconn_init( netconn_t *conn, BOOL secure )
401 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
402 int i;
403 #endif
405 conn->socket = -1;
406 if (!secure) return TRUE;
408 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
409 EnterCriticalSection( &init_ssl_cs );
410 if (libssl_handle)
412 LeaveCriticalSection( &init_ssl_cs );
413 return TRUE;
415 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
417 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
418 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
419 LeaveCriticalSection( &init_ssl_cs );
420 return FALSE;
422 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
424 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
425 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
426 LeaveCriticalSection( &init_ssl_cs );
427 return FALSE;
429 #define LOAD_FUNCPTR(x) \
430 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
432 ERR("Failed to load symbol %s\n", #x); \
433 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
434 LeaveCriticalSection( &init_ssl_cs ); \
435 return FALSE; \
437 LOAD_FUNCPTR( SSL_library_init );
438 LOAD_FUNCPTR( SSL_load_error_strings );
439 LOAD_FUNCPTR( SSLv23_method );
440 LOAD_FUNCPTR( SSL_CTX_free );
441 LOAD_FUNCPTR( SSL_CTX_new );
442 LOAD_FUNCPTR( SSL_new );
443 LOAD_FUNCPTR( SSL_free );
444 LOAD_FUNCPTR( SSL_set_fd );
445 LOAD_FUNCPTR( SSL_connect );
446 LOAD_FUNCPTR( SSL_shutdown );
447 LOAD_FUNCPTR( SSL_write );
448 LOAD_FUNCPTR( SSL_read );
449 LOAD_FUNCPTR( SSL_get_error );
450 LOAD_FUNCPTR( SSL_get_ex_new_index );
451 LOAD_FUNCPTR( SSL_get_ex_data );
452 LOAD_FUNCPTR( SSL_set_ex_data );
453 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
454 LOAD_FUNCPTR( SSL_get_verify_result );
455 LOAD_FUNCPTR( SSL_get_peer_certificate );
456 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
457 LOAD_FUNCPTR( SSL_CTX_set_verify );
458 #undef LOAD_FUNCPTR
460 #define LOAD_FUNCPTR(x) \
461 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
463 ERR("Failed to load symbol %s\n", #x); \
464 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
465 LeaveCriticalSection( &init_ssl_cs ); \
466 return FALSE; \
468 LOAD_FUNCPTR( CRYPTO_num_locks );
469 LOAD_FUNCPTR( CRYPTO_set_id_callback );
470 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
471 LOAD_FUNCPTR( ERR_free_strings );
472 LOAD_FUNCPTR( ERR_get_error );
473 LOAD_FUNCPTR( ERR_error_string );
474 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
475 LOAD_FUNCPTR( i2d_X509 );
476 LOAD_FUNCPTR( sk_value );
477 LOAD_FUNCPTR( sk_num );
478 #undef LOAD_FUNCPTR
480 pSSL_library_init();
481 pSSL_load_error_strings();
483 method = pSSLv23_method();
484 ctx = pSSL_CTX_new( method );
485 if (!pSSL_CTX_set_default_verify_paths( ctx ))
487 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
488 set_last_error( ERROR_OUTOFMEMORY );
489 LeaveCriticalSection( &init_ssl_cs );
490 return FALSE;
492 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
493 if (hostname_idx == -1)
495 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
496 set_last_error( ERROR_OUTOFMEMORY );
497 LeaveCriticalSection( &init_ssl_cs );
498 return FALSE;
500 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
501 if (error_idx == -1)
503 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
504 set_last_error( ERROR_OUTOFMEMORY );
505 LeaveCriticalSection( &init_ssl_cs );
506 return FALSE;
508 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
509 if (conn_idx == -1)
511 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
512 set_last_error( ERROR_OUTOFMEMORY );
513 LeaveCriticalSection( &init_ssl_cs );
514 return FALSE;
516 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
518 pCRYPTO_set_id_callback(ssl_thread_id);
519 num_ssl_locks = pCRYPTO_num_locks();
520 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
521 if (!ssl_locks)
523 set_last_error( ERROR_OUTOFMEMORY );
524 LeaveCriticalSection( &init_ssl_cs );
525 return FALSE;
527 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
528 pCRYPTO_set_locking_callback(ssl_lock_callback);
530 LeaveCriticalSection( &init_ssl_cs );
531 #else
532 WARN("SSL support not compiled in.\n");
533 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
534 return FALSE;
535 #endif
536 return TRUE;
539 void netconn_unload( void )
541 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
542 if (libcrypto_handle)
544 pERR_free_strings();
545 wine_dlclose( libcrypto_handle, NULL, 0 );
547 if (libssl_handle)
549 if (ctx)
550 pSSL_CTX_free( ctx );
551 wine_dlclose( libssl_handle, NULL, 0 );
553 if (ssl_locks)
555 int i;
556 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
557 HeapFree( GetProcessHeap(), 0, ssl_locks );
559 #endif
562 BOOL netconn_connected( netconn_t *conn )
564 return (conn->socket != -1);
567 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
569 if ((conn->socket = socket( domain, type, protocol )) == -1)
571 WARN("unable to create socket (%s)\n", strerror(errno));
572 set_last_error( sock_get_error( errno ) );
573 return FALSE;
575 return TRUE;
578 BOOL netconn_close( netconn_t *conn )
580 int res;
582 #ifdef SONAME_LIBSSL
583 if (conn->secure)
585 heap_free( conn->peek_msg_mem );
586 conn->peek_msg_mem = NULL;
587 conn->peek_msg = NULL;
588 conn->peek_len = 0;
590 pSSL_shutdown( conn->ssl_conn );
591 pSSL_free( conn->ssl_conn );
593 conn->ssl_conn = NULL;
594 conn->secure = FALSE;
596 #endif
597 res = closesocket( conn->socket );
598 conn->socket = -1;
599 if (res == -1)
601 set_last_error( sock_get_error( errno ) );
602 return FALSE;
604 return TRUE;
607 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
609 BOOL ret = FALSE;
610 int res = 0, state;
612 if (timeout > 0)
614 state = 1;
615 ioctlsocket( conn->socket, FIONBIO, &state );
617 if (connect( conn->socket, sockaddr, addr_len ) < 0)
619 res = sock_get_error( errno );
620 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
622 struct pollfd pfd;
624 pfd.fd = conn->socket;
625 pfd.events = POLLOUT;
626 if (poll( &pfd, 1, timeout ) > 0)
627 ret = TRUE;
628 else
629 res = sock_get_error( errno );
632 else
633 ret = TRUE;
634 if (timeout > 0)
636 state = 0;
637 ioctlsocket( conn->socket, FIONBIO, &state );
639 if (!ret)
641 WARN("unable to connect to host (%d)\n", res);
642 set_last_error( res );
644 return ret;
647 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
649 #ifdef SONAME_LIBSSL
650 if (!(conn->ssl_conn = pSSL_new( ctx )))
652 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
653 set_last_error( ERROR_OUTOFMEMORY );
654 goto fail;
656 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
658 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
659 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
660 goto fail;
662 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
664 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
665 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
666 return FALSE;
668 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
670 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
671 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
672 goto fail;
674 if (pSSL_connect( conn->ssl_conn ) <= 0)
676 DWORD err;
678 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
679 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
680 ERR("couldn't verify server certificate (%d)\n", err);
681 set_last_error( err );
682 goto fail;
684 TRACE("established SSL connection\n");
685 conn->secure = TRUE;
686 return TRUE;
688 fail:
689 if (conn->ssl_conn)
691 pSSL_shutdown( conn->ssl_conn );
692 pSSL_free( conn->ssl_conn );
693 conn->ssl_conn = NULL;
695 #endif
696 return FALSE;
699 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
701 if (!netconn_connected( conn )) return FALSE;
702 if (conn->secure)
704 #ifdef SONAME_LIBSSL
705 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
706 *sent = pSSL_write( conn->ssl_conn, msg, len );
707 if (*sent < 1 && len) return FALSE;
708 return TRUE;
709 #else
710 return FALSE;
711 #endif
713 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
715 set_last_error( sock_get_error( errno ) );
716 return FALSE;
718 return TRUE;
721 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
723 int ret;
725 *recvd = 0;
726 if (!netconn_connected( conn )) return FALSE;
727 if (!len) return TRUE;
729 if (conn->secure)
731 #ifdef SONAME_LIBSSL
732 if (flags & ~(MSG_PEEK | MSG_WAITALL))
733 FIXME("SSL_read does not support the following flags: %08x\n", flags);
735 /* this ugly hack is all for MSG_PEEK */
736 if (flags & MSG_PEEK && !conn->peek_msg)
738 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
740 else if (flags & MSG_PEEK && conn->peek_msg)
742 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
743 *recvd = min( len, conn->peek_len );
744 memcpy( buf, conn->peek_msg, *recvd );
745 return TRUE;
747 else if (conn->peek_msg)
749 *recvd = min( len, conn->peek_len );
750 memcpy( buf, conn->peek_msg, *recvd );
751 conn->peek_len -= *recvd;
752 conn->peek_msg += *recvd;
754 if (conn->peek_len == 0)
756 heap_free( conn->peek_msg_mem );
757 conn->peek_msg_mem = NULL;
758 conn->peek_msg = NULL;
760 /* check if we have enough data from the peek buffer */
761 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
763 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
764 if (ret < 0)
765 return FALSE;
767 /* check if EOF was received */
768 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
769 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
771 netconn_close( conn );
772 return TRUE;
774 if (flags & MSG_PEEK) /* must copy into buffer */
776 conn->peek_len = ret;
777 if (!ret)
779 heap_free( conn->peek_msg_mem );
780 conn->peek_msg_mem = NULL;
781 conn->peek_msg = NULL;
783 else memcpy( conn->peek_msg, buf, ret );
785 *recvd = ret;
786 return TRUE;
787 #else
788 return FALSE;
789 #endif
791 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
793 set_last_error( sock_get_error( errno ) );
794 return FALSE;
796 return TRUE;
799 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
801 #ifdef FIONREAD
802 int ret, unread;
803 #endif
804 *available = 0;
805 if (!netconn_connected( conn )) return FALSE;
807 if (conn->secure)
809 #ifdef SONAME_LIBSSL
810 if (conn->peek_msg) *available = conn->peek_len;
811 #endif
812 return TRUE;
814 #ifdef FIONREAD
815 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
816 #endif
817 return TRUE;
820 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
822 struct pollfd pfd;
823 BOOL ret = FALSE;
824 DWORD recvd = 0;
826 if (!netconn_connected( conn )) return FALSE;
828 if (conn->secure)
830 #ifdef SONAME_LIBSSL
831 while (recvd < *buflen)
833 int dummy;
834 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
836 set_last_error( ERROR_CONNECTION_ABORTED );
837 break;
839 if (buffer[recvd] == '\n')
841 ret = TRUE;
842 break;
844 if (buffer[recvd] != '\r') recvd++;
846 if (ret)
848 buffer[recvd++] = 0;
849 *buflen = recvd;
850 TRACE("received line %s\n", debugstr_a(buffer));
852 return ret;
853 #else
854 return FALSE;
855 #endif
858 pfd.fd = conn->socket;
859 pfd.events = POLLIN;
860 while (recvd < *buflen)
862 int timeout, res;
863 struct timeval tv;
864 socklen_t len = sizeof(tv);
866 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
867 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
868 else
869 timeout = -1;
870 if (poll( &pfd, 1, timeout ) > 0)
872 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
874 if (res == -1) set_last_error( sock_get_error( errno ) );
875 break;
877 if (buffer[recvd] == '\n')
879 ret = TRUE;
880 break;
882 if (buffer[recvd] != '\r') recvd++;
884 else
886 set_last_error( ERROR_WINHTTP_TIMEOUT );
887 break;
890 if (ret)
892 buffer[recvd++] = 0;
893 *buflen = recvd;
894 TRACE("received line %s\n", debugstr_a(buffer));
896 return ret;
899 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
901 int res;
902 struct timeval tv;
904 /* value is in milliseconds, convert to struct timeval */
905 tv.tv_sec = value / 1000;
906 tv.tv_usec = (value % 1000) * 1000;
908 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
910 WARN("setsockopt failed (%s)\n", strerror( errno ));
911 return sock_get_error( errno );
913 return ERROR_SUCCESS;
916 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
918 char *hostname;
919 #ifdef HAVE_GETADDRINFO
920 struct addrinfo *res, hints;
921 int ret;
922 #else
923 struct hostent *he;
924 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
925 #endif
927 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
929 #ifdef HAVE_GETADDRINFO
930 memset( &hints, 0, sizeof(struct addrinfo) );
931 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
932 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
934 hints.ai_family = AF_INET;
936 ret = getaddrinfo( hostname, NULL, &hints, &res );
937 if (ret != 0)
939 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
940 hints.ai_family = AF_INET6;
941 ret = getaddrinfo( hostname, NULL, &hints, &res );
942 if (ret != 0)
944 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
945 heap_free( hostname );
946 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
949 heap_free( hostname );
950 if (*sa_len < res->ai_addrlen)
952 WARN("address too small\n");
953 freeaddrinfo( res );
954 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
956 *sa_len = res->ai_addrlen;
957 memcpy( sa, res->ai_addr, res->ai_addrlen );
958 /* Copy port */
959 switch (res->ai_family)
961 case AF_INET:
962 ((struct sockaddr_in *)sa)->sin_port = htons( port );
963 break;
964 case AF_INET6:
965 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
966 break;
969 freeaddrinfo( res );
970 return ERROR_SUCCESS;
971 #else
972 EnterCriticalSection( &cs_gethostbyname );
974 he = gethostbyname( hostname );
975 heap_free( hostname );
976 if (!he)
978 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
979 LeaveCriticalSection( &cs_gethostbyname );
980 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
982 if (*sa_len < sizeof(struct sockaddr_in))
984 WARN("address too small\n");
985 LeaveCriticalSection( &cs_gethostbyname );
986 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
988 *sa_len = sizeof(struct sockaddr_in);
989 memset( sa, 0, sizeof(struct sockaddr_in) );
990 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
991 sin->sin_family = he->h_addrtype;
992 sin->sin_port = htons( port );
994 LeaveCriticalSection( &cs_gethostbyname );
995 return ERROR_SUCCESS;
996 #endif
999 struct resolve_args
1001 WCHAR *hostname;
1002 INTERNET_PORT port;
1003 struct sockaddr *sa;
1004 socklen_t *sa_len;
1007 static DWORD CALLBACK resolve_proc( LPVOID arg )
1009 struct resolve_args *ra = arg;
1010 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1013 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1015 DWORD ret;
1017 if (timeout)
1019 DWORD status;
1020 HANDLE thread;
1021 struct resolve_args ra;
1023 ra.hostname = hostname;
1024 ra.port = port;
1025 ra.sa = sa;
1026 ra.sa_len = sa_len;
1028 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1029 if (!thread) return FALSE;
1031 status = WaitForSingleObject( thread, timeout );
1032 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1033 else ret = ERROR_WINHTTP_TIMEOUT;
1034 CloseHandle( thread );
1036 else ret = resolve_hostname( hostname, port, sa, sa_len );
1038 if (ret)
1040 set_last_error( ret );
1041 return FALSE;
1043 return TRUE;
1046 const void *netconn_get_certificate( netconn_t *conn )
1048 #ifdef SONAME_LIBSSL
1049 X509 *cert;
1050 const CERT_CONTEXT *ret;
1052 if (!conn->secure) return NULL;
1054 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1055 ret = X509_to_cert_context( cert );
1056 return ret;
1057 #else
1058 return NULL;
1059 #endif