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
20 #include "wine/port.h"
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_SOCKET_H
28 # include <sys/socket.h>
30 #ifdef HAVE_SYS_IOCTL_H
31 # include <sys/ioctl.h>
33 #ifdef HAVE_SYS_FILIO_H
34 # include <sys/filio.h>
39 #ifdef HAVE_OPENSSL_SSL_H
40 # include <openssl/ssl.h>
45 #define NONAMELESSUNION
47 #include "wine/debug.h"
48 #include "wine/library.h"
55 #include "winhttp_private.h"
57 /* to avoid conflicts with the Unix socket headers */
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 };
79 #include <openssl/err.h>
81 static CRITICAL_SECTION init_ssl_cs;
82 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
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;
96 static int hostname_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 );
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] );
149 LeaveCriticalSection( &ssl_locks[type] );
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)
160 case EINTR: return WSAEINTR;
161 case EBADF: return WSAEBADF;
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;
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;
201 case EPROCLIM: return WSAEPROCLIM;
204 case EUSERS: return WSAEUSERS;
207 case EDQUOT: return WSAEDQUOT;
210 case ESTALE: return WSAESTALE;
213 case EREMOTE: return WSAEREMOTE;
215 default: errno = err; perror( "sock_set_error" ); return WSAEFAULT;
222 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
224 unsigned char *buffer, *p;
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.
239 if (!(buffer = heap_alloc( len ))) return NULL;
241 len = pi2d_X509( cert, &p );
249 ret = CertCreateCertificateContext( X509_ASN_ENCODING, buffer, len );
251 if (malloc) free( buffer );
252 else heap_free( buffer );
257 static DWORD netconn_verify_cert( PCCERT_CONTEXT cert, HCERTSTORE store,
258 WCHAR *server, DWORD security_flags )
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,
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;
297 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
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,
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;
325 err = ERROR_WINHTTP_SECURE_INVALID_CERT;
328 CertFreeCertificateChain( chain );
331 err = ERROR_WINHTTP_SECURE_CHANNEL_ERROR;
332 TRACE("returning %08x\n", err);
336 static int netconn_secure_verify( int preverify_ok, X509_STORE_CTX *ctx )
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 );
348 HCERTSTORE store = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, 0,
349 CERT_STORE_CREATE_NEW_FLAG, NULL );
355 PCCERT_CONTEXT endCert = NULL;
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 )))
366 ret = CertAddCertificateContextToStore( store, context,
367 CERT_STORE_ADD_ALWAYS, &endCert );
369 ret = CertAddCertificateContextToStore( store, context,
370 CERT_STORE_ADD_ALWAYS, NULL );
371 CertFreeCertificateContext( context );
374 if (!endCert) ret = FALSE;
377 DWORD_PTR err = netconn_verify_cert( endCert, store, server,
378 conn->security_flags );
382 pSSL_set_ex_data( ssl, error_idx, (void *)err );
386 CertFreeCertificateContext( endCert );
387 CertCloseStore( store, 0 );
394 BOOL netconn_init( netconn_t *conn, BOOL secure )
396 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
401 if (!secure) return TRUE;
403 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
404 EnterCriticalSection( &init_ssl_cs );
407 LeaveCriticalSection( &init_ssl_cs );
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 );
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 );
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 ); \
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 );
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 ); \
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 );
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 );
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 );
495 error_idx = pSSL_get_ex_new_index( 0, (void *)"error index", NULL, NULL, NULL );
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 );
503 conn_idx = pSSL_get_ex_new_index( 0, (void *)"netconn index", NULL, NULL, NULL );
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 );
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));
518 set_last_error( ERROR_OUTOFMEMORY );
519 LeaveCriticalSection( &init_ssl_cs );
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 );
527 WARN("SSL support not compiled in.\n");
528 set_last_error( ERROR_WINHTTP_SECURE_CHANNEL_ERROR );
534 void netconn_unload( void )
536 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
537 if (libcrypto_handle)
540 wine_dlclose( libcrypto_handle, NULL, 0 );
545 pSSL_CTX_free( ctx );
546 wine_dlclose( libssl_handle, NULL, 0 );
551 for (i = 0; i < num_ssl_locks; i++) DeleteCriticalSection( &ssl_locks[i] );
552 HeapFree( GetProcessHeap(), 0, ssl_locks );
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 ) );
573 BOOL netconn_close( netconn_t *conn )
580 heap_free( conn->peek_msg_mem );
581 conn->peek_msg_mem = NULL;
582 conn->peek_msg = NULL;
585 pSSL_shutdown( conn->ssl_conn );
586 pSSL_free( conn->ssl_conn );
588 conn->ssl_conn = NULL;
589 conn->secure = FALSE;
592 res = closesocket( conn->socket );
596 set_last_error( sock_get_error( errno ) );
602 BOOL netconn_connect( netconn_t *conn, const struct sockaddr *sockaddr, unsigned int addr_len, int timeout )
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)
619 pfd.fd = conn->socket;
620 pfd.events = POLLOUT;
621 if (poll( &pfd, 1, timeout ) > 0)
624 res = sock_get_error( errno );
632 ioctlsocket( conn->socket, FIONBIO, &state );
636 WARN("unable to connect to host (%d)\n", res);
637 set_last_error( res );
642 BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname )
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 );
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 );
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 );
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 );
669 if (pSSL_connect( conn->ssl_conn ) <= 0)
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 );
679 TRACE("established SSL connection\n");
686 pSSL_shutdown( conn->ssl_conn );
687 pSSL_free( conn->ssl_conn );
688 conn->ssl_conn = NULL;
694 BOOL netconn_send( netconn_t *conn, const void *msg, size_t len, int flags, int *sent )
696 if (!netconn_connected( conn )) return FALSE;
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;
708 if ((*sent = send( conn->socket, msg, len, flags )) == -1)
710 set_last_error( sock_get_error( errno ) );
716 BOOL netconn_recv( netconn_t *conn, void *buf, size_t len, int flags, int *recvd )
721 if (!netconn_connected( conn )) return FALSE;
722 if (!len) return TRUE;
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 );
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 );
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 );
769 if (flags & MSG_PEEK) /* must copy into buffer */
771 conn->peek_len = 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 );
786 if ((*recvd = recv( conn->socket, buf, len, flags )) == -1)
788 set_last_error( sock_get_error( errno ) );
794 BOOL netconn_query_data_available( netconn_t *conn, DWORD *available )
800 if (!netconn_connected( conn )) return FALSE;
805 if (conn->peek_msg) *available = conn->peek_len;
810 if (!(ret = ioctlsocket( conn->socket, FIONREAD, &unread ))) *available = unread;
815 BOOL netconn_get_next_line( netconn_t *conn, char *buffer, DWORD *buflen )
821 if (!netconn_connected( conn )) return FALSE;
826 while (recvd < *buflen)
829 if (!netconn_recv( conn, &buffer[recvd], 1, 0, &dummy ))
831 set_last_error( ERROR_CONNECTION_ABORTED );
834 if (buffer[recvd] == '\n')
839 if (buffer[recvd] != '\r') recvd++;
845 TRACE("received line %s\n", debugstr_a(buffer));
853 pfd.fd = conn->socket;
855 while (recvd < *buflen)
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;
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 ) );
872 if (buffer[recvd] == '\n')
877 if (buffer[recvd] != '\r') recvd++;
881 set_last_error( ERROR_WINHTTP_TIMEOUT );
889 TRACE("received line %s\n", debugstr_a(buffer));
894 DWORD netconn_set_timeout( netconn_t *netconn, BOOL send, int value )
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 )
914 #ifdef HAVE_GETADDRINFO
915 struct addrinfo *res, hints;
919 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
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 );
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 );
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");
949 return ERROR_WINHTTP_NAME_NOT_RESOLVED;
951 *sa_len = res->ai_addrlen;
952 memcpy( sa, res->ai_addr, res->ai_addrlen );
954 switch (res->ai_family)
957 ((struct sockaddr_in *)sa)->sin_port = htons( port );
960 ((struct sockaddr_in6 *)sa)->sin6_port = htons( port );
965 return ERROR_SUCCESS;
967 EnterCriticalSection( &cs_gethostbyname );
969 he = gethostbyname( hostname );
970 heap_free( hostname );
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;
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 )
1016 struct resolve_args ra;
1018 ra.hostname = hostname;
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 );
1035 set_last_error( ret );
1041 const void *netconn_get_certificate( netconn_t *conn )
1043 #ifdef SONAME_LIBSSL
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 );