shdocvw: Moved IHlinkFrame implementation to separated object.
[wine.git] / dlls / winhttp / net.c
blobe60bd16c6b06d1e164bffab4516f5bbd67513d27
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_error );
115 MAKE_FUNCPTR( SSL_get_ex_new_index );
116 MAKE_FUNCPTR( SSL_get_ex_data );
117 MAKE_FUNCPTR( SSL_set_ex_data );
118 MAKE_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
119 MAKE_FUNCPTR( SSL_get_verify_result );
120 MAKE_FUNCPTR( SSL_get_peer_certificate );
121 MAKE_FUNCPTR( SSL_CTX_set_default_verify_paths );
122 MAKE_FUNCPTR( SSL_CTX_set_verify );
124 MAKE_FUNCPTR( CRYPTO_num_locks );
125 MAKE_FUNCPTR( CRYPTO_set_id_callback );
126 MAKE_FUNCPTR( CRYPTO_set_locking_callback );
127 MAKE_FUNCPTR( ERR_free_strings );
128 MAKE_FUNCPTR( ERR_get_error );
129 MAKE_FUNCPTR( ERR_error_string );
130 MAKE_FUNCPTR( X509_STORE_CTX_get_ex_data );
131 MAKE_FUNCPTR( i2d_X509 );
132 MAKE_FUNCPTR( sk_value );
133 MAKE_FUNCPTR( sk_num );
134 #undef MAKE_FUNCPTR
136 static CRITICAL_SECTION *ssl_locks;
137 static unsigned int num_ssl_locks;
139 static unsigned long ssl_thread_id(void)
141 return GetCurrentThreadId();
144 static void ssl_lock_callback(int mode, int type, const char *file, int line)
146 if (mode & CRYPTO_LOCK)
147 EnterCriticalSection( &ssl_locks[type] );
148 else
149 LeaveCriticalSection( &ssl_locks[type] );
152 #endif
154 /* translate a unix error code into a winsock error code */
155 static int sock_get_error( int err )
157 #if !defined(__MINGW32__) && !defined (_MSC_VER)
158 switch (err)
160 case EINTR: return WSAEINTR;
161 case EBADF: return WSAEBADF;
162 case EPERM:
163 case EACCES: return WSAEACCES;
164 case EFAULT: return WSAEFAULT;
165 case EINVAL: return WSAEINVAL;
166 case EMFILE: return WSAEMFILE;
167 case EWOULDBLOCK: return WSAEWOULDBLOCK;
168 case EINPROGRESS: return WSAEINPROGRESS;
169 case EALREADY: return WSAEALREADY;
170 case ENOTSOCK: return WSAENOTSOCK;
171 case EDESTADDRREQ: return WSAEDESTADDRREQ;
172 case EMSGSIZE: return WSAEMSGSIZE;
173 case EPROTOTYPE: return WSAEPROTOTYPE;
174 case ENOPROTOOPT: return WSAENOPROTOOPT;
175 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
176 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
177 case EOPNOTSUPP: return WSAEOPNOTSUPP;
178 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
179 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
180 case EADDRINUSE: return WSAEADDRINUSE;
181 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
182 case ENETDOWN: return WSAENETDOWN;
183 case ENETUNREACH: return WSAENETUNREACH;
184 case ENETRESET: return WSAENETRESET;
185 case ECONNABORTED: return WSAECONNABORTED;
186 case EPIPE:
187 case ECONNRESET: return WSAECONNRESET;
188 case ENOBUFS: return WSAENOBUFS;
189 case EISCONN: return WSAEISCONN;
190 case ENOTCONN: return WSAENOTCONN;
191 case ESHUTDOWN: return WSAESHUTDOWN;
192 case ETOOMANYREFS: return WSAETOOMANYREFS;
193 case ETIMEDOUT: return WSAETIMEDOUT;
194 case ECONNREFUSED: return WSAECONNREFUSED;
195 case ELOOP: return WSAELOOP;
196 case ENAMETOOLONG: return WSAENAMETOOLONG;
197 case EHOSTDOWN: return WSAEHOSTDOWN;
198 case EHOSTUNREACH: return WSAEHOSTUNREACH;
199 case ENOTEMPTY: return WSAENOTEMPTY;
200 #ifdef EPROCLIM
201 case EPROCLIM: return WSAEPROCLIM;
202 #endif
203 #ifdef EUSERS
204 case EUSERS: return WSAEUSERS;
205 #endif
206 #ifdef EDQUOT
207 case EDQUOT: return WSAEDQUOT;
208 #endif
209 #ifdef ESTALE
210 case ESTALE: return WSAESTALE;
211 #endif
212 #ifdef EREMOTE
213 case EREMOTE: return WSAEREMOTE;
214 #endif
215 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
217 #endif
218 return err;
221 #ifdef SONAME_LIBSSL
222 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
224 unsigned char *buffer, *p;
225 int len;
226 BOOL malloc = FALSE;
227 PCCERT_CONTEXT ret;
229 p = NULL;
230 if ((len = pi2d_X509( cert, &p )) < 0) return NULL;
232 * SSL 0.9.7 and above malloc the buffer if it is null.
233 * however earlier version do not and so we would need to alloc the buffer.
235 * see the i2d_X509 man page for more details.
237 if (!p)
239 if (!(buffer = heap_alloc( len ))) return NULL;
240 p = buffer;
241 len = pi2d_X509( cert, &p );
243 else
245 buffer = p;
246 malloc = TRUE;
249 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
251 if (malloc) free( buffer );
252 else heap_free( buffer );
254 return ret;
257 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
258 WCHAR *server, DWORD security_flags )
260 BOOL ret;
261 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
262 PCCERT_CHAIN_CONTEXT chain;
263 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
264 char *server_auth[] = { oid_server_auth };
265 DWORD err = ERROR_SUCCESS;
267 TRACE("verifying %s\n", debugstr_w( server ));
268 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
269 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
270 if ((ret = CertGetCertificateChain( NULL, cert, NULL, store, &chainPara, 0,
271 NULL, &chain )))
273 if (chain->TrustStatus.dwErrorStatus)
275 if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_NOT_TIME_VALID)
277 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID))
278 err = ERROR_WINHTTP_SECURE_CERT_DATE_INVALID;
280 else if (chain->TrustStatus.dwErrorStatus &
281 CERT_TRUST_IS_UNTRUSTED_ROOT)
282 err = ERROR_WINHTTP_SECURE_INVALID_CA;
283 else if ((chain->TrustStatus.dwErrorStatus &
284 CERT_TRUST_IS_OFFLINE_REVOCATION) ||
285 (chain->TrustStatus.dwErrorStatus &
286 CERT_TRUST_REVOCATION_STATUS_UNKNOWN))
287 err = ERROR_WINHTTP_SECURE_CERT_REV_FAILED;
288 else if (chain->TrustStatus.dwErrorStatus & CERT_TRUST_IS_REVOKED)
289 err = ERROR_WINHTTP_SECURE_CERT_REVOKED;
290 else if (chain->TrustStatus.dwErrorStatus &
291 CERT_TRUST_IS_NOT_VALID_FOR_USAGE)
293 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE))
294 err = ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE;
296 else
297 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
299 else
301 CERT_CHAIN_POLICY_PARA policyPara;
302 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
303 CERT_CHAIN_POLICY_STATUS policyStatus;
305 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
306 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
307 sslExtraPolicyPara.pwszServerName = server;
308 policyPara.cbSize = sizeof(policyPara);
309 policyPara.dwFlags = 0;
310 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
311 ret = CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL,
312 chain, &policyPara,
313 &policyStatus );
314 /* Any error in the policy status indicates that the
315 * policy couldn't be verified.
317 if (ret && policyStatus.dwError)
319 if (policyStatus.dwError == CERT_E_CN_NO_MATCH)
321 if (!(security_flags & SECURITY_FLAG_IGNORE_CERT_CN_INVALID))
322 err = ERROR_WINHTTP_SECURE_CERT_CN_INVALID;
324 else
325 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
328 CertFreeCertificateChain( chain );
330 else
331 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
332 TRACE("returning %08x\n", err);
333 return err;
336 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
338 SSL *ssl;
339 WCHAR *server;
340 BOOL ret = FALSE;
341 netconn_t *conn;
343 ssl = pX509_STORE_CTX_get_ex_data( ctx, pSSL_get_ex_data_X509_STORE_CTX_idx() );
344 server = pSSL_get_ex_data( ssl, hostname_idx );
345 conn = pSSL_get_ex_data( ssl, conn_idx );
346 if (preverify_ok)
348 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
349 CERT_STORE_CREATE_NEW_FLAG, NULL );
351 if (store)
353 X509 *cert;
354 int i;
355 PCCERT_CONTEXT endCert = NULL;
357 ret = TRUE;
358 for (i = 0; ret && i < psk_num((struct stack_st *)ctx->chain); i++)
360 PCCERT_CONTEXT context;
362 cert = (X509 *)psk_value((struct stack_st *)ctx->chain, i);
363 if ((context = X509_to_cert_context( cert )))
365 if (i == 0)
366 ret = CertAddCertificateContextToStore( store, context,
367 CERT_STORE_ADD_ALWAYS, &endCert );
368 else
369 ret = CertAddCertificateContextToStore( store, context,
370 CERT_STORE_ADD_ALWAYS, NULL );
371 CertFreeCertificateContext( context );
374 if (!endCert) ret = FALSE;
375 if (ret)
377 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
378 conn->security_flags );
380 if (err)
382 pSSL_set_ex_data( ssl, error_idx, (void *)err );
383 ret = FALSE;
386 CertFreeCertificateContext( endCert );
387 CertCloseStore( store, 0 );
390 return ret;
392 #endif
394 BOOL netconn_init( netconn_t *conn, BOOL secure )
396 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
397 int i;
398 #endif
400 conn->socket = -1;
401 if (!secure) return TRUE;
403 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
404 EnterCriticalSection( &init_ssl_cs );
405 if (libssl_handle)
407 LeaveCriticalSection( &init_ssl_cs );
408 return TRUE;
410 if (!(libssl_handle = wine_dlopen( SONAME_LIBSSL, RTLD_NOW, NULL, 0 )))
412 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
413 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
414 LeaveCriticalSection( &init_ssl_cs );
415 return FALSE;
417 if (!(libcrypto_handle = wine_dlopen( SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0 )))
419 ERR("Trying to use SSL but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
420 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
421 LeaveCriticalSection( &init_ssl_cs );
422 return FALSE;
424 #define LOAD_FUNCPTR(x) \
425 if (!(p##x = wine_dlsym( libssl_handle, #x, NULL, 0 ))) \
427 ERR("Failed to load symbol %s\n", #x); \
428 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
429 LeaveCriticalSection( &init_ssl_cs ); \
430 return FALSE; \
432 LOAD_FUNCPTR( SSL_library_init );
433 LOAD_FUNCPTR( SSL_load_error_strings );
434 LOAD_FUNCPTR( SSLv23_method );
435 LOAD_FUNCPTR( SSL_CTX_free );
436 LOAD_FUNCPTR( SSL_CTX_new );
437 LOAD_FUNCPTR( SSL_new );
438 LOAD_FUNCPTR( SSL_free );
439 LOAD_FUNCPTR( SSL_set_fd );
440 LOAD_FUNCPTR( SSL_connect );
441 LOAD_FUNCPTR( SSL_shutdown );
442 LOAD_FUNCPTR( SSL_write );
443 LOAD_FUNCPTR( SSL_read );
444 LOAD_FUNCPTR( SSL_get_error );
445 LOAD_FUNCPTR( SSL_get_ex_new_index );
446 LOAD_FUNCPTR( SSL_get_ex_data );
447 LOAD_FUNCPTR( SSL_set_ex_data );
448 LOAD_FUNCPTR( SSL_get_ex_data_X509_STORE_CTX_idx );
449 LOAD_FUNCPTR( SSL_get_verify_result );
450 LOAD_FUNCPTR( SSL_get_peer_certificate );
451 LOAD_FUNCPTR( SSL_CTX_set_default_verify_paths );
452 LOAD_FUNCPTR( SSL_CTX_set_verify );
453 #undef LOAD_FUNCPTR
455 #define LOAD_FUNCPTR(x) \
456 if (!(p##x = wine_dlsym( libcrypto_handle, #x, NULL, 0 ))) \
458 ERR("Failed to load symbol %s\n", #x); \
459 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR ); \
460 LeaveCriticalSection( &init_ssl_cs ); \
461 return FALSE; \
463 LOAD_FUNCPTR( CRYPTO_num_locks );
464 LOAD_FUNCPTR( CRYPTO_set_id_callback );
465 LOAD_FUNCPTR( CRYPTO_set_locking_callback );
466 LOAD_FUNCPTR( ERR_free_strings );
467 LOAD_FUNCPTR( ERR_get_error );
468 LOAD_FUNCPTR( ERR_error_string );
469 LOAD_FUNCPTR( X509_STORE_CTX_get_ex_data );
470 LOAD_FUNCPTR( i2d_X509 );
471 LOAD_FUNCPTR( sk_value );
472 LOAD_FUNCPTR( sk_num );
473 #undef LOAD_FUNCPTR
475 pSSL_library_init();
476 pSSL_load_error_strings();
478 method = pSSLv23_method();
479 ctx = pSSL_CTX_new( method );
480 if (!pSSL_CTX_set_default_verify_paths( ctx ))
482 ERR("SSL_CTX_set_default_verify_paths failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
483 set_last_error( ERROR_OUTOFMEMORY );
484 LeaveCriticalSection( &init_ssl_cs );
485 return FALSE;
487 hostname_idx = pSSL_get_ex_new_index( 0, (void *)"hostname index", NULL, NULL, NULL );
488 if (hostname_idx == -1)
490 ERR("SSL_get_ex_new_index failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
491 set_last_error( ERROR_OUTOFMEMORY );
492 LeaveCriticalSection( &init_ssl_cs );
493 return FALSE;
495 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
496 if (error_idx == -1)
498 ERR("SSL_get_ex_new_index 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 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
504 if (conn_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 pSSL_CTX_set_verify( ctx, SSL_VERIFY_PEER, netconn_secure_verify );
513 pCRYPTO_set_id_callback(ssl_thread_id);
514 num_ssl_locks = pCRYPTO_num_locks();
515 ssl_locks = HeapAlloc(GetProcessHeap(), 0, num_ssl_locks * sizeof(CRITICAL_SECTION));
516 if (!ssl_locks)
518 set_last_error( ERROR_OUTOFMEMORY );
519 LeaveCriticalSection( &init_ssl_cs );
520 return FALSE;
522 for (i = 0; i < num_ssl_locks; i++) InitializeCriticalSection( &ssl_locks[i] );
523 pCRYPTO_set_locking_callback(ssl_lock_callback);
525 LeaveCriticalSection( &init_ssl_cs );
526 #else
527 WARN("SSL support not compiled in.\n");
528 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
529 return FALSE;
530 #endif
531 return TRUE;
534 void netconn_unload( void )
536 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
537 if (libcrypto_handle)
539 pERR_free_strings();
540 wine_dlclose( libcrypto_handle, NULL, 0 );
542 if (libssl_handle)
544 if (ctx)
545 pSSL_CTX_free( ctx );
546 wine_dlclose( libssl_handle, NULL, 0 );
548 if (ssl_locks)
550 int i;
551 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
552 HeapFree( GetProcessHeap(), 0, ssl_locks );
554 #endif
557 BOOL netconn_connected( netconn_t *conn )
559 return (conn->socket != -1);
562 BOOL netconn_create( netconn_t *conn, int domain, int type, int protocol )
564 if ((conn->socket = socket( domain, type, protocol )) == -1)
566 WARN("unable to create socket (%s)\n", strerror(errno));
567 set_last_error( sock_get_error( errno ) );
568 return FALSE;
570 return TRUE;
573 BOOL netconn_close( netconn_t *conn )
575 int res;
577 #ifdef SONAME_LIBSSL
578 if (conn->secure)
580 heap_free( conn->peek_msg_mem );
581 conn->peek_msg_mem = NULL;
582 conn->peek_msg = NULL;
583 conn->peek_len = 0;
585 pSSL_shutdown( conn->ssl_conn );
586 pSSL_free( conn->ssl_conn );
588 conn->ssl_conn = NULL;
589 conn->secure = FALSE;
591 #endif
592 res = closesocket( conn->socket );
593 conn->socket = -1;
594 if (res == -1)
596 set_last_error( sock_get_error( errno ) );
597 return FALSE;
599 return TRUE;
602 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
604 BOOL ret = FALSE;
605 int res = 0, state;
607 if (timeout > 0)
609 state = 1;
610 ioctlsocket( conn->socket, FIONBIO, &state );
612 if (connect( conn->socket, sockaddr, addr_len ) < 0)
614 res = sock_get_error( errno );
615 if (res == WSAEWOULDBLOCK || res == WSAEINPROGRESS)
617 struct pollfd pfd;
619 pfd.fd = conn->socket;
620 pfd.events = POLLOUT;
621 if (poll( &pfd, 1, timeout ) > 0)
622 ret = TRUE;
623 else
624 res = sock_get_error( errno );
627 else
628 ret = TRUE;
629 if (timeout > 0)
631 state = 0;
632 ioctlsocket( conn->socket, FIONBIO, &state );
634 if (!ret)
636 WARN("unable to connect to host (%d)\n", res);
637 set_last_error( res );
639 return ret;
642 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
644 #ifdef SONAME_LIBSSL
645 if (!(conn->ssl_conn = pSSL_new( ctx )))
647 ERR("SSL_new failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
648 set_last_error( ERROR_OUTOFMEMORY );
649 goto fail;
651 if (!pSSL_set_ex_data( conn->ssl_conn, hostname_idx, hostname ))
653 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
654 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
655 goto fail;
657 if (!pSSL_set_ex_data( conn->ssl_conn, conn_idx, conn ))
659 ERR("SSL_set_ex_data failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
660 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
661 return FALSE;
663 if (!pSSL_set_fd( conn->ssl_conn, conn->socket ))
665 ERR("SSL_set_fd failed: %s\n", pERR_error_string( pERR_get_error(), 0 ));
666 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
667 goto fail;
669 if (pSSL_connect( conn->ssl_conn ) <= 0)
671 DWORD err;
673 err = (DWORD_PTR)pSSL_get_ex_data( conn->ssl_conn, error_idx );
674 if (!err) err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
675 ERR("couldn't verify server certificate (%d)\n", err);
676 set_last_error( err );
677 goto fail;
679 TRACE("established SSL connection\n");
680 conn->secure = TRUE;
681 return TRUE;
683 fail:
684 if (conn->ssl_conn)
686 pSSL_shutdown( conn->ssl_conn );
687 pSSL_free( conn->ssl_conn );
688 conn->ssl_conn = NULL;
690 #endif
691 return FALSE;
694 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
696 if (!netconn_connected( conn )) return FALSE;
697 if (conn->secure)
699 #ifdef SONAME_LIBSSL
700 if (flags) FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
701 *sent = pSSL_write( conn->ssl_conn, msg, len );
702 if (*sent < 1 && len) return FALSE;
703 return TRUE;
704 #else
705 return FALSE;
706 #endif
708 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
710 set_last_error( sock_get_error( errno ) );
711 return FALSE;
713 return TRUE;
716 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
718 int ret;
720 *recvd = 0;
721 if (!netconn_connected( conn )) return FALSE;
722 if (!len) return TRUE;
724 if (conn->secure)
726 #ifdef SONAME_LIBSSL
727 if (flags & ~(MSG_PEEK | MSG_WAITALL))
728 FIXME("SSL_read does not support the following flags: %08x\n", flags);
730 /* this ugly hack is all for MSG_PEEK */
731 if (flags & MSG_PEEK && !conn->peek_msg)
733 if (!(conn->peek_msg = conn->peek_msg_mem = heap_alloc( len + 1 ))) return FALSE;
735 else if (flags & MSG_PEEK && conn->peek_msg)
737 if (len < conn->peek_len) FIXME("buffer isn't big enough, should we wrap?\n");
738 *recvd = min( len, conn->peek_len );
739 memcpy( buf, conn->peek_msg, *recvd );
740 return TRUE;
742 else if (conn->peek_msg)
744 *recvd = min( len, conn->peek_len );
745 memcpy( buf, conn->peek_msg, *recvd );
746 conn->peek_len -= *recvd;
747 conn->peek_msg += *recvd;
749 if (conn->peek_len == 0)
751 heap_free( conn->peek_msg_mem );
752 conn->peek_msg_mem = NULL;
753 conn->peek_msg = NULL;
755 /* check if we have enough data from the peek buffer */
756 if (!(flags & MSG_WAITALL) || (*recvd == len)) return TRUE;
758 ret = pSSL_read( conn->ssl_conn, (char *)buf + *recvd, len - *recvd );
759 if (ret < 0)
760 return FALSE;
762 /* check if EOF was received */
763 if (!ret && (pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_ZERO_RETURN ||
764 pSSL_get_error( conn->ssl_conn, ret ) == SSL_ERROR_SYSCALL ))
766 netconn_close( conn );
767 return TRUE;
769 if (flags & MSG_PEEK) /* must copy into buffer */
771 conn->peek_len = ret;
772 if (!ret)
774 heap_free( conn->peek_msg_mem );
775 conn->peek_msg_mem = NULL;
776 conn->peek_msg = NULL;
778 else memcpy( conn->peek_msg, buf, ret );
780 *recvd = ret;
781 return TRUE;
782 #else
783 return FALSE;
784 #endif
786 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
788 set_last_error( sock_get_error( errno ) );
789 return FALSE;
791 return TRUE;
794 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
796 #ifdef FIONREAD
797 int ret, unread;
798 #endif
799 *available = 0;
800 if (!netconn_connected( conn )) return FALSE;
802 if (conn->secure)
804 #ifdef SONAME_LIBSSL
805 if (conn->peek_msg) *available = conn->peek_len;
806 #endif
807 return TRUE;
809 #ifdef FIONREAD
810 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
811 #endif
812 return TRUE;
815 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
817 struct pollfd pfd;
818 BOOL ret = FALSE;
819 DWORD recvd = 0;
821 if (!netconn_connected( conn )) return FALSE;
823 if (conn->secure)
825 #ifdef SONAME_LIBSSL
826 while (recvd < *buflen)
828 int dummy;
829 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
831 set_last_error( ERROR_CONNECTION_ABORTED );
832 break;
834 if (buffer[recvd] == '\n')
836 ret = TRUE;
837 break;
839 if (buffer[recvd] != '\r') recvd++;
841 if (ret)
843 buffer[recvd++] = 0;
844 *buflen = recvd;
845 TRACE("received line %s\n", debugstr_a(buffer));
847 return ret;
848 #else
849 return FALSE;
850 #endif
853 pfd.fd = conn->socket;
854 pfd.events = POLLIN;
855 while (recvd < *buflen)
857 int timeout, res;
858 struct timeval tv;
859 socklen_t len = sizeof(tv);
861 if ((res = getsockopt( conn->socket, SOL_SOCKET, SO_RCVTIMEO, (void*)&tv, &len ) != -1))
862 timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
863 else
864 timeout = -1;
865 if (poll( &pfd, 1, timeout ) > 0)
867 if ((res = recv( conn->socket, &buffer[recvd], 1, 0 )) <= 0)
869 if (res == -1) set_last_error( sock_get_error( errno ) );
870 break;
872 if (buffer[recvd] == '\n')
874 ret = TRUE;
875 break;
877 if (buffer[recvd] != '\r') recvd++;
879 else
881 set_last_error( ERROR_WINHTTP_TIMEOUT );
882 break;
885 if (ret)
887 buffer[recvd++] = 0;
888 *buflen = recvd;
889 TRACE("received line %s\n", debugstr_a(buffer));
891 return ret;
894 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
896 int res;
897 struct timeval tv;
899 /* value is in milliseconds, convert to struct timeval */
900 tv.tv_sec = value / 1000;
901 tv.tv_usec = (value % 1000) * 1000;
903 if ((res = setsockopt( netconn->socket, SOL_SOCKET, send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv, sizeof(tv) ) == -1))
905 WARN("setsockopt failed (%s)\n", strerror( errno ));
906 return sock_get_error( errno );
908 return ERROR_SUCCESS;
911 static DWORD resolve_hostname( WCHAR *hostnameW, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len )
913 char *hostname;
914 #ifdef HAVE_GETADDRINFO
915 struct addrinfo *res, hints;
916 int ret;
917 #else
918 struct hostent *he;
919 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
920 #endif
922 if (!(hostname = strdupWA( hostnameW ))) return ERROR_OUTOFMEMORY;
924 #ifdef HAVE_GETADDRINFO
925 memset( &hints, 0, sizeof(struct addrinfo) );
926 /* Prefer IPv4 to IPv6 addresses, since some web servers do not listen on
927 * their IPv6 addresses even though they have IPv6 addresses in the DNS.
929 hints.ai_family = AF_INET;
931 ret = getaddrinfo( hostname, NULL, &hints, &res );
932 if (ret != 0)
934 TRACE("failed to get IPv4 address of %s (%s), retrying with IPv6\n", debugstr_w(hostnameW), gai_strerror(ret));
935 hints.ai_family = AF_INET6;
936 ret = getaddrinfo( hostname, NULL, &hints, &res );
937 if (ret != 0)
939 TRACE("failed to get address of %s (%s)\n", debugstr_w(hostnameW), gai_strerror(ret));
940 heap_free( hostname );
941 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
944 heap_free( hostname );
945 if (*sa_len < res->ai_addrlen)
947 WARN("address too small\n");
948 freeaddrinfo( res );
949 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
951 *sa_len = res->ai_addrlen;
952 memcpy( sa, res->ai_addr, res->ai_addrlen );
953 /* Copy port */
954 switch (res->ai_family)
956 case AF_INET:
957 ((struct sockaddr_in *)sa)->sin_port = htons( port );
958 break;
959 case AF_INET6:
960 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
961 break;
964 freeaddrinfo( res );
965 return ERROR_SUCCESS;
966 #else
967 EnterCriticalSection( &cs_gethostbyname );
969 he = gethostbyname( hostname );
970 heap_free( hostname );
971 if (!he)
973 TRACE("failed to get address of %s (%d)\n", debugstr_w(hostnameW), h_errno);
974 LeaveCriticalSection( &cs_gethostbyname );
975 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
977 if (*sa_len < sizeof(struct sockaddr_in))
979 WARN("address too small\n");
980 LeaveCriticalSection( &cs_gethostbyname );
981 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
983 *sa_len = sizeof(struct sockaddr_in);
984 memset( sa, 0, sizeof(struct sockaddr_in) );
985 memcpy( &sin->sin_addr, he->h_addr, he->h_length );
986 sin->sin_family = he->h_addrtype;
987 sin->sin_port = htons( port );
989 LeaveCriticalSection( &cs_gethostbyname );
990 return ERROR_SUCCESS;
991 #endif
994 struct resolve_args
996 WCHAR *hostname;
997 INTERNET_PORT port;
998 struct sockaddr *sa;
999 socklen_t *sa_len;
1002 static DWORD CALLBACK resolve_proc( LPVOID arg )
1004 struct resolve_args *ra = arg;
1005 return resolve_hostname( ra->hostname, ra->port, ra->sa, ra->sa_len );
1008 BOOL netconn_resolve( WCHAR *hostname, INTERNET_PORT port, struct sockaddr *sa, socklen_t *sa_len, int timeout )
1010 DWORD ret;
1012 if (timeout)
1014 DWORD status;
1015 HANDLE thread;
1016 struct resolve_args ra;
1018 ra.hostname = hostname;
1019 ra.port = port;
1020 ra.sa = sa;
1021 ra.sa_len = sa_len;
1023 thread = CreateThread( NULL, 0, resolve_proc, &ra, 0, NULL );
1024 if (!thread) return FALSE;
1026 status = WaitForSingleObject( thread, timeout );
1027 if (status == WAIT_OBJECT_0) GetExitCodeThread( thread, &ret );
1028 else ret = ERROR_WINHTTP_TIMEOUT;
1029 CloseHandle( thread );
1031 else ret = resolve_hostname( hostname, port, sa, sa_len );
1033 if (ret)
1035 set_last_error( ret );
1036 return FALSE;
1038 return TRUE;
1041 const void *netconn_get_certificate( netconn_t *conn )
1043 #ifdef SONAME_LIBSSL
1044 X509 *cert;
1045 const CERT_CONTEXT *ret;
1047 if (!conn->secure) return NULL;
1049 if (!(cert = pSSL_get_peer_certificate( conn->ssl_conn ))) return NULL;
1050 ret = X509_to_cert_context( cert );
1051 return ret;
1052 #else
1053 return NULL;
1054 #endif